Skip to content

Instantly share code, notes, and snippets.

@thisismydesign
Last active April 25, 2024 23:37
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save thisismydesign/a83efc23aa156d79216d9b97615639ac to your computer and use it in GitHub Desktop.
Save thisismydesign/a83efc23aa156d79216d9b97615639ac to your computer and use it in GitHub Desktop.
OAuth2 in NestJS for social login (Google, Facebook, Twitter, etc) /1
import { Controller, Get, Req, Res, UseGuards } from '@nestjs/common';
import { Request, Response } from 'express';
import { GoogleOauthGuard } from './google-oauth.guard';
@Controller('auth/google')
export class GoogleOauthController {
constructor(private jwtAuthService: JwtAuthService) {}
@Get()
@UseGuards(GoogleOauthGuard)
async googleAuth(@Req() _req) {
// Guard redirects
}
@Get('redirect')
@UseGuards(GoogleOauthGuard)
async googleAuthRedirect(@Req() req: Request, @Res() res: Response) {
// For now, we'll just show the user object
return req.user;
}
}
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
@Injectable()
export class GoogleOauthGuard extends AuthGuard('google') {}
import { Module } from '@nestjs/common';
import { GoogleOauthController } from './google-oauth.controller';
import { GoogleOauthStrategy } from './google-oauth.strategy';
@Module({
imports: [],
controllers: [GoogleOauthController],
providers: [GoogleOauthStrategy],
})
export class GoogleOauthModule {}
import { PassportStrategy } from '@nestjs/passport';
import { Profile, Strategy } from 'passport-google-oauth20';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
@Injectable()
export class GoogleOauthStrategy extends PassportStrategy(Strategy, 'google') {
constructor(
configService: ConfigService,
private readonly usersService: UsersService,
) {
super({
// Put config in `.env`
clientID: configService.get<string>('OAUTH_GOOGLE_ID'),
clientSecret: configService.get<string>('OAUTH_GOOGLE_SECRET'),
callbackURL: configService.get<string>('OAUTH_GOOGLE_REDIRECT_URL'),
scope: ['email', 'profile'],
});
}
async validate(
_accessToken: string,
_refreshToken: string,
profile: Profile,
) {
const { id, name, emails } = profile;
// Here a custom User object is returned. In the the repo I'm using a UsersService with repository pattern, learn more here: https://docs.nestjs.com/techniques/database
return {
provider: 'google',
providerId: id,
name: name.givenName,
username: emails[0].value,
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment