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/#417] RefreshToken Redis 저장 #424

Merged
merged 4 commits into from
Dec 9, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion BE/src/login/login.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export class LoginController {
async refreshToken(@Body('refresh_token') refreshToken) {
try {
const payload = this.loginService.validateToken(refreshToken, 'refresh');
return await this.loginService.refreshToken(payload);
return await this.loginService.refreshToken(refreshToken, payload);
} catch (e) {
throw new HttpException('refresh token이 유효하지 않음', 403);
}
Expand Down
27 changes: 22 additions & 5 deletions BE/src/login/login.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Inject, Injectable, Logger } from '@nestjs/common';
import { HttpException, Inject, Injectable, Logger } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { UserEntity } from '../entities/user.entity';
Expand Down Expand Up @@ -44,6 +44,11 @@ export class LoginService {
}
const accessToken = this.generateAccessToken(user);
const refreshToken = this.generateRefreshToken(user);
await this.cacheManager.set(
user.user_hash,
refreshToken,
60 * 60 * 24 * 14,
);
return { access_token: accessToken, refresh_token: refreshToken };
}

Expand All @@ -53,6 +58,7 @@ export class LoginService {
await this.fcmHandler.removeRegistrationToken(decodedToken.userId);
const ttl: number = decodedToken.exp - Math.floor(Date.now() / 1000);
await this.cacheManager.set(accessToken, 'logout', { ttl });
await this.cacheManager.del(decodedToken.userId);
}
}
async registerUser(socialProperties: SocialProperties) {
Expand Down Expand Up @@ -166,13 +172,23 @@ export class LoginService {
});
}

async refreshToken(payload): Promise<JwtTokens> {
async refreshToken(refreshtoken, payload): Promise<JwtTokens> {
const user = await this.userRepository.findOne({
where: { user_hash: payload.userId },
});
const accessToken = this.generateAccessToken(user);
const refreshToken = this.generateRefreshToken(user);
return { access_token: accessToken, refresh_token: refreshToken };

if ((await this.cacheManager.get(user.user_hash)) === refreshtoken) {
const accessToken = this.generateAccessToken(user);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

redis에 저장된 refesh token만 사용할 수 있게 되었네요

const refreshToken = this.generateRefreshToken(user);
await this.cacheManager.set(
user.user_hash,
refreshToken,
60 * 60 * 24 * 2,
);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

환경변수로 하면 더 좋을 것 같네요~

return { access_token: accessToken, refresh_token: refreshToken };
} else {
throw new HttpException('refresh token이 유효하지 않음', 403);
}
}

async loginAdmin(id) {
Expand All @@ -181,6 +197,7 @@ export class LoginService {
});
const accessToken = this.generateAccessToken(user);
const refreshToken = this.generateRefreshToken(user);
await this.cacheManager.set(user.user_hash, refreshToken, 60 * 60 * 24 * 2);
return { access_token: accessToken, refresh_token: refreshToken };
}
}
10 changes: 8 additions & 2 deletions BE/src/users/users.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import {
Body,
ParseFilePipe,
MaxFileSizeValidator,
Header,
Headers,
} from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './createUser.dto';
Expand Down Expand Up @@ -58,8 +60,12 @@ export class UsersController {
}

@Delete(':id')
async usersRemove(@Param('id') id: string, @UserHash() userId) {
await this.usersService.removeUser(id, userId);
async usersRemove(
@Param('id') id: string,
@UserHash() userId: string,
@Headers('authorization') token: string,
) {
await this.usersService.removeUser(id, userId, token);
}

@Patch(':id')
Expand Down
3 changes: 2 additions & 1 deletion BE/src/users/users.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { BlockUserEntity } from '../entities/blockUser.entity';
import { BlockPostEntity } from '../entities/blockPost.entity';
import { AuthGuard } from 'src/utils/auth.guard';
import { RegistrationTokenEntity } from '../entities/registrationToken.entity';
import { FcmHandler } from 'src/utils/fcmHandler';

@Module({
imports: [
Expand All @@ -23,6 +24,6 @@ import { RegistrationTokenEntity } from '../entities/registrationToken.entity';
]),
],
controllers: [UsersController],
providers: [UsersService, S3Handler, AuthGuard],
providers: [UsersService, S3Handler, AuthGuard, FcmHandler],
})
export class UsersModule {}
16 changes: 14 additions & 2 deletions BE/src/users/users.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { HttpException, Injectable } from '@nestjs/common';
import { HttpException, Inject, Injectable } from '@nestjs/common';
import { CreateUserDto } from './createUser.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { UserEntity } from 'src/entities/user.entity';
Expand All @@ -12,10 +12,14 @@ import { BlockUserEntity } from '../entities/blockUser.entity';
import { BlockPostEntity } from '../entities/blockPost.entity';
import { RegistrationTokenEntity } from '../entities/registrationToken.entity';
import { ConfigService } from '@nestjs/config';
import * as jwt from 'jsonwebtoken';
import { FcmHandler } from 'src/utils/fcmHandler';
import { CACHE_MANAGER, CacheStore } from '@nestjs/cache-manager';

@Injectable()
export class UsersService {
constructor(
@Inject(CACHE_MANAGER) private cacheManager: CacheStore,
@InjectRepository(PostEntity)
private postRepository: Repository<PostEntity>,
@InjectRepository(UserEntity)
Expand All @@ -30,6 +34,7 @@ export class UsersService {
private registrationTokenRepository: Repository<RegistrationTokenEntity>,
private s3Handler: S3Handler,
private configService: ConfigService,
private fcmHandler: FcmHandler,
) {}

async createUser(imageLocation: string, createUserDto: CreateUserDto) {
Expand Down Expand Up @@ -57,8 +62,15 @@ export class UsersService {
}
}

async removeUser(id: string, userId) {
async removeUser(id: string, userId: string, accessToken: string) {
const userPk = await this.checkAuth(id, userId);
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);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

유저 탈퇴할 때 registration token 삭제는 까먹었는데 넣어주셔서 감사합니다

await this.cacheManager.set(accessToken, 'logout', { ttl });
}

await this.deleteCascadingUser(userPk, userId);
return true;
}
Expand Down
Loading