-
Notifications
You must be signed in to change notification settings - Fork 0
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
[#7] JWT인증구현 #8
Changes from 1 commit
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
912164f
[#7] JWT인증구현
sejin5 602cccb
[#7-2] 인증 구현 및 회원가입 개선
sejin5 80ce0a9
[#9] 지도 REST API 연동
sejin5 b6dbfd4
[#7-3] 인증구현 파일삭제
sejin5 d183577
Merge pull request #11 from f-lab-edu/feature/10
sejin5 5cad772
Merge pull request #10 from f-lab-edu/feature/9
sejin5 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}) | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
export const jwtConstants = { | ||
secret: 'frogthedev1635@^#$', | ||
expiresIn:'5m', | ||
expiresInRefresh:'2h' | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
export class JwtTokenDto { | ||
accessToken; | ||
refreshToken; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'){} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이 부분 반영 안된 것 같습니다~
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
#13
새로 PR로 올렸습니다!
이때 기존 브랜치에 수정한게 아니라 새로만든 브랜치에 코드를 수정해서 신규 PR로 올리게 되었습니다ㅜㅜ