Authentication methods over sockets

女生的网名这么多〃 提交于 2019-12-03 01:55:56

Thanks to Kasper Isager there will be a passport generator for sails.js in the near future (Sails.js Version 0.10).

He implement Passport by using policies (sails middleware).

api/services/passport.js

var passport = require('passport');

passport.serializeUser(function(user, next) {
    next(null, user.id);
});

passport.deserializeUser(function(id, next) {
    User.findOne(id).done(next);
});

// Put your Passport config logic here

// Make passport globally available
module.exports = passport;

api/policies/passport.js

module.exports = function (req, res, next) {

  // Initialize Passport
  passport.initialize()(req, res, function () {
    // Use the built-in sessions
    passport.session()(req, res, function () {
      // Make the user available throughout the frontend
      res.locals.user = req.user;

      next();
    });
  });

};

config/policies.js

module.exports.policies = {

    '*': [ 'passport' ],

    // MyCustomController: {
    //  update: [
    //      'passport',
    //      'authorize'
    //  ]
    // }

};

This will make the the passport request methods (logIn, etc.) available in socket requests as well.

After a successful login your server-side session object will look like this:

{
    // Express
    cookie: {
        originalMaxAge: null,
        expires: null,
        httpOnly: true,
        path: '/'
    },
    // Passport
    passport: {
        user: '52fc98e108b31348a537fa43' // userId
    }
}

You may access it in any policy with req.session or even on socket callbacks like:

config/sockets.js

onConnect: function(session, socket){}
onDisconnect: function(session, socket){}

If you want to see the Kaspers full implementation check out his repository: sails-generate-auth

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!