Skip to content

Commit

Permalink
Merge pull request #27 from Daaaiii/JWT
Browse files Browse the repository at this point in the history
Atualiza Login
  • Loading branch information
Daaaiii committed Oct 7, 2023
2 parents b29c7c5 + ca2a6a6 commit e77b165
Show file tree
Hide file tree
Showing 18 changed files with 103 additions and 137 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,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
3 changes: 1 addition & 2 deletions src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { Module } from '@nestjs/common';

import { AccountModule } from './modules';
import { AuthModule } from './modules/jwtModule/account.auth.module';

@Module({
imports: [AccountModule, AuthModule],
imports: [AccountModule],
})
export class AppModule {}
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
1 change: 0 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ async function bootstrap() {
app.use(helmet());
app.enableCors(corsOptionsConfig);
app.useGlobalPipes(new ValidationPipe());


const document = SwaggerModule.createDocument(app, swaggerDocumentConfig);
SwaggerModule.setup('', app, document);
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));
}
}
49 changes: 47 additions & 2 deletions src/modules/account/account.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,27 @@ 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({
unhashedData: data,
salt: process.env.SALT_DATA_HASH,
});


if (!hashed) {
throw new TryingHashException();
}
Expand Down Expand Up @@ -85,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 @@ -149,6 +170,8 @@ export class AccountService {
date: expiresIn,
});

delete account.password;

return {
url,
fullname: account.fullname,
Expand Down Expand Up @@ -178,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);
}
}
19 changes: 0 additions & 19 deletions src/modules/jwtModule/account.auth.controller.ts

This file was deleted.

7 changes: 0 additions & 7 deletions src/modules/jwtModule/account.auth.login.dto.ts

This file was deleted.

23 changes: 0 additions & 23 deletions src/modules/jwtModule/account.auth.module.ts

This file was deleted.

65 changes: 0 additions & 65 deletions src/modules/jwtModule/account.auth.service.ts

This file was deleted.

Loading

0 comments on commit e77b165

Please sign in to comment.