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