Skip to content

Instantly share code, notes, and snippets.

@thisismydesign
Last active September 6, 2023 12:42
Show Gist options
  • Save thisismydesign/a01c80729efeaa33485ef53c54102aac to your computer and use it in GitHub Desktop.
Save thisismydesign/a01c80729efeaa33485ef53c54102aac to your computer and use it in GitHub Desktop.
OAuth2 in NestJS for social login (Google, Facebook, Twitter, etc) /3
import { Controller, Get, Req, Res, UseGuards } from '@nestjs/common';
import { Request, Response } from 'express';
import { GoogleOauthGuard } from './google-oauth.guard';
import { JwtAuthService } from '../jwt/jwt-auth.service';
@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) {
const { accessToken } = this.jwtAuthService.login(req.user);
res.cookie('jwt, accessToken, {
httpOnly: true,
sameSite: 'lax',
});
return req.user;
}
}
import { Module } from '@nestjs/common';
import { JwtAuthModule } from '../jwt/jwt-auth.module';
import { GoogleOauthController } from './google-oauth.controller';
import { GoogleOauthStrategy } from './google-oauth.strategy';
@Module({
imports: [JwtAuthModule],
controllers: [GoogleOauthController],
providers: [GoogleOauthStrategy],
})
export class GoogleOauthModule {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment