1

我正在尝试设置一个快速服务器,其中将在使用本地护照进行用户身份验证时启动套接字连接。我在配置护照的文件的最后一行收到错误“TypeError:对象不是函数”。

这是我的 passport.js 文件:

var LocalStrategy   = require('passport-local').Strategy;
var Player          = require('../app/models/playerModel.js');

module.exports = function(passport) {
passport.serializeUser(function(player, done) {
    done(null, player.id);
});

passport.deserializeUser(function(id, done) {
    Player.findById(id, function(err, player) {
        done(err, player);
    });
});

//login
passport.use('local-login', new LocalStrategy({
    usernameField : 'username',
    passwordField : 'password',
    passReqToCallback : true 
},
function(req, username, password, done) { // callback with username and password from our form

    // find a user whose username is the same as the forms username
    // we are checking to see if the user trying to login already exists
    Player.findOne({ 'local.username' :  username }, function(err, player) {
        // if there are any errors, return the error before anything else
        if (err)
            return done('test' + err);

        // if no user is found, return the message
        if (!player)
            return done(null, false, console.log('No user found.'));

    // if the user is found but the password is wrong
        if (!player.validPassword(password))
            return done(null, false, console.log('Oops! Wrong password.')); 

        // THIS IS THE LINE THAT THROWS THE ERROR
        return done(null, player);
    });

}));
};

这是我的 server.js 文件:

var
 express  = require('express'), // framework
 http     = require('http'),
 io = require('socket.io'),
 mongoose = require('mongoose'), // object modeling for mongodb
 passport = require('passport'), // user authentication and authorization
 passportSocketIo = require('passport.socketio'),
 routes   = require('./app/routes.js'),
 configDB = require('./config/database.js'),
 MemoryStore = express.session.MemoryStore,
 sessionStore = new MemoryStore(),

 app      = express(),
 server   = http.createServer(app),
 port     = process.env.PORT || 8080;

mongoose.connect(configDB.url); // connect to our database

require('./config/passport')(passport); // pass passport for configuration

app.configure(function() {

// set up our express application
    app.use(express.logger('dev')); // log every request to the console
    app.use(express.cookieParser()); // read cookies (needed for auth)
    app.use(express.bodyParser()); // get information from html forms
    app.use(express.methodOverride()); // used for creating RESTful services
    app.use(express.static( __dirname + '/app')); // defines root directory for static files

// required for passport
    app.use(express.session({ secret: 'secret', key: 'express.sid' , store: sessionStore})); // session secret
    app.use(passport.initialize());
    app.use(passport.session()); // persistent login sessions
});

routes.configRoutes(app, server, passport); // load our routes and pass in our app and fully configured passport

server.listen(port);
io = io.listen(server);

io.set('authorization', passportSocketIo.authorize({
    cookieParser: express.cookieParser,
    key:         'express.sid',       // the name of the cookie where express/connect  stores its session_id
    secret:      'session_secret',    // the session_secret to parse the cookie
    store:       sessionStore,        
    success:     onAuthorizeSuccess,  // *optional* callback on success - read more below
    fail:        onAuthorizeFail,     // *optional* callback on fail/error - read more below
 }));

function onAuthorizeSuccess(data, accept){
  console.log('successful connection to socket.io');
  accept(null, true);
}

function onAuthorizeFail(data, message, error, accept){
  if(error)
    throw new Error(message);
  accept(null, false);
}

我的 routes.js 中处理登录的部分:

app.get('/login', function(req, res) {
console.log("log in");
});

// process the login form
app.post('/login', passport.authenticate('local-login', {
    successRedirect : '/', // redirect to the secure profile section
    failureRedirect : '/test', // redirect back to the signup page if there is an error
    failureFlash : true // allow flash messages
}));

如果我注释掉io.set('authorization'函数,用户好像在认证。我以为函数所做的就是使用passport认证函数来允许建立一个socket连接。为什么突然不当我尝试启动套接字连接时进行身份验证?

我不认为我完全理解身份验证的工作方式。当我提交登录表单时,我会向“dirname/login”发送一个帖子,该帖子在我的 routes.js 文件中处理。passport.authenticate 是收到帖子时要运行的回调,然后在我的数据库中搜索播放器,如果收到正确的用户名和密码,播放器对象将被序列化并添加到会话中。socket.io 是从哪里来的?io.set('authorization' 函数是否添加了一个监听器来查看用户何时通过身份验证?

对不起,代码墙,我是节点新手,我不完全理解这个过程。

4

1 回答 1

1

在这里找到了答案!显然,我只需要更改我的 passport.socketio index.js 文件中的一行,因为 socketio 试图使用一个奇怪的护照版本。

改变这个:

var defaults = {
   passport:     require('passport'),
   key:          'connect.sid',
   secret:       null,
   store:        null,
   success:      function(data, accept){accept(null, true)},
   fail:         function(data, message, critical, accept){accept(null, false)}
};

对此:

var defaults = {
   passport:     null,
   key:          'connect.sid',
   secret:       null,
   store:        null,
   success:      function(data, accept){accept(null, true)},
   fail:         function(data, message, critical, accept){accept(null, false)}
};

然后将您正在使用的护照 obj 传递给 io 授权函数:

io.set('authorization', passportSocketIo.authorize({
    passport:     passport,
    cookieParser: express.cookieParser,
    key:         'express.sid',       // the name of the cookie where express/connect  stores its session_id
    secret:      'session_secret',    // the session_secret to parse the cookie
    store:       sessionStore,        
    success:     onAuthorizeSuccess,  // *optional* callback on success - read more below
    fail:        onAuthorizeFail,     // *optional* callback on fail/error - read more below
}));
于 2014-05-23T17:21:25.450 回答