Skip to content

Commit 9933448

Browse files
committed
update refresh token
1 parent 5a3693d commit 9933448

File tree

8 files changed

+111
-10
lines changed

8 files changed

+111
-10
lines changed

public/openapi.yml

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,10 @@ paths:
130130
$ref: '#/components/schemas/AuthSuccessResponse'
131131
/auth/refresh:
132132
post:
133+
security:
134+
- ApiKey: []
135+
- RefreshToken: []
136+
133137
tags:
134138
- "Authentication"
135139
description: ""
@@ -243,6 +247,11 @@ components:
243247
type: http
244248
scheme: bearer
245249
bearerFormat: JWT # optional, arbitrary value for documentation purposes
250+
RefreshToken:
251+
description: "Hanya dipakai di `/auth/refresh`"
252+
type: http
253+
scheme: bearer
254+
bearerFormat: JWT # optional, arbitrary value for documentation purposes
246255
schemas:
247256
LoginRequestBody:
248257
type: object

src/@types/index.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,6 @@ type UserInAuth = {
88
id: number,
99
name: string,
1010
email: string,
11-
unique_id: string,
11+
deviceUniqueId: string,
1212
fcm_token?: string,
1313
}

src/apps/auth/auth.controller.ts

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { Body, Controller, Get, HttpCode, HttpStatus, Post, Req } from '@nestjs/common';
22
import { Request } from 'express';
3-
import { UseJwtGuard } from 'src/filters/jwt.guard';
3+
import { UseJwtGuard, UseJwtRefreshGuard } from 'src/filters/jwt.guard';
44
import { Response } from 'src/utils/response.utils';
55
import { AuthService } from './auth.service';
66
import { LoginDTO } from './dto/login.dto';
@@ -29,13 +29,30 @@ export class AuthController {
2929
});
3030
}
3131

