-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #6 from PBTP/feat-authorazation
DMVM-137 feat: 인증/인가
- Loading branch information
Showing
23 changed files
with
813 additions
and
1,237 deletions.
There are no files selected for viewing
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 |
---|---|---|
|
@@ -54,3 +54,4 @@ pids | |
|
||
# Diagnostic reports (https://nodejs.org/api/report.html) | ||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json | ||
*.pem |
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
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,18 @@ | ||
import { Test, TestingModule } from '@nestjs/testing'; | ||
import { AuthService } from './auth.service'; | ||
|
||
describe('AuthService', () => { | ||
let service: AuthService; | ||
|
||
beforeEach(async () => { | ||
const module: TestingModule = await Test.createTestingModule({ | ||
providers: [AuthService], | ||
}).compile(); | ||
|
||
service = module.get<AuthService>(AuthService); | ||
}); | ||
|
||
it('should be defined', () => { | ||
expect(service).toBeDefined(); | ||
}); | ||
}); |
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,123 @@ | ||
import { Injectable } from '@nestjs/common'; | ||
import { AuthDto } from '../presentation/auth.dto'; | ||
import { CustomerService } from 'src/customer/application/customer.service'; | ||
import { Customer } from 'src/customer/entities/customer.entity'; | ||
import { JwtService, JwtSignOptions } from '@nestjs/jwt'; | ||
import { ConfigService } from '@nestjs/config'; | ||
import { CacheService } from '../../common/cache/cache.service'; | ||
|
||
@Injectable() | ||
export class AuthService { | ||
private readonly accessTokenOption: JwtSignOptions; | ||
private readonly refreshTokenOption: JwtSignOptions; | ||
private readonly accessTokenStrategy: string; | ||
|
||
constructor( | ||
private readonly jwtService: JwtService, | ||
private readonly configService: ConfigService, | ||
private readonly cacheService: CacheService, | ||
private readonly customerService: CustomerService, | ||
) { | ||
this.accessTokenOption = { | ||
secret: this.configService.get<string>('jwt/access/secret'), | ||
expiresIn: this.configService.get<number>('jwt/access/expire'), | ||
}; | ||
|
||
this.refreshTokenOption = { | ||
secret: this.configService.get<string>('jwt/refresh/secret'), | ||
expiresIn: this.configService.get<number>('jwt/refresh/expire'), | ||
}; | ||
|
||
this.accessTokenStrategy = this.configService.get<string>( | ||
'jwt/access/strategy', | ||
); | ||
} | ||
|
||
async login(dto: AuthDto): Promise<AuthDto> { | ||
let customer: Customer = await this.customerService.findOne(dto); | ||
customer = customer ?? (await this.customerService.create(dto)); | ||
|
||
const accessToken = this.jwtService.sign( | ||
{ tokenType: 'access', subject: customer.customerId }, | ||
this.accessTokenOption, | ||
); | ||
|
||
await this.saveAccessToken(customer, accessToken); | ||
|
||
const refreshToken = this.jwtService.sign( | ||
{ tokenType: 'refresh', subject: customer.customerId }, | ||
this.refreshTokenOption, | ||
); | ||
|
||
await this.customerService.update({ | ||
...customer, | ||
refreshToken: refreshToken, | ||
}); | ||
|
||
return { | ||
...customer, | ||
accessToken: accessToken, | ||
refreshToken: refreshToken, | ||
}; | ||
} | ||
|
||
async tokenRefresh(request: Request): Promise<AuthDto> { | ||
const token = request.headers['authorization'].replace('Bearer ', ''); | ||
|
||
const payload = this.jwtService.decode(token); | ||
|
||
const customer: Customer = await this.customerService.findOne({ | ||
customerId: payload.subject, | ||
}); | ||
|
||
const accessToken = this.jwtService.sign( | ||
{ tokenType: 'access', subject: customer.customerId }, | ||
this.accessTokenOption, | ||
); | ||
|
||
const refreshToken = this.jwtService.sign( | ||
{ tokenType: 'refresh', subject: customer.customerId }, | ||
this.refreshTokenOption, | ||
); | ||
|
||
await this.saveAccessToken(customer, accessToken); | ||
|
||
await this.customerService.update({ | ||
...customer, | ||
refreshToken: refreshToken, | ||
}); | ||
|
||
return { | ||
...customer, | ||
accessToken: accessToken, | ||
refreshToken: refreshToken, | ||
}; | ||
} | ||
|
||
private async saveAccessToken(customer: Customer, accessToken: string) { | ||
const key = `customer:${customer.customerId}:accessToken`; | ||
|
||
if (this.accessTokenStrategy.toLowerCase() === 'unique') { | ||
this.cacheService.get(key).then((v) => { | ||
if (v) { | ||
this.cacheService.del(v); | ||
} | ||
}); | ||
|
||
await this.cacheService.set( | ||
key, | ||
accessToken, | ||
(this.accessTokenOption.expiresIn as number) / 1000, | ||
); | ||
} | ||
|
||
await this.cacheService.set( | ||
accessToken, | ||
JSON.stringify({ | ||
...customer, | ||
refreshToken: undefined, | ||
}), | ||
(this.accessTokenOption.expiresIn as number) / 1000, | ||
); | ||
} | ||
} |
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,37 @@ | ||
import { ConfigService } from '@nestjs/config'; | ||
import { | ||
BadRequestException, | ||
UnauthorizedException, | ||
} from '@nestjs/common/exceptions'; | ||
import { Injectable } from '@nestjs/common'; | ||
import { PassportStrategy } from '@nestjs/passport'; | ||
import { ExtractJwt, Strategy } from 'passport-jwt'; | ||
import { Customer } from '../../customer/entities/customer.entity'; | ||
import { CacheService } from '../../common/cache/cache.service'; | ||
|
||
@Injectable() | ||
export class JwtAccessStrategy extends PassportStrategy(Strategy, 'access') { | ||
constructor( | ||
private readonly cacheService: CacheService, | ||
private readonly configService: ConfigService, | ||
) { | ||
super({ | ||
secretOrKey: configService.get<string>('jwt/access/secret'), | ||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), | ||
passReqToCallback: true, | ||
}); | ||
} | ||
|
||
async validate(req: Request, payload: any): Promise<Customer> { | ||
if (!payload) { | ||
throw new UnauthorizedException(); | ||
} | ||
|
||
if (payload.tokenType !== 'access') { | ||
throw new BadRequestException(); | ||
} | ||
|
||
const token = req.headers['authorization'].replace('Bearer ', ''); | ||
return JSON.parse(await this.cacheService.get(token)) as Customer; | ||
} | ||
} |
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,37 @@ | ||
import { ConfigService } from '@nestjs/config'; | ||
import { | ||
BadRequestException, | ||
UnauthorizedException, | ||
} from '@nestjs/common/exceptions'; | ||
import { Injectable } from '@nestjs/common'; | ||
import { PassportStrategy } from '@nestjs/passport'; | ||
import { Strategy, ExtractJwt } from 'passport-jwt'; | ||
import { CustomerService } from 'src/customer/application/customer.service'; | ||
import { Customer } from '../../customer/entities/customer.entity'; | ||
|
||
@Injectable() | ||
export class JwtRefreshStrategy extends PassportStrategy(Strategy, 'refresh') { | ||
constructor( | ||
private readonly configService: ConfigService, | ||
private readonly customerService: CustomerService, | ||
) { | ||
super({ | ||
secretOrKey: configService.get<string>('jwt/refresh/secret'), | ||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), | ||
passReqToCallback: true, | ||
}); | ||
} | ||
|
||
async validate(req: Request, payload: any): Promise<Customer> { | ||
if (!payload) { | ||
throw new UnauthorizedException(); | ||
} | ||
|
||
if (payload.tokenType !== 'refresh') { | ||
throw new BadRequestException(); | ||
} | ||
|
||
const token = req.headers['authorization'].replace('Bearer ', ''); | ||
return await this.customerService.findOne({ refreshToken: token }); | ||
} | ||
} |
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,28 @@ | ||
import { Module } from '@nestjs/common'; | ||
import { AuthService } from './application/auth.service'; | ||
import { AuthController } from './presentation/auth.controller'; | ||
import { CustomerModule } from 'src/customer/customer.module'; | ||
import { JwtModule } from '@nestjs/jwt'; | ||
import { ConfigService } from '@nestjs/config'; | ||
import { JwtAccessStrategy } from './application/jwt-access.strategy'; | ||
import { JwtRefreshStrategy } from './application/jwt-refresh.strategy'; | ||
import { PassportModule } from '@nestjs/passport'; | ||
import { CacheModule } from '../common/cache/cache.module'; | ||
|
||
@Module({ | ||
imports: [ | ||
JwtModule.registerAsync({ | ||
useFactory: async (configService: ConfigService) => ({ | ||
secret: configService.get<string>('jwt/access/secret'), | ||
}), | ||
inject: [ConfigService], | ||
}), | ||
PassportModule.register({ defaultStrategy: 'access' }), | ||
CacheModule, | ||
CustomerModule, | ||
], | ||
controllers: [AuthController], | ||
providers: [AuthService, JwtAccessStrategy, JwtRefreshStrategy], | ||
exports: [AuthService, JwtAccessStrategy, JwtRefreshStrategy], | ||
}) | ||
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 |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import { Test, TestingModule } from '@nestjs/testing'; | ||
import { AuthController } from './auth.controller'; | ||
import { AuthService } from '../application/auth.service'; | ||
|
||
describe('AuthController', () => { | ||
let controller: AuthController; | ||
|
||
beforeEach(async () => { | ||
const module: TestingModule = await Test.createTestingModule({ | ||
controllers: [AuthController], | ||
providers: [AuthService], | ||
}).compile(); | ||
|
||
controller = module.get<AuthController>(AuthController); | ||
}); | ||
|
||
it('should be defined', () => { | ||
expect(controller).toBeDefined(); | ||
}); | ||
}); |
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,20 @@ | ||
import { Controller, Post, Body, UseGuards, Req } from '@nestjs/common'; | ||
import { AuthService } from '../application/auth.service'; | ||
import { AuthDto } from './auth.dto'; | ||
import { AuthGuard } from '@nestjs/passport'; | ||
|
||
@Controller('/api/v1/auth') | ||
export class AuthController { | ||
constructor(private readonly authService: AuthService) {} | ||
|
||
@Post('/login') | ||
async login(@Body() dto: AuthDto) { | ||
return await this.authService.login(dto); | ||
} | ||
|
||
@Post('/refresh') | ||
@UseGuards(AuthGuard('refresh')) | ||
async refresh(@Req() req: Request) { | ||
return await this.authService.tokenRefresh(req); | ||
} | ||
} |
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,6 @@ | ||
import { CustomerDto } from 'src/customer/presentation/customer.dto'; | ||
|
||
export class AuthDto extends CustomerDto { | ||
accessToken: string; | ||
refreshToken: string; | ||
} |
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,10 @@ | ||
import { Module } from "@nestjs/common"; | ||
import { RedisModule } from "@liaoliaots/nestjs-redis"; | ||
import { CacheService } from "./cache.service"; | ||
|
||
@Module({ | ||
imports:[RedisModule], | ||
providers: [CacheService], | ||
exports: [CacheService], | ||
}) | ||
export class CacheModule {} |
Oops, something went wrong.