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