32+
@UseJwtRefreshGuard()
33+
@Post('/refresh')
34+
@HttpCode(HttpStatus.OK)
35+
async refresh(
36+
@I18n() i18n: I18nContext,
37+
@Req() req: Request,
38+
) {
39+
40+
const refreshResponse = await this.authService.refresh(req);
41+
42+
return Response.success({
43+
message: i18n.t('auth.refresh.response-success'),
44+
data: refreshResponse,
45+
});
46+
}
47+
3248
@Post('/register')
3349
@HttpCode(HttpStatus.CREATED)
3450
async register(
3551
@I18n() i18n: I18nContext,
3652
@Req() req: Request,
3753
@Body() data: RegisterDTO,
3854
) {
55+
3956
const registerResponse = await this.authService.register(data, req);
4057

4158
return Response.success({

src/apps/auth/auth.module.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,5 @@ import { RedisModule } from 'src/modules/redis/redis.module';
1515
providers: [AuthService, AccessTokenStrategy, RefreshTokenStrategy],
1616
controllers: [AuthController]
1717
})
18+
1819
export class AuthModule {}

src/apps/auth/auth.service.ts

Lines changed: 63 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { HttpException, HttpStatus, Injectable, UnauthorizedException } from '@nestjs/common';
1+
import { HttpException, HttpStatus, Injectable, UnauthorizedException } from '@nestjs/common';
22
import { JwtService } from '@nestjs/jwt';
33
import { InjectRepository } from '@nestjs/typeorm';
44
import { User } from 'src/entities/user.entity';
@@ -11,13 +11,17 @@ import { Request } from 'express';
1111
import { UserDevice } from 'src/entities/user-device.entity';
1212
import { DeviceDTO } from './dto/device.dto';
1313
import { RedisService } from 'src/modules/redis/redis.service';
14+
import { I18nService } from 'nestjs-i18n';
1415

1516
@Injectable()
1617
export class AuthService {
1718

1819
constructor(
19-
@InjectRepository(User) private usersRepository: Repository<User>,
20-
@InjectRepository(UserDevice) private userDevicesRepository: Repository<UserDevice>,
20+
@InjectRepository(User)
21+
private usersRepository: Repository<User>,
22+
@InjectRepository(UserDevice)
23+
private userDevicesRepository: Repository<UserDevice>,
24+
private readonly i18n: I18nService,
2125
private readonly redisService: RedisService,
2226
private readonly jwtService: JwtService,
2327
private readonly configService: ConfigService,
@@ -28,7 +32,7 @@ export class AuthService {
2832
try {
2933
this.userDevicesRepository.update({
3034
user_id: userAuth.id,
31-
unique_id: userAuth.unique_id
35+
unique_id: userAuth.deviceUniqueId,
3236
}, {
3337
access_token: null,
3438
refresh_token: null,
@@ -44,6 +48,57 @@ export class AuthService {
4448
}
4549
}
4650

51+
async refresh(req: Request) {
52+
53+
const deviceUniqueId = req.user.deviceUniqueId;
54+
55+
const device: UserDevice = await this.userDevicesRepository.findOneBy({
56+
user_id: req.user.id,
57+
unique_id: deviceUniqueId,
58+
});
59+
60+
const token = req.header('authorization').replace('Bearer ', '');
61+
console.log(device.refresh_token)
62+
if(!await this.checkPassword(token, device.refresh_token)) {
63+
throw new HttpException(this.i18n.t('auth.refresh.invalid-token'), HttpStatus.BAD_REQUEST);
64+
}
65+
66+
const user = await this.usersRepository.findOneBy({
67+
id: req.user.id,
68+
})
69+
70+
const deviceDTO = new DeviceDTO();
71+
deviceDTO.brand = device.brand;
72+
deviceDTO.id = device.unique_id;
73+
deviceDTO.name = device.name;
74+
deviceDTO.os = device.os;
75+
76+
const tokens = await this.getTokens(user, deviceDTO);
77+
78+
await this.userDevicesRepository.update({
79+
id: device.id,
80+
}, {
81+
refresh_token: await this.makeHash(tokens.refresh_token),
82+
access_token: await this.makeHash(tokens.access_token),
83+
})
84+
85+
return {
86+
tokens
87+
};
88+
89+
// await this.userDevicesRepository.update({
90+
// id: device.id,
91+
// }, {
92+
// refresh_token: null,
93+
// access_token: null,
94+
// })
95+
96+
// return this.i18n.t('auth.refresh.response-success')
97+
// console.log(device);
98+
99+
// this.checkPassword()
100+
}
101+
47102
async login(data: LoginDTO, req: Request) {
48103
const user = await this.getUser([
49104
{username: data.identity,},
@@ -167,17 +222,19 @@ export class AuthService {
167222
return {
168223
access_token: await this.jwtService.signAsync({
169224
username: user.name,
170-
deviceId: device.id,
225+
deviceUniqueId: device.id,
171226
id: user.id,
172227
}, {
228+
subject: new Date().getTime().toString() + ' | hi',
173229
secret: this.configService.get("JWT_SECRET"),
174230
expiresIn: eval(this.configService.get('JWT_EXP_AT')),
175231
}),
176232
refresh_token: await this.jwtService.signAsync({
177233
username: user.name,
178234
id: user.id,
179-
deviceId: device.id
235+
deviceUniqueId: device.id,
180236
}, {
237+
subject: new Date().getTime().toString() + ' | hi',
181238
secret: this.configService.get("JWT_SECRET_REFRESH"),
182239
// expiresIn: 60 * 60 * 24 * 7,
183240
expiresIn: eval(this.configService.get('JWT_REFRESH_EXP_AT')),

src/apps/auth/strategies/refresh-token.strategy.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { ConfigService } from '@nestjs/config'
22
import { PassportStrategy } from '@nestjs/passport'
33
import { ExtractJwt, Strategy } from 'passport-jwt'
4-
import { Request } from 'express';
54
import { Injectable } from '@nestjs/common';
65

76
@Injectable()
@@ -18,7 +17,7 @@ export class RefreshTokenStrategy extends PassportStrategy(Strategy, 'jwt-refres
1817
}
1918

2019

21-
validate(req: Request, payload: any) {
20+
validate(payload: any) {
2221

2322
return payload;
2423
}

src/i18n/en/auth.json

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"refresh": {
3+
"response-success": "Refreshing token successfull",
4+
"invalid-token": "Invalid refresh token."
5+
},
6+
"login": {
7+
"response-success": "Refresh token successfull"
8+
}
9+
}

src/i18n/id/auth.json

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"refresh": {
3+
"response-success": "Refresh token successfull",
4+
"invalid-token": "Invalid refresh token."
5+
},
6+
"login": {
7+
"response-success": "Refresh token successfull"
8+
}
9+
}

0 commit comments

Comments
 (0)