Skip to content

Commit 18e92d2

Browse files
committed
feat: Implementar o reset de senha
1 parent 9f653e0 commit 18e92d2

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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

Comments
 (0)