diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts index 3ce5151..94652f4 100644 --- a/src/auth/auth.controller.ts +++ b/src/auth/auth.controller.ts @@ -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); + } } diff --git a/src/auth/auth.service.spec.ts b/src/auth/auth.service.spec.ts index 7d95968..0555787 100644 --- a/src/auth/auth.service.spec.ts +++ b/src/auth/auth.service.spec.ts @@ -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, diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts index 5b5858d..963c3d9 100644 --- a/src/auth/auth.service.ts +++ b/src/auth/auth.service.ts @@ -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 }; } @@ -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'), @@ -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(); + } + } + } }