Skip to content

Commit

Permalink
Merge pull request #28 from loryblu/develop
Browse files Browse the repository at this point in the history
Sync 0.3.3
  • Loading branch information
Daaaiii committed Oct 7, 2023
2 parents 49f6668 + e77b165 commit 297f00d
Show file tree
Hide file tree
Showing 13 changed files with 668 additions and 518 deletions.
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ NODE_ENV=development
SALT_DATA_HASH=[string]
SALT_DATA_PASS=[string]

SECRET_JWT=[string]

MAIL_API_KEY=[string]
MAIL_FROM=[string]
MAIL_TEST_DELIVERED=[string]
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@
"@nestjs/common": "10.0.0",
"@nestjs/config": "3.1.1",
"@nestjs/core": "10.0.0",
"@nestjs/jwt": "10.1.1",
"@nestjs/platform-express": "10.0.0",
"@nestjs/swagger": "7.1.8",
"@prisma/client": "5.2.0",
"@prisma/client": "5.3.1",
"bcrypt": "5.1.1",
"class-transformer": "0.5.1",
"class-validator": "0.14.0",
Expand Down Expand Up @@ -59,7 +60,7 @@
"husky": "8.0.3",
"jest": "29.5.0",
"prettier": "3.0.0",
"prisma": "5.2.0",
"prisma": "5.3.1",
"source-map-support": "0.5.21",
"supertest": "6.3.3",
"ts-jest": "29.1.0",
Expand Down
2 changes: 1 addition & 1 deletion src/globals/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export function unknownError(error: unknown) {
throw new UnknownErrorException();
}

export function hendleErrors(error: unknown) {
export function handleErrors(error: unknown) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
prismaKnownRequestErrors(error);
}
Expand Down
6 changes: 6 additions & 0 deletions src/globals/responses/exceptions/general.exceptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ export class ExpiredRecoveryTokenException extends UnauthorizedException {
}
}

export class InvalidCredentialsException extends UnauthorizedException {
constructor() {
super('Credenciais inválidas.');
}
}

/*
* 422 - Unprocessable Entity
*/
Expand Down
13 changes: 13 additions & 0 deletions src/modules/account/account.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ApiResponse, ApiTags } from '@nestjs/swagger';
import { MailService } from '../mail/mail.service';
import {
CreateAccountDto,
LoginDto,
ResetPasswordDto,
SetPasswordDto,
} from './account.dto';
Expand Down Expand Up @@ -31,6 +32,18 @@ export class AccountController {
return { message: 'Conta criada com sucesso!' };
}

@Post('/login')
@ApiTags('Authentication')
@HttpCode(200)
@ApiResponse(responses.ok)
@ApiResponse(responses.badRequest)
@ApiResponse(responses.unauthorized)
@ApiResponse(responses.internalError)
async login(@Body() { email, password }: LoginDto) {
const token = await this.accountService.login(email, password);
return { token, message: 'Login efetuado com sucesso' };
}

@Post('/recovery')
@HttpCode(200)
@ApiTags('Reset Password')
Expand Down
5 changes: 5 additions & 0 deletions src/modules/account/account.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,8 @@ export class SetPasswordDto extends PickType(CreateAccountDto, ['password']) {
@Matches(recoveryTokenRegExp, { message: messages.recoveryTokenPattern })
readonly recoveryToken: string;
}

export class LoginDto extends PickType(CreateAccountDto, [
'email',
'password',
]) {}
1 change: 1 addition & 0 deletions src/modules/account/account.entity.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export type RecoveryControllerOutput = {
export type GetCredentialIdByEmailOutput = {
id: Credential['id'];
fullname: ParentProfile['fullname'];
password: string;
} | void;

export type getCredentialIdByRecoveryTokenInput = {
Expand Down
9 changes: 8 additions & 1 deletion src/modules/account/account.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,16 @@ import { MailModule } from '../mail/mail.module';
import { AccountController } from './account.controller';
import { AccountService } from './account.service';
import { AccountRepository } from './account.repository';
import { JwtModule } from '@nestjs/jwt';

@Module({
imports: [PrismaModule, MailModule],
imports: [
PrismaModule,
MailModule,
JwtModule.register({
secret: process.env.SECRET_JWT,
}),
],
controllers: [AccountController],
providers: [AccountService, AccountRepository],
})
Expand Down
14 changes: 8 additions & 6 deletions src/modules/account/account.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
getCredentialIdByRecoveryTokenOutout,
SavePasswordInput,
} from './account.entity';
import { hendleErrors } from 'src/globals/errors';
import { handleErrors } from 'src/globals/errors';

@Injectable()
export class AccountRepository {
Expand Down Expand Up @@ -41,7 +41,7 @@ export class AccountRepository {
},
},
})
.catch((error) => hendleErrors(error));
.catch((error) => handleErrors(error));

