-
Notifications
You must be signed in to change notification settings - Fork 2
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
Validação de senha BugFix-US04 #11
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 12 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
GabrielVilar 2f72a15
Versão final
GabrielVilar 4bb8b5f
Versão-final
GabrielVilar 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 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; | ||
|
@@ -43,23 +45,22 @@ describe('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); | ||
// Removido o mock de bcrypt do beforeEach | ||
|
||
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: 'Password123!', // Senha correta | ||
}; | ||
|
||
const user = new User(); | ||
|
@@ -71,14 +72,17 @@ describe('AuthService', () => { | |
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', | ||
}); | ||
|
||
// Mock de bcrypt DENTRO do teste, depois de definir a senha correta | ||
jest.spyOn(bcrypt, 'hash').mockImplementation(async () => 'hashed-password'); | ||
jest.spyOn(bcrypt, 'genSalt').mockResolvedValue(10); | ||
|
||
const response = await service.signUp(signUpDto); | ||
|
||
expect(userRepository.findOneBy).toHaveBeenCalledWith({ | ||
|
@@ -88,9 +92,9 @@ describe('AuthService', () => { | |
expect(userRepository.create).toHaveBeenCalledWith({ | ||
...signUpDto, | ||
role: UserRoles.User, | ||
password: expect.any(String), | ||
password: 'hashed-password', // Agora o password está sendo hasheado corretamente | ||
}); | ||
expect(bcrypt.hash).toHaveBeenCalledWith('password', 10); | ||
expect(bcrypt.hash).toHaveBeenCalledWith('Password123!', 10); | ||
expect(userRepository.save).toHaveBeenCalled(); | ||
expect(response).toEqual({ | ||
accessToken: 'access-token', | ||
|
@@ -99,32 +103,80 @@ describe('AuthService', () => { | |
}); | ||
|
||
it('should throw an error if user already exists', async () => { | ||
const signUpDto: SignUpDto = { | ||
const signUpDto: SignUpDto = { | ||
firstName: 'Test', | ||
lastName: 'User', | ||
email: '[email protected]', | ||
phone: '123456789', | ||
password: 'Password123!', | ||
}; | ||
|
||
const existingUser = new User(); | ||
existingUser.email = '[email protected]'; | ||
|
||
jest.spyOn(userRepository, 'findOneBy').mockResolvedValueOnce(existingUser); | ||
|
||
await expect(service.signUp(signUpDto)).rejects.toThrow(BadRequestException); | ||
await expect(service.signUp(signUpDto)).rejects.toThrowError('Usuário já cadastrado.'); | ||
|
||
expect(userRepository.create).not.toHaveBeenCalled(); | ||
expect(userRepository.save).not.toHaveBeenCalled(); | ||
}); | ||
|
||
it('should reject passwords shorter than 8 characters', async () => { | ||
const invalidDto: SignUpDto = { | ||
firstName: 'Test', | ||
lastName: 'User', | ||
email: '[email protected]', | ||
phone: '123456789', | ||
password: 'password', | ||
password: 'Short1!', | ||
}; | ||
await expect(service.signUp(invalidDto)).rejects.toThrow(BadRequestException); | ||
await expect(service.signUp(invalidDto)).rejects.toThrowError('A senha deve ter pelo menos 8 caracteres.'); | ||
expect(userRepository.findOneBy).not.toHaveBeenCalled(); | ||
}); | ||
|
||
const existingUser = new User(); | ||
existingUser.email = '[email protected]'; | ||
|
||
jest | ||
.spyOn(userRepository, 'findOneBy') | ||
.mockResolvedValueOnce(existingUser); | ||
it('should reject passwords without uppercase letters', async () => { | ||
const invalidDto: SignUpDto = { | ||
firstName: 'Test', | ||
lastName: 'User', | ||
email: '[email protected]', | ||
phone: '123456789', | ||
password: 'nopassword123!', | ||
}; | ||
await expect(service.signUp(invalidDto)).rejects.toThrow(BadRequestException); | ||
await expect(service.signUp(invalidDto)).rejects.toThrowError('A senha deve conter pelo menos uma letra maiúscula.'); | ||
expect(userRepository.findOneBy).not.toHaveBeenCalled(); | ||
}); | ||
|
||
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(); | ||
} | ||
|
||
it('should reject passwords without numbers', async () => { | ||
const invalidDto: SignUpDto = { | ||
firstName: 'Test', | ||
lastName: 'User', | ||
email: '[email protected]', | ||
phone: '123456789', | ||
password: 'NoNumberPassword!', | ||
}; | ||
await expect(service.signUp(invalidDto)).rejects.toThrow(BadRequestException); | ||
await expect(service.signUp(invalidDto)).rejects.toThrowError('A senha deve conter pelo menos um número.'); | ||
expect(userRepository.findOneBy).not.toHaveBeenCalled(); | ||
}); | ||
|
||
it('should reject passwords without special characters', async () => { | ||
const invalidDto: SignUpDto = { | ||
firstName: 'Test', | ||
lastName: 'User', | ||
email: '[email protected]', | ||
phone: '123456789', | ||
password: 'NoSpecialChar123', | ||
}; | ||
await expect(service.signUp(invalidDto)).rejects.toThrow(BadRequestException); | ||
await expect(service.signUp(invalidDto)).rejects.toThrowError('A senha deve conter pelo menos um caractere especial.'); | ||
expect(userRepository.findOneBy).not.toHaveBeenCalled(); | ||
}); | ||
}); | ||
}); | ||
|
||
describe('signIn', () => { | ||
it('should throw an UnauthorizedException for invalid credentials', async () => { | ||
|
@@ -245,4 +297,74 @@ describe('AuthService', () => { | |
expect(sendMailMock).toHaveBeenCalled(); | ||
}); | ||
}); | ||
}); | ||
|
||
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); | ||
// Mock das novas funções | ||
const generateAccessTokenSpy = jest.spyOn(service, 'generateAccessToken').mockResolvedValue('access-token'); | ||
const generateRefreshTokenSpy = jest.spyOn(service, 'generateRefreshToken').mockResolvedValue('refresh-token'); // Corrigido o retorno para 'refresh-token' | ||
|
||
const result = await service.signIn(signInDto); | ||
|
||
expect(result.accessToken).toBe('access-token'); | ||
expect(result.refreshToken).toBe('refresh-token'); | ||
expect(generateAccessTokenSpy).toHaveBeenCalledWith( | ||
{ sub: user.id, email: user.email, role: user.role }, | ||
'30m', | ||
); | ||
expect(generateRefreshTokenSpy).toHaveBeenCalledWith({ | ||
sub: user.id, | ||
email: user.email, | ||
role: user.role, | ||
}); | ||
}); | ||
|
||
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); | ||
// Mock das novas funções | ||
const generateAccessTokenSpy = jest.spyOn(service, 'generateAccessToken').mockResolvedValue('access-token'); | ||
const generateRefreshTokenSpy = jest.spyOn(service, 'generateRefreshToken').mockResolvedValue('refresh-token'); // Corrigido o retorno para 'refresh-token' | ||
|
||
const result = await service.signIn(signInDto); | ||
|
||
expect(result.accessToken).toBe('access-token'); | ||
expect(result.refreshToken).toBe('refresh-token'); | ||
expect(generateAccessTokenSpy).toHaveBeenCalledWith( | ||
{ sub: user.id, email: user.email, role: user.role }, | ||
'7d', | ||
); | ||
expect(generateRefreshTokenSpy).toHaveBeenCalledWith({ | ||
sub: user.id, | ||
email: user.email, | ||
role: user.role, | ||
}); | ||
}); | ||
}); | ||
}); |
This file contains 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
This file contains 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 |
---|---|---|
|
@@ -11,4 +11,6 @@ export class SignInDto { | |
|
||
@IsNotEmpty() | ||
role: UserRoles; | ||
|
||
keepLoggedIn?: boolean; | ||
} |
This file contains 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
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