Make google auth optional on server side (#508)

* Make google auth optional on server side

* fix lint

* Fix according to review
This commit is contained in:
Charles Bochet
2023-07-04 23:53:53 +02:00
committed by GitHub
parent 6fc416da76
commit 2afe933055
10 changed files with 86 additions and 39 deletions

View File

@ -11,6 +11,7 @@ import { Response } from 'express';
import { GoogleRequest } from '../strategies/google.auth.strategy';
import { UserService } from '../../user/user.service';
import { TokenService } from '../services/token.service';
import { GoogleProviderEnabledGuard } from '../guards/google-provider-enabled.guard';
@Controller('auth/google')
export class GoogleAuthController {
@ -20,14 +21,14 @@ export class GoogleAuthController {
) {}
@Get()
@UseGuards(AuthGuard('google'))
@UseGuards(GoogleProviderEnabledGuard, AuthGuard('google'))
async googleAuth() {
// As this method is protected by Google Auth guard, it will trigger Google SSO flow
return;
}
@Get('redirect')
@UseGuards(AuthGuard('google'))
@UseGuards(GoogleProviderEnabledGuard, AuthGuard('google'))
async googleAuthRedirect(@Req() req: GoogleRequest, @Res() res: Response) {
const { firstName, lastName, email } = req.user;

View File

@ -0,0 +1,14 @@
import { Injectable, CanActivate, HttpException } from '@nestjs/common';
import { Observable } from 'rxjs';
import { EnvironmentService } from 'src/integrations/environment/environment.service';
@Injectable()
export class GoogleProviderEnabledGuard implements CanActivate {
constructor(private readonly environmentService: EnvironmentService) {}
canActivate(): boolean | Promise<boolean> | Observable<boolean> {
if (!this.environmentService.getAuthGoogleEnabled()) {
throw new HttpException('Google auth is not enabled', 404);
}
return true;
}
}

View File

@ -16,10 +16,17 @@ export type GoogleRequest = Request & {
@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
constructor(environmentService: EnvironmentService) {
const isAuthGoogleEnabled = environmentService.getAuthGoogleEnabled();
super({
clientID: environmentService.getAuthGoogleClientId(),
clientSecret: environmentService.getAuthGoogleClientSecret(),
callbackURL: environmentService.getAuthGoogleCallbackUrl(),
clientID: isAuthGoogleEnabled
? environmentService.getAuthGoogleClientId()
: 'disabled',
clientSecret: isAuthGoogleEnabled
? environmentService.getAuthGoogleClientSecret()
: 'disabled',
callbackURL: isAuthGoogleEnabled
? environmentService.getAuthGoogleCallbackUrl()
: 'disabled',
scope: ['email', 'profile'],
});
}