Notice
Recent Posts
Recent Comments
Link
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

레커

Nest.js Passport-kakao 본문

개발/TIL

Nest.js Passport-kakao

Prism Wrecker 2024. 1. 22. 09:13

Auth.controller.ts 로 경로 지정

@UseGuards 를 통해 KakaoAuthGuard 실행

import { Controller, Get, Post, Redirect, Req, UseGuards, Request, Response, Res } from '@nestjs/common';

import { ApiTags } from '@nestjs/swagger';

import { KakaoAuthGuard } from './guards/kakao.guard';
import { ConfigService } from '@nestjs/config';

@ApiTags('Auth')
@Controller('auth')
export class AuthController
{
    constructor(private readonly configService: ConfigService) { }

    @UseGuards(KakaoAuthGuard)
    @Get('login/kakao')
    async kakao(@Req() req): Promise<void> { }

    @Redirect('/')
    @UseGuards(KakaoAuthGuard)
    @Get('/login/kakao/callback')
    async callbacks(@Req() req, @Res() res)
    {
        // 토큰 확인용 주석
        console.log(req.user);
        return req.user;
    }
}

 

kakao.guard.ts 에서  kakao.strategy.ts 실행

import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';


@Injectable()
export class KakaoAuthGuard extends AuthGuard('kakao') { }

 

kakao.strategy.ts 

import { UserService } from 'src/user/user.service';
import { AuthService } from './../auth.service';

import { HttpStatus, Injectable, Res } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, Profile } from 'passport-kakao';
import * as _ from 'lodash';
import { Response } from 'express';

@Injectable()
export class KakaoStrategy extends PassportStrategy(Strategy, 'kakao') {
    constructor(
        private readonly configService: ConfigService,
        private readonly authService: AuthService,
        private readonly userService: UserService,
    )
    {
        super({
            clientID: configService.get<string>('KAKAO_KEY'),
            callbackURL: '/api/auth/login/kakao/callback',
        });
    }
    async validate(accessToken: string, refreshToken: string, profile: Profile, done: any, @Res() res: Response): Promise<any>
    {
        const kakaoId = profile.id;
        const nickname = profile._json.properties.nickname;
        const profileImage = profile._json.properties.profile_image;
        const provider = profile.provider;
        let user = await this.authService.validateUser(kakaoId);
        
        //user 가 없는 경우
        if (!user)
        {
            // 회원가입 진행
            user = await this.userService.create({ kakaoId, nickname, profileImage, provider });
            console.log(user);
        }

        const access_token = await this.authService.createAccessToken(user.userId);
        //const refresh_token = await this.authService.createRefreshToken(user.userId);

        return { access_token };
    }
}

 

 

'개발 > TIL' 카테고리의 다른 글

[NestJs] Sentry 를 이용해 Slack에 알림  (0) 2024.01.26
Rate limit_nest.js  (0) 2024.01.24
Interceptor  (0) 2024.01.19
CORS  (0) 2024.01.19
Container  (0) 2024.01.17