nestjs에서 passport를 사용하여 하나의 서버에서 여러 개의 app에 맞는 서비스를 제공하기 위해 CustomGuard를 작성했습니다.
I make CustomGuard to provide services for multiple apps on one server using passport in nestjs.
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; | |
import { ConfigService } from '@nestjs/config'; | |
import { PassportStrategy } from '@nestjs/passport'; | |
import { Profile, Strategy } from 'passport-kakao'; | |
export class KakaoProvider { | |
constructor( | |
public readonly clientID: string, | |
public readonly response_type: string, | |
public readonly clientSecret: string, | |
public readonly callbackURL: string, | |
) {} | |
} | |
@Injectable() | |
export class KakaoStrategy extends PassportStrategy(Strategy) { | |
constructor(provider?: KakaoProvider) { | |
super({ | |
response_type: 'code', | |
clientID: provider.clientID || '0', | |
clientSecret: '', | |
callbackURL: provider.callbackURL || '', | |
}); | |
} | |
async validate(accessToken: string, refreshToken: string, profile: Profile, done: (error, user, info) => void) { | |
try { | |
done(null, accessToken); | |
} catch (e) { | |
done(e); | |
} | |
} | |
} | |
@Injectable() | |
export class KakaoCustomGuard implements CanActivate { | |
constructor(private kakaoConfigService: ConfigService) {} | |
async canActivate(context: ExecutionContext) { | |
const req = context.switchToHttp().getRequest(); | |
const appKey = req.query.appKey; | |
if (appKey === 'app1') { | |
new KakaoStrategy({ | |
response_type: 'code', | |
clientID: this.kakaoConfigService.get('PASSPORT_HARMONY_KAKAO_CLIENT_ID'), | |
clientSecret: '', | |
callbackURL: this.kakaoConfigService.get('PASSPORT_KAKAO_REDIRECT_URL'), | |
}); | |
} else if (appKey === 'app2') { | |
new KakaoStrategy({ | |
response_type: 'code', | |
clientID: this.kakaoConfigService.get('PASSPORT_SPARK_KAKAO_CLIENT_ID'), | |
clientSecret: '', | |
callbackURL: this.kakaoConfigService.get('PASSPORT_KAKAO_REDIRECT_URL'), | |
}); | |
} | |
return true; | |
} | |
} |