l Login using Gmail in Nest JS
In this article, we will learn how to implement the social login feature in Nest js.
1- Installation
First of all, install the dependencies using following commands
For NPM
npm i passport passport-facebook passport-google-oauth20
For Yarn
yarn add passport passport-facebook passport-google-oauth20
2- Configuration
In the src directory of your project, create a folder named “Services”. Create a googleStrategy.ts file in services folder.
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, VerifyCallback } from 'passport-google-oauth20';
import { config } from 'dotenv';
import { Injectable } from '@nestjs/common';
config();
@Injectable()
export class GoogleStrategy extends PassportStrategy(Strategy, 'google') {
constructor() {
super({
clientID: <your-clientID>,
clientSecret: <your-clientSecret>,
callbackURL: 'http://localhost:3000/google/redirect',
scope: ['email', 'profile'],
});
}
async validate (accessToken: string, refreshToken: string, profile: any, done: VerifyCallback): Promise<any> {
const { name, emails, photos } = profile
const user = {
email: emails?.at(0).value,
firstName: name?.givenName,
lastName: name.familyName,
picture: photos?.at(0).value,
accessToken
}
done(null, user);
}
}
2.1 — Go to console.google.com in your browser
2.2 — From side bar, go to API & Services -> Credentials
2.3 — Now, Click on create credentials and select OAuth Client ID
2.4 — After creating the client id and client secret, add it in your googleStrategy.ts file
3- Import googleStrategy in your module
import { GoogleStrategy } from './services/google.strategy';
@Module({
../
providers: [GoogleStrategy],
})
export class AppModule { }
4- Setup your service file
src/app.service.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
googleLogin(req) {
if (!req.user) {
return 'No user from google'
}
return {
message: 'User information from google',
user: req.user
}
}
}
5- Setup your routes for social login using google
src/app.app.controller.ts
import {
Body,
Controller,
Get,
HttpStatus,
Post,
Req,
UseGuards
} from '@nestjs/common';
import { AppService } from './app.service';
import { AuthGuard } from '@nestjs/passport';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@Get("auth/google")
@UseGuards(AuthGuard('google'))
async googleAuth(@Req() req) {}
@Get('google/redirect')
@UseGuards(AuthGuard('google'))
googleAuthRedirect(@Req() req) {
return this.appService.googleLogin(req)
}
}
Now, you can login using google at following URL.
http://localhost:3000/auth/google
Congratulations, Now you have implemented social login using google in Nest JS.
Top comments (0)