nestjs_auth...
This commit is contained in:
parent
7a2ea67a69
commit
3a3b2bd1b0
@ -15,21 +15,23 @@ export class AuthController {
|
|||||||
//결과오류시 NotFoundError: No User found라고 console log에 출력됨
|
//결과오류시 NotFoundError: No User found라고 console log에 출력됨
|
||||||
@Post('login')
|
@Post('login')
|
||||||
async login(@Request() req) {
|
async login(@Request() req) {
|
||||||
return this.authService.login(req.user)
|
const response = await this.authService.login(req.user)
|
||||||
|
console.log(response)
|
||||||
|
return response
|
||||||
}
|
}
|
||||||
|
|
||||||
//사용자정보 AccesToken 확인용
|
//사용자정보 AccesToken 확인용
|
||||||
@UseGuards(JwtAuthGuard)
|
@UseGuards(JwtAuthGuard)
|
||||||
//jwt.strategy의 validate에서 token확인후 넘어옴
|
//jwt.strategy의 validate에서 token확인후 넘어옴
|
||||||
@Get('profile')
|
@Get('profile')
|
||||||
getProfile(@Request() req) {
|
async getProfile(@Request() req) {
|
||||||
//console.log(req)
|
//console.log(req)
|
||||||
return req.user
|
return await req.user
|
||||||
}
|
}
|
||||||
|
|
||||||
//사용자 등록
|
//사용자 등록
|
||||||
@Post('register')
|
@Post('register')
|
||||||
add(@Body() data: UserDTO): Promise<User> {
|
async add(@Body() data: UserDTO): Promise<User> {
|
||||||
return this.authService.register(data)
|
return await this.authService.register(data)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -6,29 +6,23 @@ import { Module } from '@nestjs/common'
|
|||||||
import { PassportModule } from '@nestjs/passport'
|
import { PassportModule } from '@nestjs/passport'
|
||||||
import { AuthService } from './auth.service'
|
import { AuthService } from './auth.service'
|
||||||
import { JwtModule } from '@nestjs/jwt'
|
import { JwtModule } from '@nestjs/jwt'
|
||||||
import { jwtConstants } from './guards/jwt.constants'
|
|
||||||
import { AuthController } from './auth.controller'
|
import { AuthController } from './auth.controller'
|
||||||
import { LocalStrategy } from './guards/local.strategy'
|
import { LocalStrategy } from './guards/local.strategy'
|
||||||
import { JwtAccessStrategy } from './guards/jwt.accessToken.stragy'
|
import { JwtAuthStrategy } from './guards/jwt.auth.stragy'
|
||||||
import { JwtRefreshStrategy } from './guards/jwt.refreshToken.strategy'
|
|
||||||
import { UsersModule } from '../user/user.module'
|
import { UsersModule } from '../user/user.module'
|
||||||
|
import { jwtConstants } from './guards/jwt.constants'
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
UsersModule,
|
UsersModule,
|
||||||
PassportModule,
|
PassportModule,
|
||||||
JwtModule.register({
|
JwtModule.register({
|
||||||
// secret: jwtConstants.secret,
|
secret: jwtConstants.access_secret,
|
||||||
// signOptions: { expiresIn: jwtConstants.expiresIn }
|
signOptions: { expiresIn: jwtConstants.access_expiresIn }
|
||||||
})
|
})
|
||||||
],
|
],
|
||||||
controllers: [AuthController],
|
controllers: [AuthController],
|
||||||
providers: [
|
providers: [AuthService, LocalStrategy, JwtAuthStrategy],
|
||||||
AuthService,
|
|
||||||
LocalStrategy,
|
|
||||||
JwtAccessStrategy,
|
|
||||||
JwtRefreshStrategy
|
|
||||||
],
|
|
||||||
exports: [AuthService]
|
exports: [AuthService]
|
||||||
})
|
})
|
||||||
export class AuthModule {}
|
export class AuthModule {}
|
||||||
|
|||||||
@ -14,10 +14,20 @@ export class AuthService {
|
|||||||
private jwtService: JwtService
|
private jwtService: JwtService
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
|
//password 암호화
|
||||||
|
async getEcryptedPassword(password: string): Promise<string> {
|
||||||
|
// const encryptedPassword = await bcrypt.hash(
|
||||||
|
// password,
|
||||||
|
// jwtConstants.password_saltorRounds
|
||||||
|
// )
|
||||||
|
const encryptedPassword = password
|
||||||
|
return encryptedPassword
|
||||||
|
}
|
||||||
//app.controller.ts에서 @UseGuards(AuthGuard('local'))용
|
//app.controller.ts에서 @UseGuards(AuthGuard('local'))용
|
||||||
async validateUser(email: string, password: string): Promise<any | null> {
|
async validateUser(email: string, password: string): Promise<any | null> {
|
||||||
const user = await this.userService.fetchOne({ email: email })
|
const user = await this.userService.fetchOne({ email: email })
|
||||||
if (user && user.password === password) {
|
const encryptedPassword = await this.getEcryptedPassword(password)
|
||||||
|
if (user && user.password === encryptedPassword) {
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||||
const { password, ...result } = user
|
const { password, ...result } = user
|
||||||
return result
|
return result
|
||||||
@ -30,37 +40,42 @@ export class AuthService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async register(data: UserDTO): Promise<any | null> {
|
async register(data: UserDTO): Promise<any | null> {
|
||||||
|
const tokens = await this.getTokens(data)
|
||||||
|
data.refresh_key = tokens['refresh-token']
|
||||||
|
const encryptedPassword = await this.getEcryptedPassword(data.password)
|
||||||
|
data.password = encryptedPassword
|
||||||
const user = await this.userService.add(data)
|
const user = await this.userService.add(data)
|
||||||
if (!user) return null
|
if (!user) return null
|
||||||
return this.getTokens(user)
|
return user
|
||||||
}
|
}
|
||||||
|
|
||||||
async updateRefreshToken(user: User, refreshToken: string) {
|
async updateRefreshKey(user: User): Promise<any> {
|
||||||
const hashedRefreshToken = await bcrypt.hash(
|
const tokens = await this.getTokens(user)
|
||||||
refreshToken,
|
|
||||||
jwtConstants.refresh_saltorRounds
|
|
||||||
)
|
|
||||||
await this.userService.update({
|
await this.userService.update({
|
||||||
where: { id: user.id },
|
where: { id: user.id },
|
||||||
data: { refresh_token: hashedRefreshToken }
|
data: { refresh_token: tokens['refresh-token'] }
|
||||||
})
|
})
|
||||||
|
return tokens
|
||||||
}
|
}
|
||||||
|
|
||||||
async getTokens(user: User) {
|
async getTokens(data: UserDTO): Promise<any> {
|
||||||
const token_payload = {
|
const payload = {
|
||||||
email: user.email,
|
email: data.email,
|
||||||
name: user.name
|
name: data.name
|
||||||
}
|
}
|
||||||
const [accessToken, refreshToken] = await Promise.all([
|
const [accessToken, refreshToken] = await Promise.all([
|
||||||
this.jwtService.signAsync(token_payload, {
|
this.jwtService.sign(payload, {
|
||||||
secret: jwtConstants.access_secret,
|
secret: jwtConstants.access_secret,
|
||||||
expiresIn: jwtConstants.access_expiresIn
|
expiresIn: jwtConstants.access_expiresIn
|
||||||
}),
|
}),
|
||||||
this.jwtService.signAsync(token_payload, {
|
this.jwtService.sign(
|
||||||
secret: jwtConstants.refresh_secret,
|
{},
|
||||||
expiresIn: jwtConstants.refresh_expiresIn
|
{
|
||||||
})
|
secret: jwtConstants.refresh_secret,
|
||||||
|
expiresIn: jwtConstants.refresh_expiresIn
|
||||||
|
}
|
||||||
|
)
|
||||||
])
|
])
|
||||||
return { accessToken, refreshToken }
|
return { 'access-token': accessToken, 'refresh-token': refreshToken }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -7,7 +7,7 @@ import { AuthGuard } from '@nestjs/passport'
|
|||||||
import { Observable } from 'rxjs'
|
import { Observable } from 'rxjs'
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class JwtAuthGuard extends AuthGuard(['accessToken', 'refreshToken']) {
|
export class JwtAuthGuard extends AuthGuard('jwt') {
|
||||||
canActivate(
|
canActivate(
|
||||||
context: ExecutionContext
|
context: ExecutionContext
|
||||||
): boolean | Promise<boolean> | Observable<boolean> {
|
): boolean | Promise<boolean> | Observable<boolean> {
|
||||||
|
|||||||
@ -9,10 +9,7 @@ type JwtPayload = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class JwtAccessStrategy extends PassportStrategy(
|
export class JwtAuthStrategy extends PassportStrategy(Strategy, 'jwt') {
|
||||||
Strategy,
|
|
||||||
'accessToken'
|
|
||||||
) {
|
|
||||||
constructor() {
|
constructor() {
|
||||||
super({
|
super({
|
||||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||||
@ -3,5 +3,5 @@ export const jwtConstants = {
|
|||||||
access_expiresIn: process.env.JWT_CONSTANTS_ACCESS_EXPIRESIN,
|
access_expiresIn: process.env.JWT_CONSTANTS_ACCESS_EXPIRESIN,
|
||||||
refresh_secret: process.env.JWT_CONSTANTS_REPRESH_SECRET,
|
refresh_secret: process.env.JWT_CONSTANTS_REPRESH_SECRET,
|
||||||
refresh_expiresIn: process.env.JWT_CONSTANTS_REPRESH_EXPIRESIN,
|
refresh_expiresIn: process.env.JWT_CONSTANTS_REPRESH_EXPIRESIN,
|
||||||
refresh_saltorRounds: process.env.JWT_CONSTANTS_REPRESH_SALTORROUNDS
|
password_saltorRounds: process.env.AUTH_PASSWORD_SALTORROUNDS
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,24 +0,0 @@
|
|||||||
import { ExtractJwt, Strategy } from 'passport-jwt'
|
|
||||||
import { PassportStrategy } from '@nestjs/passport'
|
|
||||||
import { Injectable } from '@nestjs/common'
|
|
||||||
import { jwtConstants } from './jwt.constants'
|
|
||||||
|
|
||||||
@Injectable()
|
|
||||||
export class JwtRefreshStrategy extends PassportStrategy(
|
|
||||||
Strategy,
|
|
||||||
'refreshToken'
|
|
||||||
) {
|
|
||||||
constructor() {
|
|
||||||
super({
|
|
||||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
|
||||||
ignoreExpiration: false,
|
|
||||||
secretOrKey: jwtConstants.refresh_secret,
|
|
||||||
passReqToCallback: true
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
validate(req: Request, payload: any) {
|
|
||||||
const refreshToken = req.get('Authorization').replace('Bearer', '').trim()
|
|
||||||
return { ...payload, refreshToken }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -15,6 +15,7 @@ export class LocalStrategy extends PassportStrategy(Strategy) {
|
|||||||
//Login인증용
|
//Login인증용
|
||||||
async validate(email: string, password: string): Promise<any> {
|
async validate(email: string, password: string): Promise<any> {
|
||||||
const user = await this.authService.validateUser(email, password)
|
const user = await this.authService.validateUser(email, password)
|
||||||
|
//console.log(user)
|
||||||
if (!user) {
|
if (!user) {
|
||||||
throw new UnauthorizedException()
|
throw new UnauthorizedException()
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user