Skip to content
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

Jwt #24

Merged
merged 8 commits into from
Oct 3, 2023
Merged

Jwt #24

Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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=[string]

MAIL_API_KEY=[string]
MAIL_FROM=[string]
MAIL_TEST_DELIVERED=[string]
Expand Down
3 changes: 2 additions & 1 deletion 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",
viniciuscosmome marked this conversation as resolved.
Show resolved Hide resolved
"bcrypt": "5.1.1",
"class-transformer": "0.5.1",
"class-validator": "0.14.0",
Expand Down
3 changes: 2 additions & 1 deletion src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Module } from '@nestjs/common';

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

@Module({
imports: [AccountModule],
imports: [AccountModule, AuthModule],
})
export class AppModule {}
1 change: 1 addition & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ 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
1 change: 1 addition & 0 deletions src/modules/account/account.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export class AccountService {
salt: process.env.SALT_DATA_HASH,
});


if (!hashed) {
throw new TryingHashException();
}
Expand Down
19 changes: 19 additions & 0 deletions src/modules/jwtModule/account.auth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Body, Controller, Post, HttpCode } from '@nestjs/common';

import { ApiTags } from '@nestjs/swagger';

import { AuthService } from './account.auth.service';
import { LoginDto } from './account.auth.login.dto';

@Controller('/auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}

@ApiTags()
@Post('/login')
@HttpCode(200)
async login(@Body() { email, password }: LoginDto) {
const token = await this.authService.login(email, password);
return { token, message: 'Login efetuado com sucesso' };
}
}
7 changes: 7 additions & 0 deletions src/modules/jwtModule/account.auth.login.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { PickType } from '@nestjs/swagger';
import { CreateAccountDto } from '../account/account.dto';

export class LoginDto extends PickType(CreateAccountDto, [
'email',
'password',
]) {}
23 changes: 23 additions & 0 deletions src/modules/jwtModule/account.auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { AuthController } from './account.auth.controller';

import { PrismaModule } from 'src/prisma/prisma.module';
import { AccountModule } from '../account/account.module';
import { AuthService } from './account.auth.service';
import { AccountService } from '../account/account.service';
import { AccountRepository } from '../account/account.repository';

@Module({
imports: [
JwtModule.register({
secret: process.env.SECRET,
}),
AccountModule,
PrismaModule,
AuthModule,
],
controllers: [AuthController],
providers: [AuthService, AccountService, AccountRepository],
})
export class AuthModule {}
65 changes: 65 additions & 0 deletions src/modules/jwtModule/account.auth.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { BadRequestException, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from 'src/prisma/prisma.service';
import { Credential } from '@prisma/client';
import * as bcrypt from 'bcrypt';
import { hashDataAsync } from '../../globals/utils';

@Injectable()
export class AuthService {
constructor(
private readonly jwtService: JwtService,
private readonly prisma: PrismaService,
) {}

async createToken(user: Credential) {
const token = {
accessToken: this.jwtService.sign(
{
id: user.id,
},
{
expiresIn: '1 h',
subject: String(user.id),
},
),

refreshToken: this.jwtService.sign(
{
id: user.id,
},
{
expiresIn: '3 h',
subject: String(user.id),
},
),
};

return token;
}

async login(email: string, password: string) {
const hashedEmail = await hashDataAsync({
unhashedData: email,
salt: process.env.SALT_DATA_HASH,
});

const user = await this.prisma.credential.findUnique({
where: {
email: hashedEmail,
},
});

if (!user) {
throw new BadRequestException('Usuário não encontrado.');
}

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

if (!comparePassword) {
throw new BadRequestException('A senha está incorreta.');
}

return this.createToken(user);
}
}
Loading
Loading