Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BE/#412] access token 블랙리스트 도입 #416

Merged
merged 5 commits into from
Dec 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions BE/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { RedisConfigProvider } from './config/redis.config';
useClass: MysqlConfigProvider,
}),
CacheModule.registerAsync({
isGlobal: true,
useClass: RedisConfigProvider,
}),
PostsBlockModule,
Expand Down
1 change: 1 addition & 0 deletions BE/src/config/redis.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export class RedisConfigProvider implements CacheOptionsFactory {
store: redisStore,
host: this.configService.get('REDIS_HOST'),
port: this.configService.get('REDIS_PORT'),
password: this.configService.get('REDIS_PASSWORD'),
};
}
}
5 changes: 3 additions & 2 deletions BE/src/login/login.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,9 @@ export class LoginController {
checkAccessToken() {}

@Post('logout')
logout(@Headers('Authorization') token, @UserHash() userId) {
@UseGuards(AuthGuard)
async logout(@Headers('Authorization') token) {
const accessToken = token.split(' ')[1];
this.loginService.logout(userId, accessToken);
await this.loginService.logout(accessToken);
}
}
13 changes: 10 additions & 3 deletions BE/src/login/login.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { Inject, Injectable, Logger } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { UserEntity } from '../entities/user.entity';
Expand All @@ -9,6 +9,7 @@ import { AppleLoginDto } from './dto/appleLogin.dto';
import * as jwt from 'jsonwebtoken';
import * as jwksClient from 'jwks-rsa';
import { FcmHandler } from '../utils/fcmHandler';
import { CACHE_MANAGER, CacheStore } from '@nestjs/cache-manager';

export interface SocialProperties {
OAuthDomain: string;
Expand All @@ -30,6 +31,7 @@ export class LoginService {
private configService: ConfigService,
private jwtService: JwtService,
private fcmHandler: FcmHandler,
@Inject(CACHE_MANAGER) private cacheManager: CacheStore,
) {
this.jwksClient = jwksClient({
jwksUri: 'https://appleid.apple.com/auth/keys',
Expand All @@ -45,8 +47,13 @@ export class LoginService {
return { access_token: accessToken, refresh_token: refreshToken };
}

async logout(userId, accessToken) {
await this.fcmHandler.removeRegistrationToken(userId);
async logout(accessToken) {
const decodedToken: any = jwt.decode(accessToken);
if (decodedToken && decodedToken.exp) {
await this.fcmHandler.removeRegistrationToken(decodedToken.userId);
const ttl: number = decodedToken.exp - Math.floor(Date.now() / 1000);
await this.cacheManager.set(accessToken, 'logout', { ttl });
}
}
async registerUser(socialProperties: SocialProperties) {
const userEntity = new UserEntity();
Expand Down
24 changes: 16 additions & 8 deletions BE/src/utils/auth.guard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,32 @@ import {
CanActivate,
ExecutionContext,
HttpException,
Inject,
Injectable,
} from '@nestjs/common';
import * as jwt from 'jsonwebtoken';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';

@Injectable()
export class AuthGuard implements CanActivate {
canActivate(context: ExecutionContext): boolean {
constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
const authorizationHeader = context.switchToHttp().getRequest()
.headers.authorization;

if (!authorizationHeader) throw new HttpException('토큰이 없습니다.', 401);
else {
try {
jwt.verify(authorizationHeader.split(' ')[1], process.env.JWT_SECRET);
return true;
} catch (err) {
return false;
}

const accessToken = authorizationHeader.split(' ')[1];
const isBlackList = await this.cacheManager.get(accessToken);
if (isBlackList) {
throw new HttpException('로그아웃된 토큰입니다.', 401);
}
try {
jwt.verify(accessToken, process.env.JWT_SECRET);
return true;
} catch (err) {
return false;
}
}
}
Loading