Skip to content

Commit

Permalink
Merge pull request #62 from Boost-Coder/feature/jwtRefresh-#61
Browse files Browse the repository at this point in the history
[#61] refreshToken 보내면 새로운 token 들 반환
  • Loading branch information
koomin1227 authored Apr 16, 2024
2 parents 38a5f94 + 45a4059 commit 52d4625
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 7 deletions.
5 changes: 5 additions & 0 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,9 @@ export class AuthController {
) {
return await this.authService.checkSejongStudent(body, userId);
}

@Post('refresh')
public refreshTokens(@Body('refreshToken') refreshToken: string) {
return this.authService.sendTokens(refreshToken);
}
}
2 changes: 1 addition & 1 deletion src/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ describe('AuthService', () => {
it('should generate access token', function () {
mockJwtService.sign.mockResolvedValue('jwt-token');

service.generateAccessToken(user);
service.generateAccessToken(user.userId);

expect(mockJwtService.sign).toHaveBeenCalledWith({
userId: user.userId,
Expand Down
33 changes: 27 additions & 6 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ export class AuthService {
user = await this.userService.createUser(providerId);
await this.totalService.createTotalPoint(user.userId);
}
const accessToken = this.generateAccessToken(user);
const refreshToken = this.generateRefreshToken(user);
const accessToken = this.generateAccessToken(user.userId);
const refreshToken = this.generateRefreshToken(user.userId);
return { accessToken, refreshToken, isMember };
}

Expand All @@ -42,16 +42,16 @@ export class AuthService {
);
}

generateAccessToken(user: User): string {
generateAccessToken(userId: string): string {
return this.jwtService.sign({
userId: user.userId,
userId: userId,
});
}

generateRefreshToken(user: User): string {
generateRefreshToken(userId: string): string {
return this.jwtService.sign(
{
userId: user.userId,
userId: userId,
},
{
secret: this.configService.get('JWT_REFRESH_SECRET'),
Expand Down Expand Up @@ -143,4 +143,25 @@ export class AuthService {
return { isAuthorized: isSejongJson.result.is_auth };
}
}

public sendTokens(refreshToken: string) {
const payload = this.validateRefreshToken(refreshToken);

return {
accessToken: this.generateAccessToken(payload.userId),
refreshToken: this.generateRefreshToken(payload.userId),
};
}

public validateRefreshToken(refreshToken: string) {
try {
return this.jwtService.verify(refreshToken, {
secret: this.configService.get('JWT_REFRESH_SECRET'),
});
} catch (e) {
if (e instanceof TokenExpiredError) {
throw new UnauthorizedException();
}
}
}
}

0 comments on commit 52d4625

Please sign in to comment.