Why is `req.user` undefined for socket requests in Sails.js, Angular.js and Passport.js?

前端 未结 3 1629
萌比男神i
萌比男神i 2021-01-14 18:30

I am trying to get the questions for the current user with a request like this:

http://localhost:1337/question/forme         


        
3条回答
  •  醉话见心
    2021-01-14 19:05

    You can inject authentication methods into socket requests. For this just make a little hijack into config/bootstrap.js.

    var passport = require('passport'),
    http = require('http'),
    initialize = passport.initialize(),
    session = passport.session(),
    methods = ['login', 'logIn', 'logout', 'logOut', 'isAuthenticated', 'isUnauthenticated'];
    
    module.exports.bootstrap = function(cb) {
        sails.removeAllListeners('router:request');
        sails.on('router:request', function(req, res) {
            initialize(req, res, function() {
                session(req, res, function(error) {
                    if (error) {
                        return sails.config[500](500, req, res);
                    }
                    for (var i = 0; i < methods.length; i++) {
                        req[methods[i]] = http.IncomingMessage.prototype[methods[i]].bind(req);
                    }
                    sails.router.route(req, res);
                });
            });
        });
    
        cb();
    };
    

    After this hijack you can use isAuthenticated() and other methods from Passport in sockets.

    And then inject user variable through policies like Scott says.

提交回复
热议问题