目标
我想做的事:
- 为用户创建会话
- 为套接字创建会话 (
socket.io
) - 用于
passport.js
验证登录和socket
会话。
笔记
我已经安装MongoStore
和passport.socket.io npm's
. 我可以登录并设置登录cookie
用户的(connect.sid
)
问题
如何设置系统来存储socket
会话并将它们与用户耦合session
?
代码
应用程序.js
/* The usual express setup */
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
User = require('./models/user.js'),
MongoStore = require('connect-mongo')(express);
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({
secret: 'chuck norris',
store: new MongoStore({db: User.name}, // the db's name
function(err) {
console.log(err || 'connect ok!');
})
}));
app.use(express.methodOverride());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
app.js(护照部分)
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
},
function(username, password, done) {
User.findOne({username: username}, function(err, user) {
if(!user) {
return done(null, false, {message: 'Incorrect Username!'});
}
if(!user.validPassword(password)) {
return done(null, false, {message: 'Incorrect Password!'});
}
return done(null, user);
});
}
));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
app.post('/',
passport.authenticate('local'),
function(req, res) {
res.redirect('/home/'+req.user.username);
});
app.js(socket.io 部分)
io.set('authorization', passportSocket.authorize({
key: 'connect.sid',
secret: 'chuck norris',
store: /* Not entirely sure what goes here */
fail : function(data, accept) { accept(null, false); },
success: function(data, accept) { accept(null, true); }
}));
io.sockets.on('connection', function(socket) {
console.log('User Connected: ' + socket.handshake.user.username);
});