๐ ๊ณต๋ถํ๋ ์ง์ง์ํ์นด๋ ์ฒ์์ด์ง?
[Nest JS ๋ก CRUD ๊ฒ์ํ ๋ง๋ค๊ธฐ] (26) ๋ก๊ทธ์ธ ๊ธฐ๋ฅ ๊ตฌํํ๊ธฐ ๋ณธ๋ฌธ
๐ฉ๐ป ๋ฐฑ์๋(Back-End)/Nest js
[Nest JS ๋ก CRUD ๊ฒ์ํ ๋ง๋ค๊ธฐ] (26) ๋ก๊ทธ์ธ ๊ธฐ๋ฅ ๊ตฌํํ๊ธฐ
์ง์ง์ํ์นด 2023. 6. 8. 17:50728x90
๋ฐ์ํ
<๋ณธ ๋ธ๋ก๊ทธ๋ John Ahn ์ ์ ํ๋ธ๋ฅผ ์ฐธ๊ณ ํด์ ๊ณต๋ถํ๋ฉฐ ์์ฑํ์์ต๋๋ค :-)>
=> ๋ฐ๋ผํ๋ฉด์ ๋ฐฐ์ฐ๋ NestJS
๐งธ ๋ก๊ทธ์ธ ๊ธฐ๋ฅ ๊ตฌํํ๊ธฐ
ํ์ ๊ฐ์ ํ๊ณ , ๋น๋ฐ๋ฒํธ ์ํธํ ์๋ฃ!
๊ฐ์ ํ ์์ด๋๋ก ๋ก๊ทธ์ธ ํ๊ธฐ
๐ ๊ธฐ๋ฅ ๊ตฌํ ์์
1) ํด๋ผ์ด์ธํธ์์ ์ ๊ณต ๋ฐ์ ์์ด๋๋ฅผ ์ด์ฉํด ํด๋น ์์ด๋๊ฐ ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ์๋ ์์ด๋์ธ์ง ํ์ธ
2) ์๋ ์์ด๋๋ผ๋ฉด ์ ๊ณต ๋ฐ์ ๋น๋ฐ๋ฒํธ์ ์๋ ์์ด๋์ ๋น๋ฐ๋ฒํธ์ ๋น๊ตํ๊ธฐ
๐ user.service.ts
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { UserRepository } from './user.repository';
import { AuthCredentialsDto } from './dto/auth-credential.dto';
import * as bcrypt from "bcryptjs";
@Injectable()
export class AuthService {
constructor(
@InjectRepository(UserRepository)
private userRepository: UserRepository,
) {}
// ํ์๊ฐ์
async signUp(authCredentialsDto: AuthCredentialsDto): Promise<void> {
return this.userRepository.createUser(authCredentialsDto);
}
// ๋ก๊ทธ์ธ
async signIn(authCredentialsDto: AuthCredentialsDto): Promise<string> {
const {username, password} = authCredentialsDto;
// ํด๋น ์์ด๋๊ฐ ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ์๋ ์์ด๋์ธ์ง ํ์ธ
const user = await this.userRepository.findOne({username});
// ์ ๊ณต ๋ฐ์ ๋น๋ฐ๋ฒํธ์ ์๋ ์์ด๋์ ๋น๋ฐ๋ฒํธ์ ๋น๊ตํ๊ธฐ
if (user && (await bcrypt.comepare(password, user.password))){
return "login success";
} else {
throw new UnauthorizedException("login fail");
}
}
}
๐ user.controller.ts
import { Body, Controller, Post, ValidationPipe } from '@nestjs/common';
import { AuthService } from './auth.service';
import { AuthCredentialsDto } from './dto/auth-credential.dto';
@Controller('auth')
export class AuthController {
constructor( private authService: AuthService) {}
// localhost:3000/auth/signUp
@Post("/signup")
// ValidationPipe : ์์ฒญ์ด ์ปจํธ๋กค๋ฌ์ ์๋ ํธ๋ค๋ฌ๋ก ๋ค์ด์์ ๋ Dto ์ ์๋ ์ ํจ์ฑ ์กฐ๊ฑด์ ๋ง๊ฒ ์ฒดํฌ
signUp(@Body(ValidationPipe) authCredentialsDto: AuthCredentialsDto): Promise<void> {
return this.authService.signUp(authCredentialsDto);
}
// ๋ก๊ทธ์ธ ๊ธฐ๋ฅ ๊ตฌํํ๊ธฐ
@Post("/signin")
signIn(@Body(ValidationPipe) authCredentialsDto: AuthCredentialsDto) {
return this.authService.signIn(authCredentialsDto);
}
}
728x90
๋ฐ์ํ
'๐ฉโ๐ป ๋ฐฑ์๋(Back-End) > Nest js' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Comments