๐Ÿ˜Ž ๊ณต๋ถ€ํ•˜๋Š” ์ง•์ง•์•ŒํŒŒ์นด๋Š” ์ฒ˜์Œ์ด์ง€?

[Nest JS ๋กœ CRUD ๊ฒŒ์‹œํŒ ๋งŒ๋“ค๊ธฐ] (26) ๋กœ๊ทธ์ธ ๊ธฐ๋Šฅ ๊ตฌํ˜„ํ•˜๊ธฐ ๋ณธ๋ฌธ

๐Ÿ‘ฉ‍๐Ÿ’ป ๋ฐฑ์—”๋“œ(Back-End)/Nest js

[Nest JS ๋กœ CRUD ๊ฒŒ์‹œํŒ ๋งŒ๋“ค๊ธฐ] (26) ๋กœ๊ทธ์ธ ๊ธฐ๋Šฅ ๊ตฌํ˜„ํ•˜๊ธฐ

์ง•์ง•์•ŒํŒŒ์นด 2023. 6. 8. 17:50
728x90
๋ฐ˜์‘ํ˜•

<๋ณธ ๋ธ”๋กœ๊ทธ๋Š” 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
๋ฐ˜์‘ํ˜•
Comments