56 lines
1.5 KiB
TypeScript
56 lines
1.5 KiB
TypeScript
import { PassportStrategy } from '@nestjs/passport';
|
|
import { Injectable } from '@nestjs/common';
|
|
import { Strategy, VerifyCallback } from 'passport-google-oauth20';
|
|
import { ConfigService } from '@nestjs/config';
|
|
import { PersonaService } from './persona.service';
|
|
|
|
@Injectable()
|
|
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
|
|
constructor(
|
|
private readonly personaService: PersonaService,
|
|
private readonly config: ConfigService,
|
|
) {
|
|
const clientID = config.get<string>('GOOGLE_CLIENT_ID');
|
|
const clientSecret = config.get<string>('GOOGLE_CLIENT_SECRET');
|
|
const callbackURL = config.get<string>('GOOGLE_CALLBACK_URL');
|
|
|
|
if (!clientID || !clientSecret || !callbackURL) {
|
|
throw new Error(
|
|
'Las variables de entorno de Google OAuth no están definidas',
|
|
);
|
|
}
|
|
|
|
super({
|
|
clientID,
|
|
clientSecret,
|
|
callbackURL,
|
|
scope: ['email', 'profile'],
|
|
passReqToCallback: true,
|
|
});
|
|
}
|
|
|
|
async validate(
|
|
req: any,
|
|
accessToken: string,
|
|
refreshToken: string,
|
|
profile: any,
|
|
done: VerifyCallback,
|
|
): Promise<any> {
|
|
try {
|
|
const email = profile.emails?.[0]?.value;
|
|
const name = profile.name?.givenName || '';
|
|
const apellidoP = profile.name?.familyName || '';
|
|
|
|
const user = await this.personaService.validateOrCreateGoogleUser({
|
|
email,
|
|
nombre: name,
|
|
apellidoP,
|
|
});
|
|
|
|
done(null, user);
|
|
} catch (error) {
|
|
done(error, false);
|
|
}
|
|
}
|
|
}
|