I watched a video and learnt about the passport package to handle the authentication and save the user data in MongoDB from Google.
Passport is the middleware for NodeJS. It can be used to authenticate using a username and password, Facebook, Twitter, Google and more. It is simple to use and flexible.
Steps to use passport package for google authentication:-
Passport is the middleware for NodeJS. It can be used to authenticate using a username and password, Facebook, Twitter, Google and more. It is simple to use and flexible.
Steps to use passport package for google authentication:-
- install passport npm i passport passport-google-oauth20 --save
- I used the below code to handle the authentication.
1. This file has Google strategy to fetch the user's profile from user's Google profile and saving it in my MongoDB.
passport.js
passport.js
const GoogleStrategy = require('passport-google-oauth20');
const User = require('../models/User');
module.exports = function (passport) {
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: '/auth/google/callback'
},
async (accessToken, refreshToken, profile, done) => {
console.log(profile);
const newUser = {
googleId: profile.id,
firstName: profile.name.givenName,
lastName: profile.name.familyName,
displayName: profile.displayName,
image: profile.photos[0].value
}
try {
let user = await User.findOne({
googleId: profile.id
});
if (!user) {
user = await User.create(newUser);
}
done(null, user);
} catch (err) {
console.error(err);
}
}));
passport.serializeUser((user, done) => {
done(null, user.id)
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => done(err, user));
});
}
Google client id and client secret can be obtain from Goole Cloud Console by creating a new project.
2. I used MongoDB to save the user details using mongoose package.
User.js
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
googleId: {
type: String,
required: true
},
displayName: {
type: String,
required: true
},
firstName: {
type: String,
required: true
},
image: {
type: String
},
createdAt: {
type: Date,
default: Date.now()
}
});
module.exports = mongoose.model('User', UserSchema);
3. I created a route file to handle the authentication.
auth.js
const express = require('express');
const passport = require('passport');
const router = express.Router();
const User = require('../models/User');
//@route GET /auth/google
router.get('/google', passport.authenticate('google', {
scope: ['profile']
}));
//@route GET /auth/google/callback
router.get('/google/callback', passport.authenticate('google', {
failureRedirect: '/'
}), (req, res) => {
res.render('dashboard', {
layout: 'main'
});
});
module.exports = router;
4. I initialized the passport in app.js file
const path = require('path');
const express = require('express');
const dotenv = require('dotenv');
const exphbs = require('express-handlebars');
const passport = require('passport');
const connectDB = require('./config/db');
//dotenv config
dotenv.config({
path: './config/config.env'
});
//Passport config
require('./config/passport')(passport);
connectDB();
const app = express();
//Handlebars
app.engine('.hbs', exphbs({
defaultLayout: 'main',
extname: '.hbs'
}));
app.set('view engine', 'hbs');
//Passport middleware
app.use(passport.initialize());
//Static folder
app.use(express.static(path.join(__dirname, 'public')));
//Routes
app.use('/', require('./routes/index'));
app.use('/auth', require('./routes/auth'));
const PORT = process.env.PORT || 3000;
app.listen(PORT, console.log(`Server running on ${process.env.NODE_ENV} mode on ${PORT}`));
Note: I'll upload the above project on Github very soon.
Comments
Post a Comment