-
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 #61 from boostcampwm2023/feat/20-auth-login-api
[Feat] JWT를 활용한 인증 및 로그인 API 구현
- Loading branch information
Showing
17 changed files
with
376 additions
and
37 deletions.
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
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,16 @@ | ||
import { Body, Controller, Post, ValidationPipe } from "@nestjs/common"; | ||
import { AuthService } from "./auth.service"; | ||
import { AuthCredentialsDto } from "./dto/auth-credential.dto"; | ||
import { AccessTokenDto } from "./dto/auth-access-token.dto"; | ||
|
||
@Controller("auth") | ||
export class AuthController { | ||
constructor(private authService: AuthService) {} | ||
|
||
@Post("/signin") | ||
signIn( | ||
@Body(ValidationPipe) authCredentialsDto: AuthCredentialsDto, | ||
): Promise<AccessTokenDto> { | ||
return this.authService.signIn(authCredentialsDto); | ||
} | ||
} |
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,25 @@ | ||
import "dotenv/config"; | ||
import { Module } from "@nestjs/common"; | ||
import { AuthController } from "./auth.controller"; | ||
import { AuthService } from "./auth.service"; | ||
import { JwtModule } from "@nestjs/jwt"; | ||
import { PassportModule } from "@nestjs/passport"; | ||
import { JwtStrategy } from "./jwt.strategy"; | ||
import { UsersModule } from "src/users/users.module"; | ||
|
||
@Module({ | ||
imports: [ | ||
PassportModule.register({ defaultStrategy: "jwt" }), | ||
JwtModule.register({ | ||
secret: process.env.JWT_SECRET, | ||
signOptions: { | ||
expiresIn: process.env.JWT_ACCESS_TOKEN_TIME, | ||
}, | ||
}), | ||
UsersModule, | ||
], | ||
controllers: [AuthController], | ||
providers: [AuthService, JwtStrategy], | ||
exports: [PassportModule], | ||
}) | ||
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,30 @@ | ||
import { Injectable, UnauthorizedException } from "@nestjs/common"; | ||
import { JwtService } from "@nestjs/jwt"; | ||
import { UsersRepository } from "src/users/users.repository"; | ||
import { AuthCredentialsDto } from "./dto/auth-credential.dto"; | ||
import * as bcrypt from "bcryptjs"; | ||
import { AccessTokenDto } from "./dto/auth-access-token.dto"; | ||
|
||
@Injectable() | ||
export class AuthService { | ||
constructor( | ||
private usersRepository: UsersRepository, | ||
private jwtService: JwtService, | ||
) {} | ||
|
||
async signIn( | ||
authCredentialsDto: AuthCredentialsDto, | ||
): Promise<AccessTokenDto> { | ||
const { userId, password } = authCredentialsDto; | ||
const user = await this.usersRepository.getUserByUserId(userId); | ||
|
||
if (user && (await bcrypt.compare(password, user.password))) { | ||
const payload = { userId }; | ||
const accessToken = await this.jwtService.sign(payload); | ||
|
||
return new AccessTokenDto(accessToken); | ||
} else { | ||
throw new UnauthorizedException("login failed"); | ||
} | ||
} | ||
} |
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,7 @@ | ||
export class AccessTokenDto { | ||
accessToken: string; | ||
|
||
constructor(accessToken: string) { | ||
this.accessToken = accessToken; | ||
} | ||
} |
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 { IsString, MaxLength } from "class-validator"; | ||
|
||
export class AuthCredentialsDto { | ||
@IsString() | ||
@MaxLength(20) | ||
userId: string; | ||
|
||
@IsString() | ||
@MaxLength(20) | ||
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import { Injectable, UnauthorizedException } from "@nestjs/common"; | ||
import { PassportStrategy } from "@nestjs/passport"; | ||
import { ExtractJwt, Strategy } from "passport-jwt"; | ||
import { User } from "src/users/users.entity"; | ||
import { UsersRepository } from "src/users/users.repository"; | ||
|
||
@Injectable() | ||
export class JwtStrategy extends PassportStrategy(Strategy) { | ||
constructor(private userRepository: UsersRepository) { | ||
super({ | ||
secretOrKey: process.env.JWT_SECRET, | ||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), | ||
}); | ||
} | ||
|
||
async validate(payload) { | ||
const { userId } = payload; | ||
const user: User = await this.userRepository.getUserByUserId(userId); | ||
|
||
if (!user) { | ||
throw new UnauthorizedException(); | ||
} | ||
return user; | ||
} | ||
} |
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
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
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 |
---|---|---|
@@ -1,16 +1,38 @@ | ||
import { | ||
ConflictException, | ||
InternalServerErrorException, | ||
NotFoundException, | ||
} from "@nestjs/common"; | ||
import { CreateUserDto } from "./users.dto"; | ||
import { User } from "./users.entity"; | ||
import * as bcrypt from "bcryptjs"; | ||
|
||
export class UsersRepository { | ||
async createUser( | ||
createUserDto: CreateUserDto, | ||
encodedPassword: string, | ||
): Promise<User> { | ||
const { userId, nickname } = createUserDto; | ||
const password = encodedPassword; | ||
const newUser = User.create({ userId, password, nickname }); | ||
await newUser.save(); | ||
async createUser(createUserDto: CreateUserDto): Promise<User> { | ||
const { userId, password, nickname } = createUserDto; | ||
|
||
return newUser; | ||
const salt = await bcrypt.genSalt(); | ||
const hashedPassword = await bcrypt.hash(password, salt); | ||
const user = User.create({ userId, password: hashedPassword, nickname }); | ||
|
||
try { | ||
await user.save(); | ||
} catch (error) { | ||
if (error.code === "ER_DUP_ENTRY") { | ||
throw new ConflictException("Existing userId"); | ||
} else { | ||
throw new InternalServerErrorException(); | ||
} | ||
} | ||
|
||
return user; | ||
} | ||
|
||
async getUserByUserId(userId: string): Promise<User> { | ||
const found = await User.findOne({ where: { userId } }); | ||
if (!found) { | ||
throw new NotFoundException(`Can't find User with UserId: [${userId}]`); | ||
} | ||
return found; | ||
} | ||
} |
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