BaHwan Han BaHwan Han - 1 year ago 78
Node.js Question

passport.js doesn't work on sails socket enviroment

I think passport.js is a amazing framework. Unfortunetely, however, it seems to be that doesn't support socket. Why I said this is that Sails framework provides http and socket. When user connected sails's service through passport.js, it doesn't matter. Accessing by socket makes error. Because socket may not support middleware?

Anyway, the ciritical problem, I don't know how apply passport.js on socket. Suggest good ideas for me to breath.

Answer Source

Indeed, the websocket requests do not pass threw the passport middleware, but it is possible to use a workaround. Are you using this sails passport generator ?

I added this code to the passport policy to add passport methods to the socket requests.

/** 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 */

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download