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

[#7] JWT인증구현 #8

Merged
merged 6 commits into from
Jan 19, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
244 changes: 232 additions & 12 deletions package-lock.json

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,20 @@
"@nestjs/common": "^10.0.0",
"@nestjs/config": "^3.3.0",
"@nestjs/core": "^10.0.0",
"@nestjs/jwt": "^10.2.0",
"@nestjs/mapped-types": "*",
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.0.0",
"@nestjs/typeorm": "^10.0.2",
"@types/passport-jwt": "^4.0.1",
"bcrypt": "^5.1.1",
"bcrypto": "^5.5.2",
"class-validator": "^0.14.1",
"dotenv": "^16.4.5",
"mysql2": "^3.11.4",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"passport-local": "^1.0.0",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1",
"typeorm": "^0.3.20"
Expand All @@ -44,6 +50,7 @@
"@types/express": "^4.17.17",
"@types/jest": "^29.5.2",
"@types/node": "^20.3.1",
"@types/passport-local": "^1.0.38",
"@types/supertest": "^6.0.0",
"@typescript-eslint/eslint-plugin": "^8.0.0",
"@typescript-eslint/parser": "^8.0.0",
Expand Down
11 changes: 9 additions & 2 deletions src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import { Controller } from '@nestjs/common';
import { Controller, Post, UseGuards, Request } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LocalAuthGuard } from './security/passport.jwt';

@Controller('auth')
@Controller()
export class AuthController {
constructor(private readonly authService: AuthService) {}

@Post('/signin')
@UseGuards(LocalAuthGuard)
async singin(@Request() req){
return this.authService.signin(req.user);

Choose a reason for hiding this comment

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

custom decorator 를 통해 더 개선된 코드를 작성할 수 있을 것 같아요.

ref: https://docs.nestjs.com/custom-decorators

Choose a reason for hiding this comment

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

이 부분 반영 안된 것 같습니다~

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

#13

새로 PR로 올렸습니다!
이때 기존 브랜치에 수정한게 아니라 새로만든 브랜치에 코드를 수정해서 신규 PR로 올리게 되었습니다ㅜㅜ

}
}
15 changes: 14 additions & 1 deletion src/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,22 @@
import { Module } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { UsersModule } from 'src/users/users.module';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { JwtStrategy, JwtLocalStrategy } from './security/passport.jwt';
import { jwtConstants } from './constants';

@Module({
imports:[
UsersModule,
JwtModule.register({
secret:jwtConstants.secret,
signOptions: {expiresIn:jwtConstants.expiresIn}
}),
PassportModule
],
controllers: [AuthController],
providers: [AuthService],
providers: [AuthService, JwtStrategy, JwtLocalStrategy],
})
export class AuthModule {}
56 changes: 54 additions & 2 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,56 @@
import { Injectable } from '@nestjs/common';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import * as bcrypt from 'bcrypt';
import { UserEntity } from 'src/users/entities/user.entity';
import { UsersService } from 'src/users/users.service';
import { JwtService } from '@nestjs/jwt';
import { JwtTokenDto } from './dto/token.dto';
import { jwtConstants } from './constants';

