Skip to content

Commit

Permalink
Merge pull request #4 from fga-eps-mds/feature/#137-criptografia_senh…
Browse files Browse the repository at this point in the history
…a_e_verificacao_email

Feature/#137 criptografia senha e verificacao email
  • Loading branch information
HenriqueAmorim20 authored Oct 20, 2023
2 parents 8da7a29 + 59b1af8 commit 86de634
Show file tree
Hide file tree
Showing 5 changed files with 74 additions and 6 deletions.
4 changes: 4 additions & 0 deletions .env.development
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,7 @@ DB_USERNAME=postgres
DB_PASS=postgres
DB_DATABASE=gerocuidado-usuario-db
DB_PORT=5001

#BCRYPT
HASH_SALT=10

3 changes: 3 additions & 0 deletions .env.test
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,6 @@ DB_USERNAME=postgres
DB_PASS=postgres
DB_DATABASE=gerocuidado-usuario-db-test
DB_PORT=5001

#BCRYPT
HASH_SALT=10
17 changes: 16 additions & 1 deletion e2e/usuario.e2e-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,27 @@ describe('E2E - Usuario', () => {

expect(res.statusCode).toEqual(201);
expect(res.body.message).toEqual('Salvo com sucesso!');
expect(res.body.data).toMatchObject({ ...user, id: res.body.data.id });
expect(res.body.data).toMatchObject({
...user,
id: res.body.data.id,
senha: res.body.data.senha,
});

Object.assign(user, res.body.data);
delete user.senha;
});

it('should not successfully add a new "usuario" when email is already registered', async () => {
const res = await request(app.getHttpServer())
.post('')
.set('Content-Type', 'application/json')
.send({ ...user, senha: 'senha' });

expect(res.statusCode).toEqual(400);
expect(res.body.message).toEqual('Este email já está cadastrado!');
expect(res.body.data).toBeNull();
});

it('should not add a new "usuario" when validations are incorrect', async () => {
const res = await request(app.getHttpServer())
.post('')
Expand Down
34 changes: 32 additions & 2 deletions src/usuario/usuario.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { BadRequestException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import bcrypt from 'bcrypt';
import { Repository } from 'typeorm';
import { OrderParams, Ordering } from '../shared/decorators/ordenate.decorator';
import {
Expand All @@ -12,11 +15,13 @@ import { UsuarioService } from './usuario.service';
describe('UsuarioService', () => {
let service: UsuarioService;
let repository: Repository<Usuario>;
let configService: ConfigService;

const mockRepository = {
save: jest.fn(),
findOneOrFail: jest.fn(),
remove: jest.fn(),
findOne: jest.fn(),
createQueryBuilder: jest.fn(() => ({
where: jest.fn().mockReturnThis(),
limit: jest.fn().mockReturnThis(),
Expand All @@ -26,19 +31,28 @@ describe('UsuarioService', () => {
})),
};

const mockConfigService = {
get: jest.fn(),
};

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
UsuarioService,
{
provide: getRepositoryToken(Usuario),
useValue: mockRepository,
},
UsuarioService,
{
provide: ConfigService,
useValue: mockConfigService,
},
],
}).compile();

service = module.get<UsuarioService>(UsuarioService);
repository = module.get<Repository<Usuario>>(getRepositoryToken(Usuario));
configService = module.get<ConfigService>(ConfigService);
});

it('should be defined', () => {
Expand All @@ -48,11 +62,27 @@ describe('UsuarioService', () => {
it('should create Usuario', async () => {
const user = { nome: 'Henrique' } as any;
jest.spyOn(repository, 'save').mockReturnValue({ id: 1 } as any);

jest.spyOn(repository, 'findOne').mockReturnValue(undefined as any);
jest.spyOn(configService, 'get').mockReturnValue(10 as any);
jest
.spyOn(bcrypt, 'hash')
.mockImplementation((pass: string | Buffer, salt: string | number) =>
Promise.resolve('senha'),
);
const created = await service.create(user);
expect(created.id).toEqual(1);
});

it('should not create Usuario', async () => {
const user = { nome: 'Henrique' } as any;
jest
.spyOn(repository, 'findOne')
.mockReturnValue({ email: '[email protected]' } as any);
expect(service.create(user)).rejects.toThrow(
new BadRequestException('Este email já está cadastrado!'),
);
});

it('should find Usuario', async () => {
jest.spyOn(repository, 'findOneOrFail').mockReturnValue({ id: 1 } as any);

Expand Down
22 changes: 19 additions & 3 deletions src/usuario/usuario.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Injectable } from '@nestjs/common';
import { BadRequestException, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { InjectRepository } from '@nestjs/typeorm';
import bcrypt from 'bcrypt';
import { Repository } from 'typeorm';
import { Ordering } from '../shared/decorators/ordenate.decorator';
import { Pagination } from '../shared/decorators/paginate.decorator';
Expand All @@ -18,15 +20,29 @@ export class UsuarioService {
constructor(
@InjectRepository(Usuario)
private readonly _repository: Repository<Usuario>,
private readonly _configService: ConfigService,
) {}

async create(body: CreateUsuarioDto): Promise<Usuario> {
const usuario = new Usuario(body);

// TODO verificar email e criptografar senha
await this.checkEmail(usuario.email);
usuario.senha = await this.hashPassword(usuario.senha);
return this._repository.save(usuario);
}

async hashPassword(senha: string): Promise<string> {
const salt = this._configService.get('HASH_SALT');
return bcrypt.hash(senha, Number(salt));
}

async checkEmail(email: string) {
const userFound = await this._repository.findOne({ where: { email } });

if (userFound) {
throw new BadRequestException('Este email já está cadastrado!');
}
}

async findOne(id: number) {
return this._repository.findOneOrFail({ where: { id } });
}
Expand Down

0 comments on commit 86de634

Please sign in to comment.