Passport + Socket.io获取登录的用户ID

时间:2014-09-02 22:06:18

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

我正在创建一个Node.js应用程序,我需要在socket.io中的mongoDB中创建一个新文档。 我必须在新文档中插入登录用户。

如何在socketio中访问会话变量?

// INCLUDE MODULES =======================================================
var SocketIOFileUpload = require("socketio-file-upload");
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var socketio = require('socket.io');
var Twig = require('twig');
var twig = Twig.twig;
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var Cookies = require( "cookies" );
var flash    = require('connect-flash');
var configDB = require('./config/database.js');
var connect = require('connect');

var ImageFile = require('./app/models/image');

// Assets ================================================================
app.use(express.static(path.join(__dirname, 'public')));
app.use(connect.favicon(path.join(__dirname, 'public/images/favicon.ico'))); 
// Start mongoose
mongoose.connect(configDB.url);

// USER MANAGEMENT =======================================================
require('./config/passport')(passport); // pass passport for configuration
app.use(connect.logger('dev')); // log every request to the console
app.use(connect.cookieParser()); // read cookies (needed for auth)
app.use(connect.json());       // to support JSON-encoded bodies
app.use(SocketIOFileUpload.router);         //socket io file upload
app.use(connect.urlencoded()); // to support URL-encoded bodies
app.set('view engine', 'twig'); // set up twig for templating
app.use(connect.session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash());

// Some more code ...

//SOCKET IO =======================================================
//Quand on client se connecte, on le note dans la console
var io = socketio.listen(server);
io.sockets.on("connection", function(socket){
        // Make an instance of SocketIOFileUpload and listen on this socket:
        var session = socket.handshake.session;
        var uploader = new SocketIOFileUpload();
        uploader.dir = "/LeafStore/public/uploads";
        uploader.listen(socket);
        console.log(socket.handshake.user);

        // Do something when a file is saved:
        uploader.on("saved", function(event, socket){
            console.log(event.file);
        });

     // Do something when a file is saved:
        uploader.on("complete", function(event){
            console.log("saving file" + name);
            console.log(event);
            var name = event.file.name;
            var imageData = {
                name: name
              , type: "image"
              , userId: ""
              , creationDate: new Date()
            };
            var newImage = new ImageFile(imageData);
            newImage.save( function(error, data){
                if(error){
                    throw error;
                }
                else{

                }
            });

            // save the user
            newImage.save(function(err) {
                if (err)
                    throw err;
            });;
        });

        // Error handler:
        uploader.on("error", function(event){
            console.log("Error from uploader", event);
        });
});


// LISTEN SERVER =======================================================
server.listen(80);

1 个答案:

答案 0 :(得分:0)

我找到了一个临时解决方案:

我在观看中发出用户ID:

socket.emit('userId', $("#userId").val());

然后我设置socket.userId var:

socket.on('userId', function(userId){
            socket.userId = userId;
        });

但它可能不安全