Skip to content

Commit

Permalink
[refactor] #4 #5 유저 관리 시스템 디테일 변경 및 guard DB 조회 x
Browse files Browse the repository at this point in the history
- API 들 redirect 안하고 send(200) 식으로 변경

- guard에서 DB 조회하는 로직을 변경
  • Loading branch information
comeintostout committed Nov 21, 2022
1 parent 7d54cda commit 31269e8
Show file tree
Hide file tree
Showing 6 changed files with 54 additions and 32 deletions.
12 changes: 4 additions & 8 deletions backend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@
"@nestjs/platform-express": "^9.0.0",
"@nestjs/typeorm": "^9.0.1",
"@types/cookie-parser": "^1.4.3",
"@types/passport": "^1.0.11",
"class-transformer": "^0.5.1",
"class-validator": "^0.13.2",
"cookie-parser": "^1.4.6",
"passport": "^0.6.0",
"passport-jwt": "^4.0.0",
"pg": "^8.8.0",
"reflect-metadata": "^0.1.13",
Expand Down
3 changes: 3 additions & 0 deletions backend/src/auth/dto/user-data.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ export class UserDataDto {
@IsNotEmpty()
@IsString()
social: socialPlatform;

@IsString()
nickname: string;
}

export class UserDataFromSocialDto {
Expand Down
17 changes: 7 additions & 10 deletions backend/src/auth/jwt-auth.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { User } from './entity/user.entity';
import { UserService } from './user.service';
import { UserDataDto } from './dto/user-data.dto';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'criticalGuard') {
constructor(private userService: UserService) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromExtractors([
request => {
Expand All @@ -19,16 +17,15 @@ export class JwtStrategy extends PassportStrategy(Strategy, 'criticalGuard') {
});
}

// db 참조 하는 guard
async validate(payload: UserDataDto): Promise<boolean> {
const user: User = await this.userService.findUser(payload);

if (!user) {
// 빡빡한 가드
async validate(payload: UserDataDto): Promise<UserDataDto> {
if (!payload.nickname) {
throw new UnauthorizedException(
'서버에 해당 유저가 존재하지 않습니다. 가입을 완료해주세요.'
);
}
return true;

return payload;
}
}

Expand All @@ -46,7 +43,7 @@ export class JwtStrategy2 extends PassportStrategy(Strategy, 'looseGuard') {
});
}

// db 참조 하지 않는 guard
// 느슨한 가드
async validate(payload: UserDataDto): Promise<UserDataDto> {
return payload;
}
Expand Down
32 changes: 21 additions & 11 deletions backend/src/auth/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,25 +46,27 @@ export class UserController {
@Param('social') social: socialPlatform,
@Res() res: Response
): Promise<void> {
// 1단계 : 소셜에 유저 정보 받아오기
const accessToken = await this.authService.socialOauth(social, code);
const userSocialProfile = await this.authService.socialProfileSearch(
social,
accessToken
);

// 우리 유저 인지 확인하기
const userData = await this.userService.findUser({
id: userSocialProfile.id,
social: social,
});

// 탈퇴 감지 로직
if (userData.deleted) {
if (userData && userData.deleted) {
throw new UnauthorizedException('여길 어디 다시와.');
}

const jwt = await this.authService.jwtTokenGenerator({
id: userSocialProfile.id,
social,
nickname: userData?.nickname,
});
res.cookie('accessToken', jwt.accessToken);

Expand All @@ -79,36 +81,44 @@ export class UserController {

@Post()
@UseGuards(AuthGuard('looseGuard'))
signUp(
async signUp(
@Body('signupData', ValidationPipe) signupData: signupDataDto,
@Req() req: any,
@Res() res: Response
): void {
) {
const { id, social }: UserDataDto = req.user;
// body안에 nickname, characterName FE에 전송 요청
this.userService.createUser({
await this.userService.createUser({
id,
social,
nickname: signupData['nickname'],
characterName: signupData['characterName'],
});
res.redirect(process.env.CLIENT_URL);

const jwt = await this.authService.jwtTokenGenerator({
id,
social,
nickname: signupData['nickname'],
});
console.log(jwt.accessToken);
res.cookie('accessToken', jwt.accessToken);
res.send(200);
}

@Get('/logout')
logout(@Res() res: Response): void {
res.cookie('accessToken', '', {
maxAge: 0,
});
res.redirect(process.env.CLIENT_URL);
res.send(200);
}

@Delete()
@UseGuards(AuthGuard('looseGuard'))
@UseGuards(AuthGuard('criticalGuard'))
deleteUser(@Req() req: any, @Res() res: Response) {
const { id, social }: UserDataDto = req.user;
const { id, social, nickname }: UserDataDto = req.user;

this.userService.deleteUser({ id, social });
res.redirect(process.env.CLIENT_URL);
this.userService.deleteUser({ id, social, nickname });
res.send(200);
}
}
20 changes: 17 additions & 3 deletions backend/src/auth/user.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { Injectable } from '@nestjs/common';
import {
Injectable,
NotAcceptableException,
NotFoundException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserDataDto } from './dto/user-data.dto';
Expand All @@ -11,14 +15,24 @@ export class UserService {
) {}

async createUser(signupData: any): Promise<void> {
await this.userRepository.save(signupData);
try {
await this.userRepository.save(signupData);
} catch (e) {
throw new NotAcceptableException('닉네임이 중복됩니다.');
}
}

async findUser(searchOptions: object): Promise<User> {
return await this.userRepository.findOneBy(searchOptions);
}

async deleteUser(userDataToDelete: UserDataDto) {
await this.userRepository.update(userDataToDelete, { deleted: true });
try {
await this.userRepository.update(userDataToDelete, { deleted: true });
} catch (e) {
throw new NotFoundException(
'해당 유저를 찾을 수 없어 삭제할 수 없습니다.'
);
}
}
}

0 comments on commit 31269e8

Please sign in to comment.