-
Notifications
You must be signed in to change notification settings - Fork 20
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Implement refresh token in backend * Implement token refresh with axios interceptor * Fix typo * Apply lint * Add Refresh token initialization * Update Axios interceptor to handle token expiration and refresh logic * Update environment variable comments for clarity * Separate dtos related to refresh token * Add `@ApiProperty` decorator * Update `@ApiBody` and `@ApiResponse` type * Separate JWT secrets for access and refresh tokens * Add logout logic and remove duplicate call * Update env variable comments for clarity * Split JwtService for access and refresh tokens * Fix interceptor logic for refresh token * Add error config token
Showing
17 changed files
with
278 additions
and
63 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,47 @@ | ||
import { Module } from "@nestjs/common"; | ||
import { AuthService } from "./auth.service"; | ||
import { ConfigService } from "@nestjs/config"; | ||
import { JwtService } from "@nestjs/jwt"; | ||
import { UsersModule } from "src/users/users.module"; | ||
import { JwtInject } from "src/utils/constants/jwt-inject"; | ||
import { AuthController } from "./auth.controller"; | ||
import { AuthService } from "./auth.service"; | ||
import { GithubStrategy } from "./github.strategy"; | ||
import { ConfigService } from "@nestjs/config"; | ||
import { JwtModule } from "@nestjs/jwt"; | ||
import { JwtRefreshStrategy } from "./jwt-refresh.strategy"; | ||
import { JwtStrategy } from "./jwt.strategy"; | ||
|
||
@Module({ | ||
imports: [ | ||
UsersModule, | ||
JwtModule.registerAsync({ | ||
imports: [UsersModule], | ||
providers: [ | ||
AuthService, | ||
GithubStrategy, | ||
JwtStrategy, | ||
JwtRefreshStrategy, | ||
{ | ||
provide: JwtInject.ACCESS, | ||
useFactory: async (configService: ConfigService) => { | ||
return new JwtService({ | ||
secret: configService.get<string>("JWT_ACCESS_TOKEN_SECRET"), | ||
signOptions: { | ||
expiresIn: `${configService.get("JWT_ACCESS_TOKEN_EXPIRATION_TIME")}s`, | ||
}, | ||
}); | ||
}, | ||
inject: [ConfigService], | ||
}, | ||
{ | ||
provide: JwtInject.REFRESH, | ||
useFactory: async (configService: ConfigService) => { | ||
return { | ||
global: true, | ||
signOptions: { expiresIn: "24h" }, | ||
secret: configService.get<string>("JWT_AUTH_SECRET"), | ||
}; | ||
return new JwtService({ | ||
secret: configService.get<string>("JWT_REFRESH_TOKEN_SECRET"), | ||
signOptions: { | ||
expiresIn: `${configService.get("JWT_REFRESH_TOKEN_EXPIRATION_TIME")}s`, | ||
}, | ||
}); | ||
}, | ||
inject: [ConfigService], | ||
}), | ||
}, | ||
], | ||
providers: [AuthService, GithubStrategy, JwtStrategy], | ||
exports: [JwtInject.ACCESS, JwtInject.REFRESH], | ||
controllers: [AuthController], | ||
}) | ||
export class AuthModule {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,18 +1,64 @@ | ||
import { ConfigModule } from "@nestjs/config"; | ||
import { JwtService } from "@nestjs/jwt"; | ||
import { Test, TestingModule } from "@nestjs/testing"; | ||
import { UsersService } from "../users/users.service"; | ||
import { AuthService } from "./auth.service"; | ||
|
||
describe("AuthService", () => { | ||
let service: AuthService; | ||
let jwtService: JwtService; | ||
|
||
beforeEach(async () => { | ||
const module: TestingModule = await Test.createTestingModule({ | ||
providers: [AuthService], | ||
imports: [ConfigModule.forRoot()], | ||
providers: [ | ||
AuthService, | ||
{ | ||
provide: UsersService, | ||
useValue: { | ||
findOrCreate: jest | ||
.fn() | ||
.mockResolvedValue({ id: "123", nickname: "testuser" }), | ||
}, | ||
}, | ||
{ | ||
provide: JwtService, | ||
useValue: { | ||
sign: jest.fn().mockReturnValue("signedToken"), | ||
verify: jest.fn().mockReturnValue({ sub: "123", nickname: "testuser" }), | ||
}, | ||
}, | ||
], | ||
}).compile(); | ||
|
||
service = module.get<AuthService>(AuthService); | ||
jwtService = module.get<JwtService>(JwtService); | ||
}); | ||
|
||
it("should be defined", () => { | ||
expect(service).toBeDefined(); | ||
}); | ||
|
||
describe("getNewAccessToken", () => { | ||
it("should generate a new access token using refresh token", async () => { | ||
const newToken = await service.getNewAccessToken("refreshToken"); | ||
|
||
expect(newToken).toBe("signedToken"); | ||
expect(jwtService.verify).toHaveBeenCalledWith("refreshToken"); | ||
expect(jwtService.sign).toHaveBeenCalledWith( | ||
{ sub: "123", nickname: "testuser" }, | ||
expect.any(Object) | ||
); | ||
}); | ||
|
||
it("should throw an error if refresh token is invalid", async () => { | ||
jwtService.verify = jest.fn().mockImplementation(() => { | ||
throw new Error("Invalid token"); | ||
}); | ||
|
||
await expect(service.getNewAccessToken("invalidToken")).rejects.toThrow( | ||
"Invalid token" | ||
); | ||
}); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,39 @@ | ||
import { Injectable } from "@nestjs/common"; | ||
import { Inject, Injectable } from "@nestjs/common"; | ||
import { JwtService } from "@nestjs/jwt"; | ||
import { UsersService } from "src/users/users.service"; | ||
import { JwtInject } from "src/utils/constants/jwt-inject"; | ||
import { RefreshTokenResponseDto } from "./dto/refresh-token-response.dto"; | ||
import { LoginRequest } from "./types/login-request.type"; | ||
import { LoginResponse } from "./types/login-response.type"; | ||
|
||
@Injectable() | ||
export class AuthService { | ||
constructor(private usersService: UsersService) {} | ||
constructor( | ||
private readonly usersService: UsersService, | ||
@Inject(JwtInject.ACCESS) private readonly jwtAccessService: JwtService, | ||
@Inject(JwtInject.REFRESH) private readonly jwtRefreshService: JwtService | ||
) {} | ||
|
||
async loginWithSocialProvider(req: LoginRequest): Promise<LoginResponse> { | ||
const user = await this.usersService.findOrCreate( | ||
req.user.socialProvider, | ||
req.user.socialUid | ||
); | ||
|
||
const accessToken = this.jwtAccessService.sign({ sub: user.id, nickname: user.nickname }); | ||
const refreshToken = this.jwtRefreshService.sign({ sub: user.id }); | ||
|
||
return { accessToken, refreshToken }; | ||
} | ||
|
||
async getNewAccessToken(refreshToken: string): Promise<RefreshTokenResponseDto> { | ||
const payload = this.jwtRefreshService.verify(refreshToken); | ||
|
||
const newAccessToken = this.jwtAccessService.sign({ | ||
sub: payload.sub, | ||
nickname: payload.nickname, | ||
}); | ||
|
||
return { newAccessToken }; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
import { ApiProperty } from "@nestjs/swagger"; | ||
|
||
export class RefreshTokenRequestDto { | ||
@ApiProperty({ type: String, description: "The refresh token to request a new access token" }) | ||
refreshToken: string; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
import { ApiProperty } from "@nestjs/swagger"; | ||
|
||
export class RefreshTokenResponseDto { | ||
@ApiProperty({ type: String, description: "The new access token" }) | ||
newAccessToken: string; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
import { Injectable } from "@nestjs/common"; | ||
import { ConfigService } from "@nestjs/config"; | ||
import { PassportStrategy } from "@nestjs/passport"; | ||
import { Strategy as PassportJwtStrategy } from "passport-jwt"; | ||
import { JwtPayload } from "src/utils/types/jwt.type"; | ||
import { AuthorizedUser } from "src/utils/types/req.type"; | ||
|
||
@Injectable() | ||
export class JwtRefreshStrategy extends PassportStrategy(PassportJwtStrategy, "refresh") { | ||
constructor(configService: ConfigService) { | ||
super({ | ||
jwtFromRequest: (req) => { | ||
if (req && req.body.refreshToken) { | ||
return req.body.refreshToken; | ||
} | ||
return null; | ||
}, | ||
ignoreExpiration: false, | ||
secretOrKey: configService.get<string>("JWT_REFRESH_TOKEN_SECRET"), | ||
}); | ||
} | ||
|
||
async validate(payload: JwtPayload): Promise<AuthorizedUser> { | ||
return { id: payload.sub, nickname: payload.nickname }; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
export const JwtInject = { | ||
ACCESS: "JWT_ACCESS_SERVICE", | ||
REFRESH: "JWT_REFRESH_SERVICE", | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters