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

Refactor Cadastro Users #24

Merged
merged 5 commits into from
Oct 9, 2023
Merged
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
30 changes: 15 additions & 15 deletions src/application/controllers/forgotPassword.controller.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
/* eslint-disable prettier/prettier */
import { Controller, Param, Post, HttpStatus, Res, Body, Patch, Req, Put } from "@nestjs/common";
import { UserService } from '../../domain/services/user.service';
import { Response } from 'express';
import { ValidateEmailPipe } from '../../domain/core/pipes/validate-email.pipe';
import {
ApiCreatedResponse,
Controller,
Param,
Post,
HttpStatus,
Res,
Put,
Body,
} from "@nestjs/common";
import { UserService } from "../../domain/services/user.service";
import { Response } from "express";
import { ValidateEmailPipe } from "../../domain/core/pipes/validate-email.pipe";
import {
ApiForbiddenResponse,
ApiOkResponse,
ApiTags,
ApiUnprocessableEntityResponse,
} from "@nestjs/swagger";
import { CreateUserDto } from '../../domain/dto/create-user.dto';
import { ResetPasswordDto } from "../../domain/dto/reset-password.dto";

@ApiTags("Password")
@Controller("recoverPassword")
export class ForgotPasswordController {
constructor(private readonly UserService: UserService) {
}
constructor(private readonly UserService: UserService) {}

@Post("/:email")
@ApiCreatedResponse({ description: "Succesfully" })
@ApiUnprocessableEntityResponse({ description: "Bad Request" })
@ApiForbiddenResponse({ description: "Unauthorized Request" })
@Post("sendEmail/:email")
async sendForgotPasswordEmail(
@Param("email", ValidateEmailPipe) email: string,
@Res() response: Response,
Expand All @@ -37,8 +38,7 @@ export class ForgotPasswordController {
@ApiUnprocessableEntityResponse({ description: "Bad Request" })
@ApiForbiddenResponse({ description: "Unauthorized Request" })
async resetPassword(@Body() reset: ResetPasswordDto) {
console.info('Request: ', reset)
console.info("Request: ", reset);
return await this.UserService.resetPassword(reset);
}

}
24 changes: 24 additions & 0 deletions src/domain/dto/create-user.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,38 @@ import {
IsNotEmpty,
IsString,
IsStrongPassword,
MaxLength,
minLength,
MinLength,
} from "class-validator";
import { Match } from "../decorators/match.decorator";
import { CreateUserErrors } from "../enum/create-user-errors.enum.spec";
import { CompleteSignupErrors } from "../enum/complete-signup-errors.enum";

export class CreateUserDto {
@ApiProperty({
type: String,
description: "O nome é obrigatório",
})
@IsNotEmpty({ message: CompleteSignupErrors.NAME_REQUIRED })
@MinLength(3, { message: CompleteSignupErrors.NAME_MIN_LENGTH })
@MaxLength(50, { message: CompleteSignupErrors.NAME_MAX_LENGTH })
nome: string;
@ApiProperty({
type: String,
description: "O sobrenome é obrigatório",
})
@IsNotEmpty({ message: CompleteSignupErrors.LASTNAME_REQUIRED })
@MinLength(3, { message: CompleteSignupErrors.LASTNAME_MIN_LENGTH })
@MaxLength(50, { message: CompleteSignupErrors.LASTNAME_MAX_LENGTH })
sobrenome: string;
@ApiProperty({
type: String,
description: "O email é obrigatório",
})
@IsNotEmpty({ message: CreateUserErrors.EMAIL_REQUIRED })
@IsEmail({}, { message: "O email informado nao é válido." })
@IsEmail({}, { message: "O email informado nao é válido." })
email: string;

@ApiProperty({
Expand All @@ -27,6 +47,10 @@ export class CreateUserDto {
message:
"A senha deve possuir no mínimo 8 caracteres, contendo pelo menos 1 letra maiúscula, uma letra minúscula e um caractere especial (Ex.: #, $, *, @)",
})
@MinLength(8, {
message:
"A senha deve possuir no mínimo 8 caracteres, contendo pelo menos 1 letra maiúscula, uma letra minúscula e um caractere especial (Ex.: #, $, *, @)",
})
@IsNotEmpty({ message: CreateUserErrors.PASSWORD_MIN_REQUIREMENTS })
@IsStrongPassword(
{
Expand Down
2 changes: 1 addition & 1 deletion src/domain/services/email.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export class EmailService {

async sendEmailBoasVindas(user: User, key: string) {
console.info("Start Send Email");
const confirmUrl = `${process.env.HOST}/user/confirmEmail/${key}`;
const confirmUrl = `${process.env.FRONT_HOST}/Successfully`;
console.info("Url: ", confirmUrl);

const nome =
Expand Down
58 changes: 34 additions & 24 deletions src/domain/services/user.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
/* eslint-disable prettier/prettier */
import { BadRequestException, ExecutionContext, HttpException, HttpStatus, Injectable } from "@nestjs/common";
import {
BadRequestException,
HttpException,
HttpStatus,
Injectable,
} from "@nestjs/common";
import { PrismaService } from "./prisma.service";
import { User, Prisma, TypeEmail } from "@prisma/client";
import { EmailService } from "./email.service";
Expand Down Expand Up @@ -130,6 +134,8 @@ export class UserService {

const user = await this.prisma.user.create({
data: {
nome: data.nome,
sobreNome: data.sobrenome,
email: data.email,
password: await encryptPass(data.password),
},
Expand Down Expand Up @@ -175,7 +181,7 @@ export class UserService {
where: { id: userId },
data: {
...data,
updatedAt: new Date().toISOString(),
updatedAt: new Date(),
},
});

Expand All @@ -187,9 +193,9 @@ export class UserService {
where: { email },
});

console.info("userExists: ", userExists !== null ? userExists.id : "Não encontrado");
console.info("userExists: ", userExists ? userExists.id : "Não encontrado");

if (userExists === null)
if (!userExists || !userExists.validateUser)
throw new HttpException("", HttpStatus.NOT_FOUND);

await this.emailService.sendRecoverPasswordEmail(userExists, email);
Expand All @@ -201,29 +207,33 @@ export class UserService {
}

async resetPassword(data: ResetPasswordDto) {
const userExists = await this.prisma.user.findUnique({
where: { email: data.email },
});
const userExists = await this.prisma.user.findUnique({
where: { email: data.email },
});

console.info("userExists: ", userExists !== null ? userExists.id : "Não encontrado");
console.info(
"userExists: ",
userExists !== null ? userExists.id : "Não encontrado",
);

if (userExists === null) throw new HttpException("", HttpStatus.NOT_FOUND);
if (userExists === null) throw new HttpException("", HttpStatus.NOT_FOUND);

if(data.password != data.confirmPassword) throw new BadRequestException("As senhas inseridas não são iguais!");
if (data.password != data.confirmPassword)
throw new BadRequestException("As senhas inseridas não são iguais!");

await this.prisma.user.update({
where: {
email: data.email
},
data: {
password: await encryptPass(data.password)
}
});
await this.prisma.user.update({
where: {
email: data.email,
},
data: {
password: await encryptPass(data.password),
},
});

return {
data: [{email: userExists.email}],
statusCode: HttpStatus.OK,
message: "Sua senha foi redefinida com sucesso!",
};
return {
data: [{ email: userExists.email }],
statusCode: HttpStatus.OK,
message: "Sua senha foi redefinida com sucesso!",
};
}
}
2 changes: 2 additions & 0 deletions test/application/controllers/user.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ describe("User Controller test suite", () => {
} as unknown as Response;

data = {
nome: "any-Nome",
sobrenome: "any-SobreNome",
email: "[email protected]",
password: "any-password",
confirmPassword: "any-password",
Expand Down
2 changes: 1 addition & 1 deletion test/unit/email.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ describe("Email Service Test", () => {
describe("SendEmail deliver", () => {
it("SUCCESS - should add emailJob to the queue", async () => {

const confirmUrl = `${process.env.HOST}/user/confirmEmail/${key}`
const confirmUrl = `${process.env.FRONT_HOST}/Successfully`
const nome =
user.nome === null ? user.email : `${user.nome} ${user.sobreNome}`;

Expand Down
Loading