-
Notifications
You must be signed in to change notification settings - Fork 2
Validação de senha BugFix-US04 #11
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
Open
rFaelxs
wants to merge
15
commits into
main
Choose a base branch
from
US04--BugFix
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
105582a
Validação de senha BugFix-US04
leafrse a000dd4
Teste US04
leafrse 112954f
Testes-US04
leafrse 8c7d368
US04 - Adição de testes e correções
leafrse 7c36c11
fix lint
matheusyanmonteiro b277da7
Merge branch 'main' of https://github.com/fga-eps-mds/2024.2-LIVRO-LI…
matheusyanmonteiro a96e011
Merge branch 'US04--BugFix' of https://github.com/fga-eps-mds/2024.2-…
matheusyanmonteiro 2ad02a7
fix:lint
matheusyanmonteiro f95518a
remove: package-lock.json
matheusyanmonteiro 8920f1c
Correção de testes 01 - US04
leafrse 89bcaf0
Merge Branche US04
leafrse 359e85d
Merge Branche US04
leafrse c904580
Bug TestSwitch
gabrielaugusto23 2f72a15
Versão final
gabrielaugusto23 4bb8b5f
Versão-final
gabrielaugusto23 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,8 +7,10 @@ import { JwtService } from '@nestjs/jwt'; | |
| import { SignUpDto } from '../auth/dtos/signUp.dto'; | ||
| import * as bcrypt from 'bcryptjs'; | ||
| import { repositoryMockFactory } from '../../test/database/utils'; | ||
| import { UnauthorizedException } from '@nestjs/common'; | ||
| import { UnauthorizedException, BadRequestException } from '@nestjs/common'; | ||
| import * as nodemailer from 'nodemailer'; | ||
| import { SignInDto } from './dtos/signIn.dto'; | ||
|
|
||
|
|
||
| describe('AuthService', () => { | ||
| let service: AuthService; | ||
|
|
@@ -38,91 +40,88 @@ describe('AuthService', () => { | |
| }, | ||
| ], | ||
| }).compile(); | ||
|
|
||
| service = module.get<AuthService>(AuthService); | ||
| userRepository = module.get<Repository<User>>(getRepositoryToken(User)); | ||
| jwtService = module.get<JwtService>(JwtService); | ||
|
|
||
| jest.spyOn(bcrypt, 'hash').mockResolvedValueOnce('hashed-password'); | ||
| jest.spyOn(bcrypt, 'genSalt').mockResolvedValueOnce(10); | ||
|
|
||
|
|
||
| jest.spyOn(bcrypt, 'hash').mockResolvedValue('hashed-password'); | ||
| jest.spyOn(bcrypt, 'genSalt').mockResolvedValue(10); | ||
| jest.spyOn(bcrypt, 'compare').mockResolvedValue(true); | ||
|
|
||
| sendMailMock = jest.fn(); | ||
| jest.spyOn(nodemailer, 'createTransport').mockReturnValue({ | ||
| sendMail: sendMailMock, | ||
| } as any); | ||
| }); | ||
|
|
||
| //signUp | ||
| describe('signUp', () => { | ||
| it('should create a new user and return a signed token', async () => { | ||
| const signUpDto: SignUpDto = { | ||
| firstName: 'Test', | ||
| lastName: 'User', | ||
| email: '[email protected]', | ||
| phone: '123456789', | ||
| password: 'password', | ||
| password: 'ValidPassword123!', // Ensure the password meets the criteria | ||
| }; | ||
|
|
||
| const user = new User(); | ||
| user.id = '18ea976e-367b-4138-b68e-7aff3f7ae4de'; | ||
| user.firstName = signUpDto.firstName; | ||
| user.lastName = signUpDto.lastName; | ||
| user.email = signUpDto.email; | ||
| user.phone = signUpDto.phone; | ||
| user.role = UserRoles.User; | ||
|
|
||
| jest.spyOn(userRepository, 'findOneBy').mockResolvedValueOnce(null); | ||
|
|
||
| jest.spyOn(userRepository, 'create').mockReturnValue(user); | ||
| jest.spyOn(userRepository, 'save').mockResolvedValue(user); | ||
| jest.spyOn(service, 'signIn').mockResolvedValue({ | ||
| accessToken: 'access-token', | ||
| refreshToken: 'refresh-token', | ||
| }); | ||
|
|
||
| const response = await service.signUp(signUpDto); | ||
|
|
||
| expect(userRepository.findOneBy).toHaveBeenCalledWith({ | ||
| email: '[email protected]', | ||
| }); | ||
|
|
||
| expect(userRepository.create).toHaveBeenCalledWith({ | ||
| ...signUpDto, | ||
| role: UserRoles.User, | ||
| password: expect.any(String), | ||
| }); | ||
| expect(bcrypt.hash).toHaveBeenCalledWith('password', 10); | ||
| expect(bcrypt.hash).toHaveBeenCalledWith('ValidPassword123!', 10); | ||
| expect(userRepository.save).toHaveBeenCalled(); | ||
| expect(response).toEqual({ | ||
| accessToken: 'access-token', | ||
| refreshToken: 'refresh-token', | ||
| }); | ||
| }); | ||
|
|
||
| it('should throw an error if user already exists', async () => { | ||
| const signUpDto: SignUpDto = { | ||
| firstName: 'Test', | ||
| lastName: 'User', | ||
| email: '[email protected]', | ||
| phone: '123456789', | ||
| password: 'password', | ||
| password: 'ValidPassword123!', // Ensure the password meets the criteria | ||
| }; | ||
|
|
||
| const existingUser = new User(); | ||
| existingUser.email = 'existing@email.com'; | ||
|
|
||
| existingUser.email = 'test@email.com'; | ||
| jest | ||
| .spyOn(userRepository, 'findOneBy') | ||
| .mockResolvedValueOnce(existingUser); | ||
|
|
||
| try { | ||
| await service.signUp(signUpDto); | ||
| fail('An error should be thrown'); | ||
| } catch (error) { | ||
| expect(error).toBeInstanceOf(UnauthorizedException); | ||
| expect((error as Error).message).toBe('Usuário já cadastrado.'); | ||
| expect(userRepository.create).not.toHaveBeenCalled(); | ||
| expect(userRepository.save).not.toHaveBeenCalled(); | ||
| } | ||
|
|
||
| await expect(service.signUp(signUpDto)).rejects.toThrow( | ||
| UnauthorizedException, | ||
| ); | ||
| expect((await service.signUp(signUpDto).catch(e => e)).message).toBe('Usuário já cadastrado.'); | ||
| expect(userRepository.create).not.toHaveBeenCalled(); | ||
| expect(userRepository.save).not.toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
|
|
||
|
|
@@ -139,7 +138,7 @@ describe('AuthService', () => { | |
| jest.spyOn(bcrypt, 'compare').mockResolvedValueOnce(false); | ||
|
|
||
| await expect(service.signIn({ email, password, role })).rejects.toThrow( | ||
| UnauthorizedException, | ||
| BadRequestException, | ||
| ); | ||
|
|
||
| expect(userRepository.findOneBy).toHaveBeenCalledWith({ email, role }); | ||
|
|
@@ -208,41 +207,195 @@ describe('AuthService', () => { | |
| }); | ||
|
|
||
| describe('recoverPassword', () => { | ||
| it('should throw an UnauthorizedException if the user is not found', async () => { | ||
| const email = 'notfound@example.com'; | ||
|
|
||
| it('should throw UnauthorizedException if the user is not found', async () => { | ||
| const email = 'nonexistent@example.com'; | ||
| jest.spyOn(userRepository, 'findOneBy').mockResolvedValueOnce(null); | ||
| const signSpy = jest.spyOn(jwtService, 'signAsync'); | ||
|
|
||
|
|
||
| await expect(service.recoverPassword(email)).rejects.toThrow( | ||
| UnauthorizedException, | ||
| ); | ||
|
|
||
| expect(userRepository.findOneBy).toHaveBeenCalledWith({ email }); | ||
| expect(signSpy).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('should handle errors during email sending', async () => { | ||
| const email = '[email protected]'; | ||
| const user = new User(); | ||
| user.id = '123'; | ||
| user.email = email; | ||
|
|
||
| jest.spyOn(userRepository, 'findOneBy').mockResolvedValueOnce(user); | ||
| jest.spyOn(jwtService, 'signAsync').mockResolvedValueOnce('mocked-token'); | ||
|
|
||
| sendMailMock.mockRejectedValueOnce(new Error('Email service error')); | ||
|
|
||
| await expect(service.recoverPassword(email)).rejects.toThrow( | ||
| 'Email service error', | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| describe('signIn with keepLoggedIn', () => { | ||
| it('should return a token with 30m expiration when keepLoggedIn is false', async () => { | ||
| const signInDto: SignInDto = { | ||
| email: '[email protected]', | ||
| password: 'password', | ||
| role: UserRoles.User, | ||
| keepLoggedIn: false, | ||
| }; | ||
| const user = new User(); | ||
| user.id = 'user-id'; | ||
| user.email = signInDto.email; | ||
| user.password = 'hashed-password'; | ||
| user.role = UserRoles.User; | ||
|
|
||
| jest.spyOn(userRepository, 'findOneBy').mockResolvedValue(user); | ||
| jest.spyOn(bcrypt, 'compare').mockResolvedValue(true); | ||
| const signAsyncSpy = jest.spyOn(jwtService, 'signAsync'); | ||
|
|
||
| const result = await service.signIn(signInDto); | ||
|
|
||
| expect(userRepository.findOneBy).toHaveBeenCalledWith({ email }); | ||
| expect(jwtService.signAsync).toHaveBeenCalledWith( | ||
| { sub: user.id }, | ||
| expect(result.accessToken).toBeDefined(); | ||
|
|
||
| expect(signAsyncSpy).toHaveBeenNthCalledWith( | ||
| 1, | ||
| { sub: user.id, email: user.email, role: user.role }, | ||
| { expiresIn: '30m' }, | ||
| ); | ||
| expect(sendMailMock).toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('should return a token with 7d expiration when keepLoggedIn is true', async () => { | ||
| const signInDto: SignInDto = { | ||
| email: '[email protected]', | ||
| password: 'password', | ||
| role: UserRoles.User, | ||
| keepLoggedIn: true, | ||
| }; | ||
| const user = new User(); | ||
| user.id = 'user-id'; | ||
| user.email = signInDto.email; | ||
| user.password = 'hashed-password'; | ||
| user.role = UserRoles.User; | ||
|
|
||
| jest.spyOn(userRepository, 'findOneBy').mockResolvedValue(user); | ||
| jest.spyOn(bcrypt, 'compare').mockResolvedValue(true); | ||
| const signAsyncSpy = jest.spyOn(jwtService, 'signAsync'); | ||
|
|
||
| const result = await service.signIn(signInDto); | ||
|
|
||
| expect(result.accessToken).toBeDefined(); | ||
|
|
||
| expect(signAsyncSpy).toHaveBeenNthCalledWith( | ||
| 1, | ||
| { sub: user.id, email: user.email, role: user.role }, | ||
| { expiresIn: '7d' }, | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| describe('generateAccessToken', () => { | ||
| it('should generate an access token with the given payload and expiration', async () => { | ||
| const payload = { sub: '123', email: '[email protected]', role: UserRoles.User }; | ||
| const expiresIn = '30m'; | ||
|
|
||
| jest.spyOn(jwtService, 'signAsync').mockResolvedValueOnce('access-token'); | ||
|
|
||
| const result = await service.generateAccessToken(payload, expiresIn); | ||
|
|
||
| expect(result).toBe('access-token'); | ||
| expect(jwtService.signAsync).toHaveBeenCalledWith(payload, { expiresIn }); | ||
| }); | ||
| }); | ||
|
|
||
| describe('generateRefreshToken', () => { | ||
| it('should generate a refresh token with the given payload', async () => { | ||
| const payload = { sub: '123', email: '[email protected]', role: UserRoles.User }; | ||
|
|
||
| jest.spyOn(jwtService, 'signAsync').mockResolvedValueOnce('refresh-token'); | ||
|
|
||
| const result = await service.generateRefreshToken(payload); | ||
|
|
||
| expect(result).toBe('refresh-token'); | ||
| expect(jwtService.signAsync).toHaveBeenCalledWith(payload); | ||
| }); | ||
| }); | ||
|
|
||
| describe('changePassword', () => { | ||
| it('should update the password if the user exists', async () => { | ||
| const userId = '123'; | ||
| const newPassword = 'NewPassword123!'; | ||
| const user = new User(); | ||
| user.id = userId; | ||
| user.password = 'oldPassword'; | ||
|
|
||
| jest.spyOn(userRepository, 'findOneBy').mockResolvedValueOnce(user); | ||
| jest.spyOn(bcrypt, 'hash').mockResolvedValueOnce('hashedNewPassword'); | ||
| jest.spyOn(userRepository, 'save').mockResolvedValueOnce(user); | ||
|
|
||
| const result = await service.changePassword(userId, newPassword); | ||
|
|
||
| expect(result).toEqual({ success: true }); | ||
| expect(bcrypt.hash).toHaveBeenCalledWith(newPassword, 10); | ||
| expect(userRepository.save).toHaveBeenCalledWith(user); | ||
| }); | ||
|
|
||
| it('should throw UnauthorizedException if the user does not exist', async () => { | ||
| const userId = 'nonexistent'; | ||
| const newPassword = 'NewPassword123!'; | ||
|
|
||
| jest.spyOn(userRepository, 'findOneBy').mockResolvedValueOnce(null); | ||
|
|
||
| await expect(service.changePassword(userId, newPassword)).rejects.toThrow( | ||
| UnauthorizedException, | ||
| ); | ||
| }); | ||
| }); | ||
|
|
||
| describe('validatePassword', () => { | ||
| it('should throw BadRequestException if password is less than 8 characters', async () => { | ||
| const shortPassword = 'Pass1!'; // 6 characters, missing length | ||
| await expect(() => | ||
| (service as any).validatePassword(shortPassword), | ||
| ).toThrowError(BadRequestException); | ||
| await expect(() => | ||
| (service as any).validatePassword(shortPassword), | ||
| ).toThrowError('A senha deve ter pelo menos 8 caracteres.'); | ||
| }); | ||
|
|
||
| it('should throw BadRequestException if password has no uppercase letter', async () => { | ||
| const noUppercasePassword = 'password1!'; // Missing uppercase | ||
| await expect(() => | ||
| (service as any).validatePassword(noUppercasePassword), | ||
| ).toThrowError(BadRequestException); | ||
| await expect(() => | ||
| (service as any).validatePassword(noUppercasePassword), | ||
| ).toThrowError('A senha deve conter pelo menos uma letra maiúscula.'); | ||
| }); | ||
|
|
||
| it('should throw BadRequestException if password has no number', async () => { | ||
| const noNumberPassword = 'Password!'; // Missing number | ||
| await expect(() => | ||
| (service as any).validatePassword(noNumberPassword), | ||
| ).toThrowError(BadRequestException); | ||
| await expect(() => | ||
| (service as any).validatePassword(noNumberPassword), | ||
| ).toThrowError('A senha deve conter pelo menos um número.'); | ||
| }); | ||
|
|
||
| it('should throw BadRequestException if password has no special character', async () => { | ||
| const noSpecialCharPassword = 'Password1'; // Missing special character | ||
| await expect(() => | ||
| (service as any).validatePassword(noSpecialCharPassword), | ||
| ).toThrowError(BadRequestException); | ||
| await expect(() => | ||
| (service as any).validatePassword(noSpecialCharPassword), | ||
| ).toThrowError('A senha deve conter pelo menos um caractere especial.'); | ||
| }); | ||
|
|
||
| it('should not throw an exception if password meets all criteria', async () => { | ||
| const validPassword = 'ValidPassword123!'; // Meets all criteria | ||
| expect(() => | ||
| (service as any).validatePassword(validPassword), | ||
| ).not.toThrow(); | ||
| }); | ||
| }); | ||
| }); | ||
|
|
||
| }); | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Talvez por mudança de atributos os testes deste arquivo apresetaram erro, vejam se consegue resolver sozinho e me contatem por favor