DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

christianstrang
christianstrang

Posted on • Updated on

SailsJSβ€Š-β€Šuse PassportJS to Login with Google OAuthΒ 2.0

For this tutorial I assume that you used step 1 (Web App) to create your sails.js app. If you want to use Facebook Login, take a look at my other post: SailsJSβ€Š-β€Šuse Passport to Login with Facebook

1. Install Passport and the Google Strategy for Passport

$ npm install passport
$ npm install passport-google-oauth2
Enter fullscreen mode Exit fullscreen mode

2. Add the Passport middleware

We need to add passport to our middleware execution stack in config/http.js

module.exports.http = {

  middleware: {

    passportInit: require('passport').initialize(),
    passportSession: require('passport').session(),

    order: [
      'cookieParser',
      'session',
      'passportInit',
      'passportSession',
      'bodyParser',
      'compress',
      'poweredBy',
      'router',
      'www',
      'favicon',
    ],
  },
};
Enter fullscreen mode Exit fullscreen mode

3. Add the Passport-GoogleStrategy

In the folder config create a new folder passport and inside create a file called config/passport/GoogleStrategy.js.

'use strict';

var passport = require('passport'),
  GoogleStrategy = require('passport-google-oauth20').Strategy;

//var verifyHandler = function(req, token, tokenSecret, profile, done) {
var verifyHandler = function (accessToken, refreshToken, profile, cb, done) {

  var data = {
    id: cb.id,
    name: cb.displayName,
    email: cb.emails[0].value,
    emailVerified: cb.emails[0].verified
  };

  return done(null, data);
};

passport.use(new GoogleStrategy({
  clientID: YOUR_CLIENT_ID,
  clientSecret: YOUR_CLIENT_SECRET,
  callbackURL: '/api/v1/auth/google/callback',
  passReqToCallback: true
}, verifyHandler));
Enter fullscreen mode Exit fullscreen mode

Don’t forget to change your credentials (clientID and clientSecret) at the bottom. Your Google Callback URL can be localhost but remember to add the callback url as a authorized redirect uri in your google developer console:

4. Create a Passport Controller to handle Google Authentication

in your console run sails generate controller passport this will create a file PassportController.js in your api/controllers folder, add the following code:

/**
 * PassportController
 *
 * @description :: Server-side actions for handling incoming requests.
 * @help        :: See https://sailsjs.com/docs/concepts/actions
 */

var passport = require('passport');

module.exports = {

  googleAuth: function(req, res) {
    passport.authenticate('google', { scope: ['email', 'profile'] })(req, res);
  },

  googleCallback: function(req, res, next) {
    passport.authenticate('google', function(err, user) {
      if(err) {
        // redirect to login page
        console.log('google callback error: '+err);
      } else {
        console.log('google credentials');
        console.log(user);
        res.json(user);
      }
    })(req, res, next);
  },

};

Enter fullscreen mode Exit fullscreen mode

5. Add routes to your config/routes.js file

'GET /api/v1/auth/google':                {controller: 'PassportController', action: 'googleAuth'},
'GET /api/v1/auth/google/callback':       {controller: 'PassportController', action: 'googleCallback'},
Enter fullscreen mode Exit fullscreen mode

These two routes will handle the request to and the callback from facebook.

6. Login in via Google

If you visit http://localhost:1337/api/v1/auth/google you should now be redirected to Google and get a prompt to allow your app access to your Google credentials. Afterwards you are redirected to your callback url and be able to access the user credentials. With this information you can check if a user already exists in the database or create a new user.

Done

This is more of a step by step than a real tutorial, if you have any questions about a specific step or if anything is wrong/missing, please let me know in the comments.

Update: changed the callbackURL in the GoogleStrategy to make it more flexible for a staging/production environment with a different domain.

Top comments (1)

Collapse
 
lsandini profile image
Lorenzo Sandini

Hello there, just what I was looking for. But ...

npm install passport-google-oauth2

and later :

var passport = require('passport'),
GoogleStrategy = require('passport-google-oauth20').Strategy;

So either the package is "-oauth2" or "-oauth20", but can't mix...

When I lift sails the localhost:1337/api/v1/auth/google is redirected to localhost:1337/login unfortunately. And in the server logs, there is reminder to add the express-session middleware.

Something is not right :/ but thanks for your effort. New to sails here ...

Some comments have been hidden by the post's author - find out more

Create an Account!
Now it's your turn!
Β 
πŸ—’ Share a tutorial
πŸ€” Reflect on your coding journey
❓ Ask a question

Create an account to join hundreds of thousands of DEV members on their journey.