使用Sails.js进行Google身份验证

时间:2018-03-17 15:30:31

标签: mysql node.js sails.js

当我尝试在我的网站中实施Google身份验证时,使用sails JavaScript和MySQL获取错误。我使用护照和护照-Google-auth策略。问题是没有从Google获取数据到我的网站

My Express Config(express.js)文件如下所示,

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'  
};

我的Auth Controller我添加了如下代码,

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);
},

1 个答案:

答案 0 :(得分:1)

您没有发布您的代码,因此我们无法找到确切的问题:/

我通常使用此方法进行goils.js的google / facebook身份验证。 我首先遵循此文档,在前端添加身份验证按钮:

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

然后我将从google / facebook获得的令牌发布到后端,在那里我可以检查用户是否被禁止或等等...如果一切正常,我在数据库中为他创建了一个帐户,我发给他他的电子邮件密码,最后使用会话验证他

(req.session.userId = createdUser.id)

下次用户可以使用他的电子邮件和密码登录或只使用谷歌登录。这两个选项都将他带到同一个帐户:D

身份验证控制器中的My Sails.js函数:

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...
    }
  });



},

当然不要忘记运行 npm安装请求--save

如果有人需要facebookAuth功能,请告诉我:D我会为你发布:)