nestjs_auth...

This commit is contained in:
최준흠 2022-09-14 13:10:00 +09:00
parent bd66031312
commit d5e6e88461
4 changed files with 40 additions and 35 deletions

View File

@ -9,20 +9,17 @@ import { LocalAuthGuard } from './guards/local.auth.guard'
export class AuthController { export class AuthController {
constructor(private authService: AuthService) {} constructor(private authService: AuthService) {}
//local.strategy의 validate에서 true인경우 넘어옴
@UseGuards(LocalAuthGuard) @UseGuards(LocalAuthGuard)
//local.strategy의 validate에서 Login처리후 넘어옴
//결과오류시 NotFoundError: No User found라고 console log에 출력됨
@Post('login') @Post('login')
async login(@Request() req) { async login(@Request() req) {
return await this.authService.login(req.user) return await this.authService.login(req.user)
} }
//사용자정보 AccesToken 확인용 //jwt.strategy의 validate에서 true인경우 넘어옴
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
//jwt.strategy의 validate에서 token확인후 넘어옴
@Get('profile') @Get('profile')
async getProfile(@Request() req) { async getProfile(@Request() req) {
//console.log(req)
return req.user return req.user
} }

View File

@ -1,7 +1,7 @@
/* eslint-disable prettier/prettier */ /* eslint-disable prettier/prettier */
import { Injectable, UnauthorizedException } from '@nestjs/common' import { Injectable, UnauthorizedException } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt' import { JwtService } from '@nestjs/jwt'
import { User } from '@prisma/client' import { Prisma, User } from '@prisma/client'
import { UserDTO } from 'src/user/dtos/user.dto' import { UserDTO } from 'src/user/dtos/user.dto'
import { UserService } from '../user/user.service' import { UserService } from '../user/user.service'
import { jwtConstants } from './guards/jwt.constants' import { jwtConstants } from './guards/jwt.constants'
@ -23,33 +23,25 @@ export class AuthService {
// }) // })
return password return password
} }
//app.controller.ts에서 @UseGuards(AuthGuard('local'))용 //app.controller.ts에서 AuthGuard('local') 또는 AuthGuard('jwt')용
async validateUser(email: string, password: string): Promise<any> { async validateUser(where: Prisma.UserWhereInput): Promise<any> {
const user = await this.userService try {
.fetchOne({ email: email }) await this.userService.fetchOne(where)
.catch((error) => { } catch (e) {
throw new UnauthorizedException('사용자를 찾을 수 없습니다.' + error) throw new UnauthorizedException('계정 확인이 되지 않습니다.')
})
const encryptedPassword = await this.getEcryptedPassword(password)
if (user && user.password === encryptedPassword) {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { password, ...result } = user
return result
} else {
throw new UnauthorizedException('암호가 맞지 않습니다.')
} }
} }
async login(user: User): Promise<any> { async login(user: User): Promise<any> {
return await this.getTokens(user) // eslint-disable-next-line @typescript-eslint/no-unused-vars
const { password, ...result } = user
return (result['access_token'] = await this.getAccessToken(user))
} }
async register(data: UserDTO): Promise<User> { async register(data: UserDTO): Promise<any> {
const tokens = await this.getTokens(data) data.refresh_token = await this.getRefreshToken()
data.refresh_token = tokens.refresh_token
data.password = await this.getEcryptedPassword(data.password) data.password = await this.getEcryptedPassword(data.password)
await this.userService.add(data) return await this.login(await this.userService.add(data))
return tokens
} }
//Access Token 재발행 //Access Token 재발행

View File

@ -1,16 +1,17 @@
import { ExtractJwt, Strategy } from 'passport-jwt' import { ExtractJwt, Strategy } from 'passport-jwt'
import { PassportStrategy } from '@nestjs/passport' import { PassportStrategy } from '@nestjs/passport'
import { Injectable } from '@nestjs/common' import { Injectable, UnauthorizedException } from '@nestjs/common'
import { jwtConstants } from './jwt.constants' import { jwtConstants } from './jwt.constants'
import { AuthService } from '../auth.service'
type JwtPayload = { type jwtPayloadType = {
email: string email: string
name: string name: string
} }
@Injectable() @Injectable()
export class JwtAuthStrategy extends PassportStrategy(Strategy, 'jwt') { export class JwtAuthStrategy extends PassportStrategy(Strategy, 'jwt') {
constructor() { constructor(private authService: AuthService) {
super({ super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false, ignoreExpiration: false,
@ -18,10 +19,15 @@ export class JwtAuthStrategy extends PassportStrategy(Strategy, 'jwt') {
}) })
} }
async validate(payload: JwtPayload) { //AccessToken 인증
return { async validate(payload: jwtPayloadType) {
email: payload.email, try {
name: payload.name return await this.authService.validateUser({
email: payload.email,
name: payload.name
})
} catch (e) {
throw new UnauthorizedException(e)
} }
} }
} }

View File

@ -1,7 +1,7 @@
/* eslint-disable prettier/prettier */ /* eslint-disable prettier/prettier */
import { Strategy } from 'passport-local' import { Strategy } from 'passport-local'
import { PassportStrategy } from '@nestjs/passport' import { PassportStrategy } from '@nestjs/passport'
import { Injectable } from '@nestjs/common' import { Injectable, UnauthorizedException } from '@nestjs/common'
import { AuthService } from '../auth.service' import { AuthService } from '../auth.service'
@Injectable() @Injectable()
@ -14,6 +14,16 @@ export class LocalStrategy extends PassportStrategy(Strategy) {
//Login인증용 //Login인증용
async validate(email: string, password: string): Promise<any> { async validate(email: string, password: string): Promise<any> {
return await this.authService.validateUser(email, password) try {
const encryptedPassword = await this.authService.getEcryptedPassword(
password
)
return await this.authService.validateUser({
email: email,
password: encryptedPassword
})
} catch (e) {
throw new UnauthorizedException(e)
}
} }
} }