카테고리 없음
Nest.js 카카오 로그인 (passport) 구현
김만규
2024. 4. 18. 10:19
728x90
반응형
일단 소셜로그인을 하려면 flow를 알아야하기 때문에 flow를 보고 진행합니다
카카오 로그인을 클릭했을때
// src/auth/kakao/kakao-stateagy.ts
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-kakao';
import { AuthService } from '../auth.service';
@Injectable()
export class KakaoStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({
clientID: process.env.CLIENTID,
clientSecret: process.env.CLIENT_SECRT,
callbackURL: process.env.CALL_BACK_URL,
});
}
async validate(accessToken: string, refreshToken: string, profile: any, done: CallableFunction) {
const { provider, username} = profile;
const { profile_image } = profile._json.properties;
const { email } = profile._json.kakao_account;
const result = await this.authService.socialUser(email, username, profile_image, provider)
done(null, result);
}
}
Nest.js에서는 passport를 사용하려면 PassportStrategy기능과 AuthGuard 데코레이터를 통해 구현이 됩니다.
위에 같은 코드와 작성이 되어있으면 소셜로그인 flow를 보았을때 카카오에게 사용자의 정보를 받아올수있게 되어있다
여기서 clientID, clientSecrtet, classbackURL이 env에 작성되어있는값과 Kakao developers 애플리케이션 값과 틀리면 실행이 안될수있으니 참고해야합니다
// auth.guard.ts
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class KakaoAuthGuard extends AuthGuard('kakao') {}
이제 AuthGuard를 활용을 해야합니다 우리는 strategy 파일에서 적용한 kakao네이밍을 그대로 가져와야하기 때문에 'kakao'를 작성합
니다
카카오 사용의 정보 create
async socialUser(email:string, username: string, profile_image:string, provider: string){
const user = await this.usersRepository.findOne({
where: {
email: email,
social: provider,
},
select: ['id', 'email', 'nickname', 'social'],
});
if (!user) {
const user = this.usersRepository.create({
email: email,
nickname: username,
image: profile_image,
social: provider
});
return await this.usersRepository.save(user);
}
return user;
}
데이터베이스를 사용할때 쿼리를 직접 작성하여 create를 할수있겠지만 쿼리를 사용을 안해도 괜찮을 정도로 간단하기 때문에 쿼리를 직접 사용하지않고 ORM사용하였습니다
카카오 로그인 성공시
scr/auth/auth.controller.ts
@Get('/kakao/callback')
@UseGuards(KakaoAuthGuard)
kakaoAuthRedirect(
@Res() res: Response) {
res.redirect("/")
}
728x90
반응형