Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🍂 fix/restore-password #31

Open
wants to merge 2 commits into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions src/modules/users/infra/http/controller/UsersController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import UpdateUserService from '@modules/users/services/UpdateUserService';
import ConfirmUserService from '@modules/users/services/ConfirmUserService';
import RestorePasswordService from '@modules/users/services/RestorePasswordService';
import UpdatePasswordService from '@modules/users/services/UpdatePasswordService';
import ConfirmTokenService from '@modules/users/services/ConfirmTokenUserService';

export default class UserController {
public async create(req: Request, res: Response): Promise<Response> {
Expand Down Expand Up @@ -119,12 +120,22 @@ export default class UserController {
return res.status(200).json({ message: 'email sent!' })
}

public async checkToken(req: Request, res: Response): Promise<Response> {
const { email, token } = req.body

const checkToken = container.resolve(ConfirmTokenService);

const status = await checkToken.execute({email, token});

return res.status(200).json(status)
}

public async changePassword(req:Request, res: Response): Promise<Response> {
const { token, email, newPassword } = req.body;
const { email, newPassword } = req.body;

const changePassword = container.resolve(UpdatePasswordService);

const user = await changePassword.execute({ email, token, newPassword });
const user = await changePassword.execute({ email, newPassword });

return res.status(200).json(user);
}
Expand Down
2 changes: 2 additions & 0 deletions src/modules/users/infra/http/routes/users.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ usersRoutes.patch('/confirm/:userId', usersController.confirm);

usersRoutes.patch('/restore-password', usersController.requestTokenToRestorePassword);

usersRoutes.patch('/confirm-token', usersController.checkToken)

usersRoutes.patch('/update-password', usersController.changePassword);

export default usersRoutes;
32 changes: 32 additions & 0 deletions src/modules/users/services/ConfirmTokenUserService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { User } from "@prisma/client";
import IHashProvider from "@shared/container/providers/HashProvider/models/IHashProvider";
import AppError from "@shared/errors/AppError";
import { inject, injectable } from "tsyringe";
import IUsersRepository from "../repositories/IUsersRepository";

interface IRequest {
email: string,
token: string
}

@injectable()
export default class ConfirmTokenService {
constructor(
@inject('UsersRepository')
private usersRepository: IUsersRepository,

@inject('HashProvider')
private hashProvider: IHashProvider
) { }
public async execute({ email, token }: IRequest): Promise<Boolean> {
const user = await this.usersRepository.findByEmailWithRelations(email) as User;

if (!user) throw new AppError('There is no user with this Email')

const tokenMatched = await this.hashProvider.compareHash(token, user.restorePasswordToken as string)

if (!tokenMatched) throw new AppError('Incorrect Token')

return true
}
}
42 changes: 22 additions & 20 deletions src/modules/users/services/CreateUserService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export default class CreateUserService {

@inject('HashProvider')
private hashProvider: IHashProvider,

@inject('MailProvider')
private mailProvider: IMailProvider
) {}
Expand All @@ -48,6 +48,7 @@ export default class CreateUserService {
occupation,
pep
}: IRequest): Promise<Omit<User, 'password'>> {

const userAlreadyExists = await this.usersRepository.findByEmailorPhone(
email,
phone
Expand All @@ -56,32 +57,19 @@ export default class CreateUserService {
if (userAlreadyExists) {
throw new AppError('User with same email, phone or cpf already exists');
}

const hashedPassword = await this.hashProvider.generateHash(password);

const countryObject = phoneObject.find((country) => (country.code === ddd))

if (!countryObject) throw new AppError('There is no country with this ddd ');

const countryMasks = countryObject?.mask

if (!ValidPhone(phone, countryMasks as string[])) {
throw new AppError('This phone is not valid in your country', 400)
}

const user = await this.usersRepository.create({
name,
email: email.toLowerCase(),
password: hashedPassword,
ddd,
phone,
birthDate,
monthly_income,
nationality,
occupation,
pep
});

const templateDataFile = path.resolve(__dirname, '..', 'views', 'create_account.hbs');

try {
Expand All @@ -97,12 +85,26 @@ export default class CreateUserService {
},
});
} catch {
throw new AppError('You cannot create a account with this email');
throw new AppError('Error in sendind email, invalid credentials');
} finally {
// eslint-disable-next-line no-console
console.log('Email sent!');
}

const user = await this.usersRepository.create({
name,
email: email.toLowerCase(),
password: hashedPassword,
ddd,
phone,
birthDate,
monthly_income,
nationality,
occupation,
pep
});


const { password: _, ...userWithoutPassword } = user;

return userWithoutPassword;
Expand Down
4 changes: 3 additions & 1 deletion src/modules/users/services/RestorePasswordService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ export default class RestorePasswordService {

const userId = user.id

await this.usersRepository.createToken(userId, token)
const hashedToken = await this.hashProvider.generateHash(token);

await this.usersRepository.createToken(userId, hashedToken)

const templateDataFile = path.resolve(
__dirname,
Expand Down
16 changes: 10 additions & 6 deletions src/modules/users/services/UpdatePasswordService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import { inject, injectable } from 'tsyringe';
import IUsersRepository from '../repositories/IUsersRepository';

interface IRequest {
email: string;
token: string;
email: string;
newPassword: string;
}

Expand All @@ -20,15 +20,19 @@ export default class UpdatePasswordService {
private hashProvider: IHashProvider
) {}

public async execute({ email, token, newPassword }: IRequest): Promise<Omit<User, 'password'>> {
const userWithThisEmail = await this.usersRepository.findByEmailWithRelations(email)
if (token !== userWithThisEmail?.restorePasswordToken) {
throw new AppError('You cannot change password with this token')
}
public async execute({ token, email, newPassword }: IRequest): Promise<Omit<User, 'password'>> {
const userWithThisEmail = await this.usersRepository.findByEmailWithRelations(email) as User;
// if (token !== userWithThisEmail?.restorePasswordToken) {
// throw new AppError('You cannot change password with this token')
// }
if (newPassword === userWithThisEmail.password) {
throw new AppError('A nova senha deve ser diferente da senha anterior.')
}

const tokenMatched = await this.hashProvider.compareHash(token, userWithThisEmail.restorePasswordToken as string)

if (!tokenMatched) throw new AppError('Incorrect Token')

const userId = userWithThisEmail.id;

await this.usersRepository.destroyToken(userId);
Expand Down