Skip to content

Commit

Permalink
Merge pull request #49 from GoLembrar/feat-refresh-token
Browse files Browse the repository at this point in the history
Feat refresh token
  • Loading branch information
Rip4568 authored Jul 15, 2024
2 parents 87a5677 + f464afb commit 6b512d5
Show file tree
Hide file tree
Showing 6 changed files with 114 additions and 50 deletions.
11 changes: 10 additions & 1 deletion http/user-requests.http
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,19 @@ POST http://localhost:3000/auth HTTP/1.1
Content-Type: application/json

{
"email" : "test@email.com",
"email" : "jhone.test14@gmail.com",
"password" : "senhaForte"
}

###

POST http://localhost:3000/auth/refresh-token HTTP/1.1
Content-Type: application/json

{
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjlkMmJlMGM1LTFhYzYtNGE0Yy05YmRkLWJjNTg1NmJiMzI0NyIsImVtYWlsIjoiamhvbmUudGVzdDE0QGdtYWlsLmNvbSIsIm5hbWUiOiJqaG9uZSIsImlhdCI6MTcyMDU3ODM3NiwiZXhwIjoxNzIwODM3NTc2fQ.JJ-DfAXpOQzqA7YlIcgm3UYnB09w1fGXqHWxNKZa4hk"
}

### get all users account

GET http://localhost:3000/user
94 changes: 53 additions & 41 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,15 +39,15 @@
"@nestjs/mapped-types": "*",
"@nestjs/microservices": "^10.3.8",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/schedule": "^4.0.2",
"@nestjs/schedule": "^4.1.0",
"@nestjs/serve-static": "^4.0.2",
"@nestjs/swagger": "^7.1.17",
"@prisma/client": "^5.7.0",
"@prisma/client": "^5.15.1",
"@sendgrid/mail": "^8.1.3",
"amqp-connection-manager": "^4.1.14",
"amqplib": "^0.10.4",
"bcrypt": "^5.1.1",
"cache-manager": "^5.6.1",
"cache-manager": "^5.7.1",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.0",
"dotenv": "^16.4.5",
Expand Down Expand Up @@ -80,7 +80,7 @@
"eslint-plugin-prettier": "^5.0.0",
"husky": "^9.0.11",
"prettier": "^3.0.0",
"prisma": "^5.12.1",
"prisma": "^5.15.1",
"source-map-support": "^0.5.21",
"supertest": "^6.3.3",
"ts-loader": "^9.4.3",
Expand Down
7 changes: 6 additions & 1 deletion src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Body, Controller, Post } from '@nestjs/common';
import { Body, Controller, Post, Put } from '@nestjs/common';
import { AuthService } from './auth.service';
import { CredentialsDto } from './dto/credentials.dto';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
Expand All @@ -17,4 +17,9 @@ export class AuthController {
login(@Body() credentials: CredentialsDto) {
return this.authService.login(credentials);
}

@Post('refresh-token')
async refreshToken(@Body() body: { refreshToken: string }) {
return this.authService.refreshToken(body.refreshToken);
}
}
1 change: 1 addition & 0 deletions src/auth/auth.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,6 @@ import { JwtModule } from '@nestjs/jwt';
],
controllers: [AuthController],
providers: [AuthService, PrismaService],
exports: [AuthService, PrismaService],
})
export class AuthModule {}
43 changes: 40 additions & 3 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ export class AuthService {
private readonly jwt: JwtService,
) {}

async login(credentials: CredentialsDto): Promise<{ token: string }> {
async login(
credentials: CredentialsDto,
): Promise<{ token: string; refreshToken: string }> {
const foundUser: Users = await this.prisma.users.findFirst({
where: {
email: credentials.email,
Expand All @@ -36,7 +38,42 @@ export class AuthService {
name: foundUser.name,
};

const token = this.jwt.sign(jwtPayloadData);
return { token };
const token = this.jwt.sign(jwtPayloadData, {
expiresIn: process.env.JWT_EXP,
});
const refreshToken = this.jwt.sign(jwtPayloadData, {
expiresIn: process.env.JWT_REFRESH_EXP,
});

return { token, refreshToken };
}

async refreshToken(refreshToken: string) {
try {
const payload: JwtPayload = await this.jwt.verifyAsync(refreshToken, {
secret: process.env.JWT_SECRET,
});

const user = await this.prisma.users.findUnique({
where: { id: payload.id, email: payload.email, name: payload.name },
});

if (!user) throw new UnauthorizedException('Usuário não encontrado');

const token = this.jwt.sign(
{ id: user.id },
{ expiresIn: process.env.JWT_EXP },
);

return { token };
} catch (error) {
if (error.name === 'TokenExpiredError') {
throw new UnauthorizedException(
'Refresh token expirado, por favor, relogue',
);
} else {
throw new UnauthorizedException('Refresh token inválido');
}
}
}
}

0 comments on commit 6b512d5

Please sign in to comment.