-
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.
- Loading branch information
1 parent
d7256f9
commit fe534c6
Showing
12 changed files
with
312 additions
and
5 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
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,55 @@ | ||
import { Body, Controller, Delete, Post, Req, Res, UseGuards } from "@nestjs/common"; | ||
import { SignRequest } from "./dto/sign"; | ||
import { AuthService } from "./auth.service"; | ||
import { UserGuard } from "@app/jwt/guard/user.guard"; | ||
import { Response } from 'express'; | ||
|
||
@Controller('auth') | ||
export class AuthController { | ||
|
||
constructor( | ||
private readonly authService : AuthService | ||
) {} | ||
|
||
@Post('signUp') | ||
async signUp( | ||
@Body() dto : SignRequest, | ||
@Res({passthrough : true}) res:Response | ||
) { | ||
const data = await this.authService.signUp(dto.phone,dto.password); | ||
res.setHeader('Authorization',`Bearer ${data.access}`) | ||
return { | ||
result : true | ||
} | ||
} | ||
|
||
@Post('signIn') | ||
async signIn( | ||
@Body() dto : SignRequest, | ||
@Res({passthrough : true}) res:Response | ||
) { | ||
const data = await this.authService.signIn(dto.phone,dto.password); | ||
res.setHeader('Authorization',`Bearer ${data.access}`) | ||
return { | ||
result : true | ||
} | ||
} | ||
|
||
@Post('signOut') | ||
@UseGuards(UserGuard) | ||
async signOut( | ||
@Req() req | ||
) { | ||
return { | ||
result : true | ||
} | ||
} | ||
|
||
@Delete('account') | ||
@UseGuards(UserGuard) | ||
async deleteAccount(@Body() dto: SignRequest) { | ||
return { | ||
result : true | ||
} | ||
} | ||
} |
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,35 @@ | ||
import { DynamicModule, Module } from "@nestjs/common"; | ||
import { UserService } from "../user/user.service"; | ||
import { PassportModule } from "@nestjs/passport"; | ||
import { JwtModule } from "@nestjs/jwt"; | ||
import { UserStrategy } from "./strategy/user.strategy"; | ||
import { UserModule } from "../user/user.module"; | ||
import { AuthController } from "./auth.controller"; | ||
|
||
@Module({}) | ||
export class AuthModule { | ||
static forRootAsync(options : { secret : string, expiresIn : string }) : DynamicModule { | ||
return { | ||
module : AuthModule, | ||
imports : [ | ||
UserModule, | ||
PassportModule, | ||
JwtModule.register({ | ||
secret : options.secret, | ||
signOptions : { | ||
expiresIn : options.expiresIn | ||
} | ||
}) | ||
], | ||
controllers : [ | ||
AuthController, | ||
], | ||
providers : [ | ||
{ | ||
provide : UserStrategy, | ||
useFactory : (user:UserService) => new UserStrategy(user,options.secret), | ||
inject : [UserService] | ||
}], | ||
} | ||
} | ||
} |
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,29 @@ | ||
import { Injectable, UnauthorizedException } from "@nestjs/common"; | ||
import { JwtService } from "@nestjs/jwt"; | ||
import { UserService } from "../user/user.service"; | ||
|
||
@Injectable() | ||
export class AuthService { | ||
constructor( | ||
private readonly userService: UserService, | ||
private readonly jwtService: JwtService, | ||
) {} | ||
|
||
async signIn(phone: string, pwd: string) { | ||
const user = await this.userService.getUser(phone); | ||
if(user.pwd !== pwd) throw new UnauthorizedException('잘못된 비밀번호 입니다.') | ||
return this._generateAccessToken(user.userId) | ||
} | ||
|
||
async signUp(phone: string, pwd:string) { | ||
const user = await this.userService.saveUser(phone,pwd); | ||
return this._generateAccessToken(user.userId); | ||
} | ||
|
||
private _generateAccessToken(id:string) { | ||
const payload = { id }; | ||
return { | ||
access: this.jwtService.sign(payload), | ||
}; | ||
} | ||
} |
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,11 @@ | ||
import { IsNotEmpty, IsOptional, IsPhoneNumber, IsString } from "class-validator" | ||
|
||
export class SignRequest { | ||
@IsNotEmpty() | ||
@IsPhoneNumber() | ||
phone : string | ||
|
||
@IsNotEmpty() | ||
@IsString() | ||
password : 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
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 { UserService } from "./user.service"; | ||
|
||
@Module({ | ||
imports : [], | ||
controllers : [], | ||
providers : [UserService], | ||
exports : [UserService] | ||
}) | ||
export class UserModule {} |
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,31 @@ | ||
import { Injectable, UnauthorizedException } from "@nestjs/common"; | ||
import { randomString } from "@util/random"; | ||
import { v4 as uuidv4 } from 'uuid'; | ||
@Injectable() | ||
export class UserService { | ||
private readonly mock = [ | ||
{ | ||
userId : 'ddab41a0-0fc7-4602-927b-40a681021ace', | ||
nickName : 'tester', | ||
phone : '01012341234', | ||
pwd : '97385f8ee138c77ecbd815a3dda29bc40ecbfc16945d5bb9d5e65480aca3c9bc' | ||
} | ||
] | ||
|
||
async getUser(phone:string) { | ||
const user = this.mock.find((u) => u.phone === phone) | ||
if(!user) throw new UnauthorizedException('존재하지 않는 회원입니다.') | ||
return user; | ||
} | ||
|
||
async saveUser(phone:string,pwd:string) { | ||
const newUser = { | ||
userId : uuidv4(), | ||
nickName : randomString(), | ||
phone, | ||
pwd | ||
} | ||
this.mock.push() | ||
return newUser; | ||
} | ||
} |
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,46 @@ | ||
import { | ||
ExecutionContext, | ||
Injectable, | ||
UnauthorizedException, | ||
} from '@nestjs/common'; | ||
import { JwtService } from '@nestjs/jwt'; | ||
import { AuthGuard } from '@nestjs/passport'; | ||
import { Request } from 'express'; | ||
|
||
@Injectable() | ||
export class UserGuard extends AuthGuard('jwt') { | ||
constructor(private readonly jwtService: JwtService) { | ||
super(); | ||
} | ||
|
||
async canActivate(context: ExecutionContext): Promise<boolean> { | ||
const isActivated = (await super.canActivate(context)) as boolean; | ||
if (!isActivated) { | ||
throw new UnauthorizedException('Invalid token'); | ||
} | ||
|
||
const request = context.switchToHttp().getRequest<Request>(); | ||
const token = this.extractTokenFromHeader(request); | ||
|
||
if (!token) { | ||
throw new UnauthorizedException('토큰이 없습니다.'); | ||
} | ||
|
||
try { | ||
const payload = await this.jwtService.verifyAsync(token); | ||
request.user = payload; | ||
} catch (error) { | ||
throw new UnauthorizedException('토큰 검증 실패'); | ||
} | ||
|
||
return true; | ||
} | ||
|
||
private extractTokenFromHeader(request: Request): string | null { | ||
const authHeader = request.headers.authorization; | ||
if (!authHeader) return null; | ||
|
||
const [type, token] = authHeader.split(' '); | ||
return type === 'Bearer' ? token : null; | ||
} | ||
} |
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,27 @@ | ||
|
||
import { PassportStrategy } from '@nestjs/passport'; | ||
import { Injectable, UnauthorizedException } from '@nestjs/common'; | ||
import { UserService } from '../../user/user.service'; | ||
import { ExtractJwt, Strategy } from 'passport-jwt'; | ||
|
||
@Injectable() | ||
export class UserStrategy extends PassportStrategy(Strategy) { | ||
constructor(private userService: UserService, private secret : string) { | ||
super({ | ||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), | ||
ignoreExpiration: false, | ||
secretOrKey: secret, | ||
}); | ||
} | ||
|
||
async validate(phone: string, password: string): Promise<any> { | ||
const user = await this.userService.getUser(phone); | ||
if (!user) { | ||
throw new UnauthorizedException(); | ||
} | ||
return { | ||
id : user.userId, | ||
nick_name : user.nickName, | ||
}; | ||
} | ||
} |
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,3 @@ | ||
export class User { | ||
id : 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,8 @@ | ||
export const randomString = ( legnth : number = 10) : string => { | ||
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; | ||
let result = ''; | ||
for (let i = 0; i < length; i++) { | ||
result += chars.charAt(Math.floor(Math.random() * chars.length)); | ||
} | ||
return result; | ||
} |