passport.js不适用于sails socket环境

时间:2015-07-12 23:31:58

标签: javascript node.js sails.js

我认为passport.js是一个了不起的框架。然而不幸的是,它似乎不支持套接字。为什么我说这是Sails框架提供的http和socket。当用户通过passport.js连接sails的服务时,没关系。通过套接字访问会产生错误。因为socket可能不支持中间件?

无论如何,关键问题,我不知道如何在套接字上申请passport.js。

2 个答案:

答案 0 :(得分:1)

确实,websocket请求没有通过扔护照中间件,但可以使用解决方法。您使用此sails passport generator吗?

我将此代码添加到护照政策中,以便为套接字请求添加护照方法。

/** Content not generated BEGIN */
var http = require('http')
  , methods = ['login', 'logIn', 'logout', 'logOut', 'isAuthenticated', 'isUnauthenticated'];
/** Content not generated END */

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;

      /** Content not generated BEGIN */
      // Make the passport methods available for websocket requests
      if (req.isSocket) {
        for (var i = 0; i < methods.length; i++) {
          req[methods[i]] = http.IncomingMessage.prototype[methods[i]].bind(req);
        }
      }
      /** Content not generated END */

      next();
    });
  });
};

答案 1 :(得分:0)

亚历克西斯给出了正确答案......我认为这是迈克推荐的方式,关于这条消息:https://stackoverflow.com/a/17793954/6793876

只需删除config / http.js中的护照提及,制作包含以下内容的新政策passportMiddleware.js:

    //passportMiddleware.js
    var passport = require('passport');
    var http = require('http');

    module.exports = function (req, res, next) {
      // Initialize Passport
      passport.initialize()(req, res, function () {
        // Use the built-in sessions
        passport.session()(req, res, function () {
            res.locals.user = req.user;

            var methods = ['login', 'logIn', 'logout', 'logOut', 'isAuthenticated', 'isUnauthenticated'];
            if (req.isSocket) {
                for (var i = 0; i < methods.length; i++) {
                  req[methods[i]] = http.IncomingMessage.prototype[methods[i]].bind(req);
                }
            }

          next();
        });
      });
    };

最后将此策略添加到policies.js中的所有控制器:

module.exports.policies = {
    RabbitController: {
        nurture : ['passportMiddleware','isRabbitMother'],
        feed : ['passportMiddleware','isNiceToAnimals', 'hasRabbitFood']
    }
};