@Injectable()
export class AuthService {}
export class AuthService {
constructor(private readonly userService: UsersService,
private readonly jwtService: JwtService) {}

async validateUser(userId: string, password:string): Promise<any>{
const user = await this.userService.findbyId(userId);
if(!user){
throw new UnauthorizedException('아이디 혹은 비밀번호를 확인하세요.');
}

const pwdCheck = bcrypt.compareSync(password, user.password);
if(!pwdCheck){
throw new UnauthorizedException('아이디 혹은 비밀번호를 확인히세요.');
} else {
delete user.password
}

return user;
}

async signin(user: UserEntity){
return this.createToken(user);
}

async createToken(user: UserEntity) {
const tokenUserNo = user.userNo;
const tokenDto = new JwtTokenDto();
tokenDto.accessToken = await this.createAccessToken(user);
tokenDto.refreshToken = await this.createRefreshToken(tokenUserNo);

return tokenDto;
}

async createAccessToken(user: UserEntity): Promise<string>{
const payload = {userNo: user.userNo, userId:user.userId}
return this.jwtService.sign({payload},
{secret: jwtConstants.secret,
expiresIn: jwtConstants.expiresIn})
}

async createRefreshToken(userNo: number): Promise<string>{
return this.jwtService.sign({userNo},
{secret:jwtConstants.secret,
expiresIn:jwtConstants.expiresInRefresh})
}

}
5 changes: 5 additions & 0 deletions src/auth/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const jwtConstants = {
secret: 'frogthedev1635@^#$',
expiresIn:'5m',
expiresInRefresh:'2h'
};
18 changes: 9 additions & 9 deletions src/auth/dto/auth.dto.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
import { IsEmpty, IsString, IsEmail, Length, IsAlphanumeric, Matches} from "class-validator";
import {IsString, IsEmpty, IsEmail, Length, IsAlphanumeric, Matches} from "class-validator";
export namespace AuthDTO{
export class SignUp{
//TODO : guard랑 JWT토큰 적용
@IsEmpty()
@IsAlphanumeric()
@IsEmpty({message: '사용자 ID는 공백일 수 없습니다.'})
@IsAlphanumeric("en-US", {message:'사용자 ID는 영어와 숫자만 가능합니다.'})
userId: string;

@IsEmpty()
@IsString()
@Length(2,10)
@IsEmpty({message: '사용자 이름은 공백일 수 없습니다.'})
@IsString({message: '사용자 이름은 문자만 가능합니다.'})
@Length(2,10,{message:'사용자 이름은 최소 2글자에서 10글자 까지 가능합니다.'})
userName: string;

@IsEmpty()
@IsEmpty({message: '사용자 email은 공백일 수 없습니다.'})
@IsEmail()
email:string;

@IsEmpty()
@IsString()
@IsEmpty({message: '사용자 비밀번호는 공백일 수 없습니다.'})
@IsString({message: '사용자 비밀번호는 문자만 가능합니다.'})
@Matches(/^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[!@#$%^&*?_]).{8,20}$/, {
message:
'패스워드는 8~20자리이며 최소 하나 이상의 영문자, 최소 하나 이상의 숫자, 최소 하나 이상의 특수문자를 입력해야 합니다.',
Expand Down
4 changes: 4 additions & 0 deletions src/auth/dto/token.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export class JwtTokenDto {
accessToken;
refreshToken;
}
51 changes: 51 additions & 0 deletions src/auth/security/passport.jwt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";
import { Strategy as LocalStrategy } from "passport-local";
import { AuthGuard } from "@nestjs/passport";

import { AuthService } from "../auth.service";
import { jwtConstants } from "../constants";

@Injectable()
export class JwtLocalStrategy extends PassportStrategy(LocalStrategy,'local'){
constructor(private readonly authService: AuthService){
super({
usernameField: 'userId',
passwordField: 'password'
})
}

async validate(userId:string, password:string):Promise<any>{
const user = await this.authService.validateUser(userId, password);
// 사용자가 뭔가 입력하면 무조건 아이디 혹은 비밀번호를 확인하세요 라고 뜨는거 아닌가?
if(!user) {
return new UnauthorizedException({message: '회원 정보가 존재하지 않습니다.'});
}
return user;

}
}

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy,'jwt'){
constructor(){
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: jwtConstants.secret,
ignoreException: false,
algorithms: ['HS256'],
})
}

async validate(payload: any) {
return { ...payload };
}
}


@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt'){}

@Injectable()
export class LocalAuthGuard extends AuthGuard('local'){}
27 changes: 18 additions & 9 deletions src/users/users.controller.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Controller, Get, Post, Body, Patch, Param, Delete, ConflictException } from '@nestjs/common';
import { Controller, Get, Post, Body, Patch, Param, Delete,
ConflictException, UseGuards, Req,ParseIntPipe } from '@nestjs/common';
import { UsersService } from './users.service';
import { AuthDTO } from 'src/auth/dto/auth.dto';
import { userDto } from './dto/user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { JwtAuthGuard } from 'src/auth/security/passport.jwt';

@Controller('users')
export class UsersController {
Expand All @@ -24,22 +25,30 @@ export class UsersController {
return '회원가입성공';
}

@UseGuards(JwtAuthGuard)
@Get('/')
async getProfile(@Req() req: any){
const user = req.user;
return user;
}


@Get()
findAll() {
return this.usersService.findAll();
}

@Get(':id')
findOne(@Param('id') id: string) {
return this.usersService.findOne(+id);
@Get('/userNo')
findOne(@Param('userNo', ParseIntPipe) userNo: number) {
return this.usersService.findOne(userNo);
}

@Patch(':id')
update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto) {
return this.usersService.update(+id, updateUserDto);
@Patch('/userNo')
update(@Param('userNo', ParseIntPipe) userNo: number, @Body() updateUserDto: UpdateUserDto) {
return this.usersService.update(userNo, updateUserDto);
}

@Delete(':id')
@Delete('/id')
remove(@Param('id') id: string) {
return this.usersService.remove(+id);
}
Expand Down