Skip to content

Commit

Permalink
refactor(auth) : apply redis service in auth domain
Browse files Browse the repository at this point in the history
  • Loading branch information
KNU-K committed Nov 25, 2024
1 parent dae222d commit f3b9b0a
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 8 deletions.
10 changes: 10 additions & 0 deletions src/modules/auth/application/service/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { JwtService } from '@nestjs/jwt';

import { UserService } from '@user/application/service/user.service';
import { jwtConfig } from '@config/jwt.config';
import { RedisService } from '@shared/application/redis/redis.service';

import { AuthResponse, AuthCredentials } from '@auth/application/dto';

Expand All @@ -13,6 +14,7 @@ export class AuthService {
constructor(
private readonly userService: UserService,
private readonly jwtService: JwtService,
private readonly redisService: RedisService,
) {
const config = jwtConfig();
this.refreshJwtSignOptions = config.refreshJwtSignOptions;
Expand All @@ -26,6 +28,14 @@ export class AuthService {
const payload = { id: user.id, sub: user.email, username: user.name };
return AuthResponse.of(await this.issueAccessToken(payload), await this.issueRefreshToken(payload));
}
async refresh(token: string): Promise<AuthResponse> {
const payload = this.jwtService.verify(token, this.refreshJwtSignOptions);
const storedToken = await this.redisService.get(payload.sub);
if (storedToken !== token) {
throw new UnauthorizedException();
}
return AuthResponse.of(await this.issueAccessToken(payload), await this.issueRefreshToken(payload));
}

private async issueAccessToken(payload) {
return await this.issueToken(payload, this.accessJwtSignOptions);
Expand Down
14 changes: 6 additions & 8 deletions src/modules/auth/presentation/controller/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { Controller, Get, Post, Body, UseGuards, Request } from '@nestjs/common';
import { Controller, Post, Body } from '@nestjs/common';
import { AuthService } from '@auth/application/service/auth.service';
import { AuthCredentials } from '@auth/application/dto/auth-request.dto';
import { ResponseEntity } from '@common/dto/response-entity.dto';
import { AuthGuard } from '../guard/auth.guard';

@Controller('auth')
export class AuthController {
Expand All @@ -14,10 +13,9 @@ export class AuthController {
return ResponseEntity.success(authResponse, '로그인에 성공');
}

// @Get('test')
// @UseGuards(AuthGuard)
// async test(@Request() req) {
// const userId = req.user.id; // 요청 객체에서 userId 접근
// return `User ID: ${userId}`;
// }
@Post('refresh')
async refresh(@Body() refreshToken: { token: string }) {
const authResponse = await this.authService.refresh(refreshToken.token);
return ResponseEntity.success(authResponse, '토큰 갱신에 성공');
}
}

0 comments on commit f3b9b0a

Please sign in to comment.