import { HttpException, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Google, StrategyException } from '@devts/nestjs-auth';
interface GoogleProfile {
username: string;
email: string;
}
@Injectable()
export class GoogleStrategy extends Google.AbstractStrategy<
'user',
"emails" | "profile"
GoogleProfile
> {
constructor(configService: ConfigService) {
super({
client_id: configService.get('CLIENT_ID'),
client_secret: configService.get('CLIENT_SECRET'),
redirect_uri: configService.get('OAUTH_CALLBACK'),
access_type: "offline",
prompt: "consent",
scope: ['email', 'profile'],
key: 'user',
});
}
protected throw({
statusCode = 401,
message = ''
}:StrategyException): never {
throw new HttpException(statusCode, message);
}
validate(
identity: Google.IdToken<'email' | 'profile'>,
credentials: Google.Credentials,
): boolean {
return true;
}
transform(
identity: Google.IdToken<'email' | 'profile'>,
): GoogleProfile {
const { name, email } = identity;
return { username: name, emails };
}
}
// in module
@Module({
providers: [
{
provide: 'GoogleStrategy',
useClass: GoogleStrategy,
},
],
})
export class AppModule {}
import { AuthGuard } from '@devts/nestjs-auth';
import { Req } from '@nestjs/common';
import type { Request } from 'express';
@Controller('auth')
export class AuthController {
// Inject decorator get "GoogleStrategy" token
@Get('sign-in')
@UseGuards(AuthGuard('GoogleStrategy'))
signIn() {
return;
}
@Get('YOUR REDIRECT PATH')
@UseGuards(AuthGuard('GoogleStrategy'))
callback(@Req() req: Request) {
return (req as any).user; // you can get data from request[key]
}
}