Dhanesh
Dhanesh

Reputation: 324

Google Authentication using Sails.js

When I have tried to implement Google authentication in my site, using sails JavaScript, and MySQL getting error. I have using passport and passport-Google-auth Strategy. Problem is not getting data to my site from Google

My Express Config(express.js) file is like below,

var passport = require('passport')
    , GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;


var verifyHandler = function(token, tokenSecret, profile, done) {
  process.nextTick(function() {
    console.log(profile)
    User.findOne({uid: profile.id}, function(err, user) {
      if (user) {
        return done(null, user);
      } else {

        var data = {
          provider: profile.provider,
          uid: profile.id,
          name: profile.displayName
        };

        if (profile.emails && profile.emails[0] && profile.emails[0].value) {
          data.email = profile.emails[0].value;
        }
        if (profile.name && profile.name.givenName) {
          data.firstname = profile.name.givenName;
        }
        if (profile.name && profile.name.familyName) {
          data.lastname = profile.name.familyName;
        }

        User.create(data, function(err, user) {
          return done(err, user);
        });
      }
    });
  });
};

passport.serializeUser(function(user, done) {
  console.log(user)
  done(null, user.uid);
});

passport.deserializeUser(function(uid, done) {
  User.findOne({uid: uid}, function(err, user) {
    done(err, user);
  });
});

module.exports.http = {

  customMiddleware: function(app) {
    passport.use(new GoogleStrategy({
      clientID: 'Client Id here',
      clientSecret: 'Secret key here',
      callbackURL: 'http://localhost:1337/auth/google/callback'
    }, verifyHandler));



    app.use(passport.initialize());
    app.use(passport.session());
  }

};

module.exports.cache = {

  // The number of seconds to cache files being served from disk
  // (only works in production mode)
  maxAge: 31557600000
};
module.exports.userlogin = {  
  userModel: 'user'  
};

And My Auth Controller I have added code like below,

google: function(req, res) {
  passport.authenticate('google',{ 
    failureRedirect: '/login', scope: ['profile', 'email']  
  }, function(err, user) {
      req.logIn(user, function(err) {
      if (err) {
        console.log(err);
        res.view('500');
        return;
      }
      res.redirect('/');
        return;
      });
  })(req, res);
},

Upvotes: 1

Views: 1163

Answers (1)

Taha Boulehmi
Taha Boulehmi

Reputation: 227

You didn't post your code, so we can't find the exact problem :/

I usually use this method for google/facebook authentication with sails.js. I follow at first this documentation to add the authentication buttons in the frontend:

https://developers.google.com/identity/sign-in/web/sign-in

Then I post the token that I got from google/facebook to the backend where I can check if the user is banned or whatever... If everything is correct, I create an account for him in the database, I send him his password to his email and finally authenticate him using sessions

(req.session.userId = createdUser.id)

In the next time the user can log in using his email and password or just using google. And both options lead him to the same account :D

My Sails.js function in the authentication controller:

googleAuth: function(req, res) {
  if (_.isUndefined(req.param('googleToken'))) {
    return res.json({
      success: false,
      msg: 'Error! Please post your google token'
    });
  }
  var urlToRq = "https://www.googleapis.com/oauth2/v3/tokeninfo?id_token=" + req.param('googleToken');
  // Get information about the google user with the specified access token.
  request.get({url: urlToRq}, function(err, response, body) {
    if(err) {
      return res.json({
        success: false,
        msg: 'Server Error'
      });
    }
    var receivedData = JSON.parse(body);

    var userId = receivedData.sub;
    var userEmail = receivedData.email;
    var emailVerified = receivedData.email_verified;
    var userName = receivedData.name;
    var userPicture = receivedData.picture;

    if (emailVerified == false) {
      return res.json({
        success: false,
        msg: 'Your email is not verified'
      });
    }
    else {
     // AUTHENTICATION VERIFIED, YOU CAN SAVE THE CONNECTED USER IN A SESSION, OR ADD HIM TO THE DATABASE AS A NEW ACCOUNT, OR CHECK IF HE HAS A PREVIOUS ACCOUNT OR WHATEVER YOU WANT...
    }
  });



},

Of course don't forget to run npm install request --save

If anyone needs the facebookAuth function just tell me :D I will post it for you :)

Upvotes: 2

Related Questions