我无法使用socket.io发送聊天消息

时间:2016-10-20 22:46:01

标签: node.js redis socket.io passport.js

之前我可以发送消息,但是我通过遵循本教程http://www.scotthasbrouck.com/blog/2016/3/18/passportjs-express-session-with-sockeio使用redis与express和socket.io共享护照会话,现在我再也无法发送任何聊天消息了。

另外,在我的路线中,req.isAuthenticated()总是返回false,但之前我没有遇到过这个问题。

这是我的server.js。

// server.js

// set up ======================================================================
// get all the tools we need
var express  = require('express');
var app      = express();
var server = require('http').Server(app);

var port     = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash    = require('connect-flash');

var morgan       = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser   = require('body-parser');


var configDB = require('./config/database.js');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var passportSocketIo = require('passport.socketio');
var session      = require('express-session');
var chatdb = require('./app/models/chat.js');
var user = require('./app/models/user.js');
var redis = require('redis');
var client = redis.createClient();
var RedisStore = require('connect-redis')(session);

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

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

// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms

app.set('view engine', 'ejs'); // set up ejs for templating

var sessionStore = new RedisStore({ host: 'localhost', port: 6379, client: client, ttl:  260 });

// required for passport
app.use(session({
  secret: 'secret',
  store: sessionStore,
  resave: true,
  saveUninitialized: true,
 cookie: {
  secure: process.env.ENVIRONMENT !== 'development' && process.env.ENVIRONMENT !== 'test',
maxAge: 2419200000
 },

}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.use(express.static(__dirname + '/views'));
app.use(express.static(__dirname + '/public'));
io.use(passportSocketIo.authorize({
  key: 'connect.sid',
  secret: 'secret',
  store: sessionStore,
  passport: passport,
  cookieParser: cookieParser,
}));

var eventSocket = io.of('/chat');

// socket.io


io.on('connection', function (socket) {
console.log('a user connected');

socket.on('chat message', function(msg){
    var name = "efe";
    chatdb.saveMsg({name: name, msg: msg}, function(err){
        if(err) throw err;
        io.emit('chat message', msg);
    });

    if (socket.request.user && socket.request.user.logged_in) {
      console.log(socket.request.user);
    }
});


  });

 // routes ======================================================================
  require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport

  // launch ======================================================================
  http.listen(port);
  console.log('The magic happens on port ' + port);

2 个答案:

答案 0 :(得分:3)

我遇到了同样的问题。我尝试像你一样实施passport.socketio,但没有它就解决了我的问题。

这是我的中间件:

// Express session middleware
var sessionMiddleware = session({ secret: 'secret-key', resave: true, saveUninitialized: true });

// Send Express sessionMiddleware through socket.io
io.use(function(socket, next){
  // Params: request object, response object and callback.
  sessionMiddleware(socket.request, {}, next);
});

sessionMiddleware函数的第二个参数(响应对象)为空。这将使会话呈现为只读。

以下是我使用passport js会话变量获取用户信息的方法:

io.on("connection", function(socket){
  socket.on('chat message', function(msg){
    var passport = socket.request.session.passport; // Get the passport variable

    // Check if passport session exists
    if (passport && typeof passport !== 'undefined'){

      var userSession = passport.user; // Get the user session

      // Build JSON with user session data
      var message = {
        message : msg,
        name : userSession.name,
        avatar : userSession.avatar
      };

      io.emit('chat message', message); // Emit my socket
    }
  });
});

希望有所帮助。

答案 1 :(得分:-1)

这就是我能够解决它的方法。

var express = require('express');
var app = express();
var server = require('http').Server(app);

var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');

var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');

// Add connect-mongo to project - npm install connect-mongo
var MongoStore = require('connect-mongo')(session);

var configDB = require('./config/database.js');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var chatdb = require('./app/models/chat.js');

// configuration ===============================================================
// NOTE: This might need to be put into a callback/promise inside an initialize function
var db = mongoose.connect(configDB.url); // connect to our database

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

// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms

app.set('view engine', 'ejs'); // set up ejs for templating
var mongoStore = new MongoStore({
  mongooseConnection: db.connection,
});
app.use(session({
  secret: 'secret',
  clear_interval: 900,
  cookie: { maxAge: 2 * 60 * 60 * 1000 },
  store: mongoStore,
}));


// required for passport
app.use(session({ secret: 'secret' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
app.use(express.static(__dirname + '/views'));
app.use(express.static(__dirname + '/public'));


// Intercept Socket.io's handshake request
io.use(function(socket, next) {

    // Use the 'cookie-parser' module to parse the request cookies
    cookieParser('secret')(socket.request, {}, function(err) {

        // Get the session id from the request cookies
        var sessionId = socket.request.signedCookies ? socket.request.signedCookies['connect.sid'] : undefined;

        if (!sessionId) return next(new Error('sessionId was not found in socket.request'), false);

        // Use the mongoStorage instance to get the Express session information
        mongoStore.get(sessionId, function(err, session) {

            if (err) return next(err, false);
            if (!session) return next(new Error('session was not found for ' + sessionId), false);

            // Set the Socket.io session information
            socket.request.session = session;

            // Use Passport to populate the user details
            passport.initialize()(socket.request, {}, function() {
                passport.session()(socket.request, {}, function() {
                    // This will prohibit non-authenticated users from connecting to your
                    // SocketIO server.
                    if (socket.request.user) {
                        next(null, true);
                    } else {
                        next(new Error('User is not authenticated'), false);
                    }
                });
            });
        });
    });
  });

// socket.io
io.on('connection', function(socket) {

    socket.on('chat message', function(msg) {
        console.log(socket.request.user.facebook.name || socket.request.user.local.email);
        var name = socket.request.user.facebook.name || socket.request.user.local.email;
        chatdb.saveMsg({
            name: name,
            msg: msg
        }, function(err) {
            if (err) throw err;
            io.emit('chat message', msg);
        });
    });

    socket.on('disconnect', function() {
        console.log('user disconnected');
    });
});

// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport

// launch ======================================================================
http.listen(port);
console.log('The magic happens on port ' + port);