1

我的目标是将消息发送到属于用户的套接字,因此用户只能看到他们的信息或他们的用户角色。

到目前为止,我已经尝试了来自ws github和旧 SO 问题的示例代码。这个想法是将 express-session 解析器对象传递给 Websocket.Server verifyClient 函数。然后当创建一个新的套接字时,我可以将会话信息与套接字相关联。我的问题是当一个新的套接字连接时我没有看到任何护照用户,所以我一定犯了一个错误。

以下是带有会话信息的请求部分:

...
session:
   Session {
     cookie:
      { path: '/',
        _expires: 2019-06-06T20:17:56.719Z,
        originalMaxAge: 3600,
        httpOnly: true } } }

这是我尝试与 websockets 共享会话的方法:

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);
  }
};
4

0 回答 0