return;
}
Expand All @@ -56,6 +56,7 @@ export class AccountRepository {
},
select: {
id: true,
password: true,
parentProfile: {
select: {
fullname: true,
Expand All @@ -67,13 +68,14 @@ export class AccountRepository {
if (response) {
return {
id: response.id,
password: response.password,
fullname: response.parentProfile.fullname,
};
}

return null;
})
.catch((error) => hendleErrors(error));
.catch((error) => handleErrors(error));

return response;
}
Expand Down Expand Up @@ -102,7 +104,7 @@ export class AccountRepository {

return;
})
.catch((error) => hendleErrors(error));
.catch((error) => handleErrors(error));

return response;
}
Expand All @@ -122,7 +124,7 @@ export class AccountRepository {
},
},
})
.catch((error) => hendleErrors(error));
.catch((error) => handleErrors(error));
}

async savePasswordResetInformation(input: PasswordResetInput): Promise<void> {
Expand All @@ -147,6 +149,6 @@ export class AccountRepository {
},
},
})
.catch((error) => hendleErrors(error));
.catch((error) => handleErrors(error));
}
}
48 changes: 47 additions & 1 deletion src/modules/account/account.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,20 @@ import {
import {
EmailNotFoundException,
ExpiredRecoveryTokenException,
InvalidCredentialsException,
PoliciesException,
TryingEncryptException,
TryingHashException,
} from 'src/globals/responses/exceptions';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcrypt';

@Injectable()
export class AccountService {
constructor(private accountRepository: AccountRepository) {}
constructor(
private accountRepository: AccountRepository,
private readonly jwtService: JwtService,
) {}

private async hashData(data: string): Promise<string> {
const hashed = await hashDataAsync({
Expand Down Expand Up @@ -84,6 +90,22 @@ export class AccountService {
return `loryblu://password_recovery/?${encodedParams}`;
}

// TODO: criar testes para login
private async createAuthToken(id: number) {
const token = {
accessToken: this.jwtService.sign(
{
id,
},
{
expiresIn: '1 h',
},
),
};

return token;
}

async newAccountPropsProcessing(input: CreateAccountDto): Promise<void> {
if (input.policiesAccepted !== true) {
throw new PoliciesException();
Expand Down Expand Up @@ -148,6 +170,8 @@ export class AccountService {
date: expiresIn,
});

delete account.password;

return {
url,
fullname: account.fullname,
Expand Down Expand Up @@ -177,4 +201,26 @@ export class AccountService {

return;
}

async login(email: string, password: string) {
const hashedEmail = await this.hashData(email);

const user = await this.accountRepository.getCredentialIdByEmail(
hashedEmail,
);

if (!user) {
throw new EmailNotFoundException();
}

const comparePassword = await bcrypt.compare(password, user.password);

if (!comparePassword) {
throw new InvalidCredentialsException();
}

delete user.password;

return this.createAuthToken(user.id);
}
}
2 changes: 2 additions & 0 deletions test/unit/account.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { BadRequestException } from '@nestjs/common';
import { Test, TestingModule } from '@nestjs/testing';
import { JwtModule } from '@nestjs/jwt';

import { AccountService } from 'src/modules/account/account.service';
import { AccountRepository } from 'src/modules/account/account.repository';
Expand All @@ -19,6 +20,7 @@ describe('AccountService unit test', () => {

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [JwtModule],
providers: [
AccountService,
{
Expand Down
1 change: 1 addition & 0 deletions test/unit/account.service.stubs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,5 +22,6 @@ export const resetPasswordInput: ResetPasswordDto = {

export const getCredentialOutput: GetCredentialIdByEmailOutput = {
id: faker.helpers.rangeToNumber({ min: 1, max: 3000 }),
password: faker.internet.password(),
fullname: faker.person.fullName(),
};
Loading

0 comments on commit 297f00d

Please sign in to comment.