$ npm i express-session
$ npm i -D @types/express-session
export class AuthController {
constructor(private readonly configService: ConfigService) {}
@Get('callback')
@UseGuards(KakaoAuthGuard)
callback(@Res() res) {
res.redirect('protected');
}
@Get('login')
@Render('login')
login() {
return {
data: {
host: this.configService.get<string>('KAKAO_REST_API_HOST'),
restApiKey: this.configService.get<string>('KAKAO_REST_API_KEY'),
redirectUri: this.configService.get<string>('KAKAO_REDIRECT_URI'),
},
};
}
@Get('protected')
@UseGuards(SessionAuthGuard)
@Render('protected')
protected(@User() user) {
const { provider, id, username } = user;
return {
data: {
provider,
id,
username,
},
};
}
@Get('logout')
logout(@Session() session: Record<string, any>, @Res() res) {
session.destroy();
res.redirect('login');
}
}
controller에 strategy 구현 후 @UseGuards(AuthGuard('kakao'))
이렇게 바로 사용할 수 있지만,
빈 class 라도 class KakaoAuthGuard extends AuthGuard('kakao') {}
만들어 사용하는 것이 좋을 것 같다.
KakaoAuthGuard에서 serializeUser() 호출되기 위해서는 super.logIn(request)
가 필요하다.
import { AuthGuard } from '@nestjs/passport';
import { Injectable, ExecutionContext } from '@nestjs/common';
@Injectable()
export class KakaoAuthGuard extends AuthGuard('kakao') {
async canActivate(context: ExecutionContext) {
const result = (await super.canActivate(context)) as boolean;
const request = context.switchToHttp().getRequest();
await super.logIn(request);
return result;
}
}
참고)