我的目标是将消息发送到属于用户的套接字,以便用户仅查看其信息或查看其角色。
到目前为止,我已经尝试过ws github和旧有的SO问题中的示例代码。这个想法是将快速会话解析器对象传递给Websocket.Server verifyClient函数。然后,当创建新的套接字时,我可以将会话信息与套接字关联。我的问题是,当连接新的套接字时,我看不到任何通行证用户,所以我一定犯错了。
以下是带有会话信息的请求的一部分:
...
session:
Session {
cookie:
{ path: '/',
_expires: 2019-06-06T20:17:56.719Z,
originalMaxAge: 3600,
httpOnly: true } } }
这是我尝试与websocket共享会话的方法:
const express = require('express'); // 4.13.4
const http = require('http');
const WebSocket = require('ws'); // 7.0.0
const session = require('express-session'); //1.16.1
const pgSession = require('connect-pg-simple')(session); // 5.0.0
const passport = require('passport'); // 0.4.0
const app = express();
const server = http.createServer(app);
let sessionParser = session({
store: new pgSession({
conString: secrets.postgres,
tableName: secrets.sessionTable
}),
secret: secrets.sessionSecret,
saveUninitialized: true,
resave: false,
cookie: {
maxAge: 3600
}
});
app.use(sessionParser);
app.use(passport.initialize());
app.use(passport.session());
let wss = new WebSocket.Server({
server: app.listen(8080),
clientTracking: true,
verifyClient: (info, done) => {
console.log("Parsing session info from request...")
sessionParser(info.req, {}, () => {
console.log(info.req);
done(info.req.session);
})
}
}, () => {});
wss.on('connection', (ws, req) => { //, req
console.log(`WS connected with user ${req}`); //.session.passport.user?
// ...
});
server.listen(8000);
编辑,在下面添加了护照代码:
'use strict';
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const secrets = require('./secrets');
const db = require('../models');
const UserRepo = require('../repositories/UserRepository');
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
db.User.findByPk(id).then(function(user) {
done(null, user);
}).catch(function(error) {
done(error);
});
});
/**
* Sign in using Email and Password.
*/
passport.use(new LocalStrategy({ usernameField: 'email' }, function(email, password, done) {
email = email.toLowerCase();
db.User.findUser(email, password, function(err, user) {
if(err)
return done(err, null);
return done(null, user);
});
}));
/**
* Login Required middleware.
*/
exports.isAuthenticated = function(req, res, next) {
if (req.isAuthenticated()) return next();
res.redirect('/login');
};
/**
* Authorization Required middleware.
*/
exports.isAuthorized = function(req, res, next) {
var provider = req.path.split('/').slice(-1)[0];
if (req.user.tokens[provider]) {
next();
} else {
res.redirect('/auth/' + provider);
}
};