| 1 | import { hash, verify } from 'argon2'; |
| 2 | import { JwtPayload, sign |
| 3 | import { prisma } |
| 4 | |
| 5 | import { HttpException, HttpStatus |
| 6 | import { ConfigService } |
| 7 | import { createId } |
| 8 | |
| 9 | import { LoginDTO } |
| 10 | import { RegisterDTO } |
| 11 | import { UserEntity } |
| 12 | |
| 13 | @Injectable() |
| 14 | export class AuthService |
| 15 | constructor(private service |
| 16 | |
| 17 | async login(body |
| 18 | const { password, |
| 19 | const user = |
| 20 | where: { email: { |
| 21 | }); |
| 22 | if (!user) |
| 23 | throw new HttpException( |
| 24 | 'No user found with given email.', |
| 25 | HttpStatus.NOT_FOUND, |
| 26 | ); |
| 27 | |
| 28 | const isPasswordCorrect = |
| 29 | if (isPasswordCorrect === |
| 30 | throw new HttpException( |
| 31 | const token = |
| 32 | return { |
| 33 | token, |
| 34 | user: { |
| 35 | name: user.name |
| 36 | email: user.email |
| 37 | id: user.id |
| 38 | }, |
| 39 | }; |
| 40 | } |
| 41 | |
| 42 | async register(body |
| 43 | if (process.env |
| 44 | throw new HttpException( |
| 45 | 'We do not allow new accounts', |
| 46 | HttpStatus.BAD_REQUEST, |
| 47 | ); |
| 48 | const { email, |
| 49 | const existingUser = |
| 50 | where: { email: { |
| 51 | }); |
| 52 | |
| 53 | if (existingUser) { |
| 54 | throw new HttpException( |
| 55 | 'Email address is already in use.', |
| 56 | HttpStatus.CONFLICT, |
| 57 | ); |
| 58 | } |
| 59 | |
| 60 | const hashedPassword = |
| 61 | const newUser = |
| 62 | data: { |
| 63 | id: `user_${createId |
| 64 | name, |
| 65 | password: hashedPassword, |
| 66 | email, |
| 67 | }, |
| 68 | }); |
| 69 | const token = |
| 70 | return { |
| 71 | token, |
| 72 | user: { |
| 73 | id: newUser.id |
| 74 | email, |
| 75 | name, |
| 76 | }, |
| 77 | }; |
| 78 | } |
| 79 | |
| 80 | async verify(token |
| 81 | try { |
| 82 | const payload = |
| 83 | const user = |
| 84 | where: { id: payload |
| 85 | }); |
| 86 | if (!user) |
| 87 | return user; |
| 88 | } catch (e) |
| 89 | throw Error('Unauthorized' |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | async hydrate(userId |
| 94 | const user = |
| 95 | where: { id: userId |
| 96 | select: { |
| 97 | id: true, |
| 98 | name: true, |
| 99 | email: true, |
| 100 | }, |
| 101 | }); |
| 102 | if (!user) |
| 103 | return { name: |
| 104 | } |
| 105 | } |