|
| 1 | +import type { AuthCodesRepository } from '@/repositories/auth-codes-repository' |
| 2 | +import type { UsersRepository } from '@/repositories/users-repository' |
| 3 | +import { InvalidCredentialsError } from '../errors/invalid-credentials-error' |
| 4 | +import { UserNotExistsError } from '../errors/user-not-exists-error' |
| 5 | + |
| 6 | +import { hash } from 'bcryptjs' |
| 7 | +import dayjs from 'dayjs' |
| 8 | + |
| 9 | +interface ResetPasswordServiceRequest { |
| 10 | + code: number |
| 11 | + userId: string |
| 12 | + password: string |
| 13 | +} |
| 14 | + |
| 15 | +export class ResetPasswordService { |
| 16 | + constructor( |
| 17 | + private usersRepository: UsersRepository, |
| 18 | + private authCodes: AuthCodesRepository, |
| 19 | + ) {} |
| 20 | + |
| 21 | + async execute({ code, userId, password }: ResetPasswordServiceRequest) { |
| 22 | + const isValidCode = await this.authCodes.getByCodeAndUser(userId, code) |
| 23 | + |
| 24 | + if (!isValidCode) { |
| 25 | + throw new InvalidCredentialsError() |
| 26 | + } |
| 27 | + |
| 28 | + const date = dayjs().diff(isValidCode.createdAt, 'milliseconds') |
| 29 | + const dateInHours = date / 1000 / 60 / 60 |
| 30 | + const isCodeGeneratedMoreThanFiveHours = dateInHours >= 5 |
| 31 | + |
| 32 | + if (isCodeGeneratedMoreThanFiveHours) { |
| 33 | + throw new InvalidCredentialsError() |
| 34 | + } |
| 35 | + |
| 36 | + const user = await this.usersRepository.findById(userId) |
| 37 | + |
| 38 | + if (!user) { |
| 39 | + throw new UserNotExistsError() |
| 40 | + } |
| 41 | + |
| 42 | + password = await hash(password, 10) |
| 43 | + |
| 44 | + const alteredPassword = await this.usersRepository.updateById(user.id, { |
| 45 | + password, |
| 46 | + }) |
| 47 | + |
| 48 | + await this.authCodes.deleteByCode(code) |
| 49 | + |
| 50 | + return { alteredPassword } |
| 51 | + } |
| 52 | +} |
0 commit comments