EzDevInfo.com

passport.socketio

access passport.js authenticated user information from socket.io connection

Primus.io and passport.js

I consider moving from Socket.io to Primus.io (due to scalability bug) but one major plugin I'm missing is a primus-passportjs authorization plugin (something like passport.socketio).

Do you know any such plugin or code example?


Source: (StackOverflow)

Socket.io, Passport, MongoDB & passport.socketio broken in production

I built a nodejs application relaying on socket.io, using Passport & passport.socketio for authentication and authorization, and mongodb with connect-mongo for session store.

It works well on my laptop, but when I moved to the Cloud (Azure-VM) I started getting strange errors.

05-02-2014, 11:47:06.500 Listening on port 8081 (https)

/home/azureuser/myapp/node_modules/mongodb/lib/mongodb/connection/base.js:242
    throw message;      
          ^
Error: Error in session store:
Error: failed to deserialize user out of session
    at Object.io.set.passportSocketIo.authorize.fail     (/home/azureuser/myapp/lib/express/socketio.js:25:23)
    at /home/azureuser/myapp/node_modules/passport.socketio/lib/index.js:48:21
    at /home/azureuser/myapp/node_modules/connect-mongo/lib/connect-mongo.js:229:23
    at /home/azureuser/myapp/node_modules/mongodb/lib/mongodb/collection/query.js:147:5
    at Cursor.nextObject (/home/azureuser/myapp/node_modules/mongodb/lib/mongodb/cursor.js:733:5)
    at commandHandler (/home/azureuser/myapp/node_modules/mongodb/lib/mongodb/cursor.js:713:14)
    at /home/azureuser/myapp/node_modules/mongodb/lib/mongodb/db.js:1806:9
    at Server.Base._callHandler (/home/azureuser/myapp/node_modules/mongodb/lib/mongodb/connection/base.js:442:41)
    at /home/azureuser/myapp/node_modules/mongodb/lib/mongodb/connection/server.js:485:18
    at MongoReply.parseBody (/home/azureuser/myapp/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:68:5)

Any ideas where to start?


Source: (StackOverflow)

Advertisements

passport.socketio & client side connect/reconnect only when reboot server

I've got a real time app that works fine with express+passportJS and without socket authentication. When I add passport.socketio, my problem is that sockets will only connect when I reboot the server...

I've got passportjs & passport.socketio on the server and on the client side I've got angularjs with btford.socket-io:

angular.module('Socket', ['btford.socket-io'])

    .factory('socket',['socketFactory', function(socketFactory){
        var myIoSocket = io.connect("http://192.168.0.7:8080");

        mySocket = socketFactory({
            ioSocket: myIoSocket
        });

        return mySocket;
    }]);

When a user logs in, I'm doing socket.connect();. This doesn't seem to be doing anything on the server side, I'm not seeing any logs...

Here's the implementation, as per the tutorial, of passport.socketio

var io = require('socket.io').listen(app.listen(port));
var passportSocketIo = require("passport.socketio");

io.use(passportSocketIo.authorize({
    cookieParser: cookieParser,
    secret:       'secret',
    store:        sessionStore,
    success:      onAuthorizeSuccess,
    fail:         onAuthorizeFail,
}));

function onAuthorizeSuccess(data, accept){
    log.debug('successful connection to socket.io');
    return accept();
}

function onAuthorizeFail(data, message, error, accept){
    log.debug('unsuccessful connection to socket.io');
    if(error){
        throw new Error(message);
    }

    return accept(new Error(message));
}

The weird thing is, when I restart the server, I can see a lot of log messages showing that all sockets I tried to connect now actually connect.

And then it seems to let user exchange over socket and work as expected.

Anyone knows what might be happening?


Source: (StackOverflow)

passport.socketio's passport "Failed to deserialize user out of session". But passport in my main app (with the same key) deserializes just fine

passport.socketio throwing this error, while failing to authorize the user.

Error: Error: Failed to deserialize user out of session

I've narrowed the problem down to passport.socketio's /lib/index.js.

At line 59

  auth.passport.deserializeUser(userKey, function(err, user) {
    if (err)
      return auth.fail(data, err, true, accept);
    ...

It throws that error. Debugger tells me the userKey is valid, and should deserialize the user. It's the same key that passport in my main app uses to deserialize the user. (it's the ID of mongoDB object). And passport in my main app has no problem deserializing the user. (details) So don't know why this still throws the error.

The userKey passed here is the same key passport in my main app uses to deserialize.

I've gone to the extent of making the userKey global and putting it in my main code

  passport.deserializeUser(global.userKey, function(err, user) {
    if (err)
      return auth.fail(data, err, true, accept);
    console.log('ok');

Which results in infinite loop (because it's inside outer passport.deserialize) but iut prints 'ok'!, so passport from my main app can atleast deserialize just fine using the same thing that passport from index.js (passport.socketio\lib\index.js) can not! .. for some reason.

Then I've even tried passing the passport object itself from main app

io.set('authorization', require('passport.socketio').authorize({
    passport: passport,
    ...

which actually results in no errors!! but then I don't get the socket.handshake object.

I'm out of ideas to diagnose this any further and would really appreciate any help whatsoever.

What could be causing passport.socketio's passport to not "deserialize user out of session"?


Source: (StackOverflow)

Does Express.io has a property authorization to reload a session data??

I have been implementing the socket concept as in the https://github.com/techpines/express.io/tree/master/examples/sessions, I am able to display the session data that is stored once the page is initialised. But nevertheless , when a session data keeps on changing over an interval , i get that session data emitted as undefined..

But similar concept is well done using socket.io authorization & handshake session provided the link http://www.danielbaulig.de/socket-ioexpress/

Client Side code :

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect();

  // Emit ready event.
  setInterval(function(){
    socket.emit('ready', 'test');
  },2000);

  // Listen for get-feelings event.
  socket.on('get-feelings', function () {
  socket.emit('send-feelings', 'Good');
  })

  // Listen for session event.
  socket.on('session', function(data) {
  document.getElementById('count').value = data.count;
  })
</script>

<input type="text" id="count" />

Server Side Code :

express = require('express.io')
app = express().http().io()

// Setup your sessions, just like normal.
app.use(express.cookieParser())
app.use(express.session({secret: 'monkey'}))

// Session is automatically setup on initial request.
app.get('/', function(req, res) {
    var i = 0;
setInterval(function(){
   req.session.count = i++;
   console.log('Count Incremented as '+ req.session.count);
},1000);

res.sendfile(__dirname + '/client.html')
})

// Setup a route for the ready event, and add session data.
app.io.route('ready', function(req) {

 req.session.reload( function () {
        // "touch" it (resetting maxAge and lastAccess)
        // and save it back again.
        req.session.touch().save(function() {
           req.io.emit('get-feelings')
        });
    });
 /*
req.session.save(function() {
    req.io.emit('get-feelings')
})*/
})

// Send back the session data.
app.io.route('send-feelings', function(req) {
 console.log('Count Emitted as '+ req.session.count); // it is undefined in console

 req.session.reload( function () {
        // "touch" it (resetting maxAge and lastAccess)
        // and save it back again.
        req.session.save(function() {
          req.io.emit('session', req.session)
      });
    });

})

app.listen(7076);

in console , it is printed as undefined in every emit ... i want to why socket session is not updated as the original user session keeps changing ... ???

Do i need to put any extra configuaration in the server side to handle changing session data ???


Source: (StackOverflow)

client connecting twice to server, Socket.io

I am trying to log username of logged in users by connecting socket.io to passport.js using passport.socketio. It is successful however it logs the username twice and after trying and searching for a fair amount of time I am stuck.

The code sections are as follows:

The Server Code:

var server = http.createServer(app);
var io = require('socket.io')(server);

io.use(passportSocketIo.authorize({
  cookieParser: cookieParser,       // the same middleware you registred in express
  key:          'connect.sid',       // the name of the cookie where express stores its session_id
  secret:       'hello',    // the session_secret to parse the cookie
  store:        new (require("connect-mongo")(Esession))({
    url: "mongodb://localhost/local"
  }),        // we NEED to use a sessionstore. no memorystore please
  success:      onAuthorizeSuccess,  // *optional* callback on success - read more below
  fail:         onAuthorizeFail,     // *optional* callback on fail/error - read more below
}));

function onAuthorizeSuccess(data, accept){
  console.log('successful connection to socket.io');
  accept(null, true);
  accept();
}

function onAuthorizeFail(data, message, error, accept){
  if(error)
    throw new Error(message);
  console.log('failed connection to socket.io:', message);

  // We use this callback to log all of our failed connections.
  accept(null, false);

  // OR

  // If you use socket.io@1.X the callback looks different
  // If you don't want to accept the connection
  if(error)
    accept(new Error(message));
  // this error will be sent to the user as a special error-package
  // see: http://socket.io/docs/client-api/#socket > error-object
}
io.on('connection', function(socket) {
  var userID = socket.request.user;
  console.log(userID.tg+ " has connected")

});

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
server.listen(port);

The Client Code

<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
    var socket = io.connect();
</script>

The output is as follows:

successful connection to socket.io
UserName has connected
UserName has connected

I am unsure as to why it is outputting twice any help would be much appreciated. I am relatively new to Node.js but I don't believe it's the passport part that is causing it, however I am stuck so I might not have the best idea.

Thanks in Advanced

EDIT: Tried the latest version of socket and checked my own version both seem to be latest versions, Just to make sure I updated the client code to:

<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="https://cdn.socket.io/socket.io-1.3.2.js"></script>
<script>
    var socket = io.connect();
</script>

the issue persists


Source: (StackOverflow)

How to use passport.socketio in sails with passport

I received the following errors when I use socketio after user login. I found passport-socketio that perhaps solve this problem, but I do not know how integrates it to sails.js. Do you know any code example? Thinks

error: TypeError: Object #<Object> has no method 'isAuthenticated'
at module.exports (/Users/peng/www/321bougez/api/policies/isAuthenticated.js:13:11)
at _bind.enhancedFn (/Users/peng/www/321bougez/node_modules/sails/lib/router/bind.js:375:4)
at callbacks (/Users/peng/www/321bougez/node_modules/sails/node_modules/express/lib/router/index.js:164:37)
at param (/Users/peng/www/321bougez/node_modules/sails/node_modules/express/lib/router/index.js:138:11)
at param (/Users/peng/www/321bougez/node_modules/sails/node_modules/express/lib/router/index.js:135:11)
at pass (/Users/peng/www/321bougez/node_modules/sails/node_modules/express/lib/router/index.js:145:5)
at nextRoute (/Users/peng/www/321bougez/node_modules/sails/node_modules/express/lib/router/index.js:100:7)
at callbacks (/Users/peng/www/321bougez/node_modules/sails/node_modules/express/lib/router/index.js:167:11)
at wrapperFn (/Users/peng/www/321bougez/node_modules/sails/lib/hooks/controllers/index.js:293:4)
at _bind.enhancedFn (/Users/peng/www/321bougez/node_modules/sails/lib/router/bind.js:375:4)

Source: (StackOverflow)

Node.JS + Passport.SocketIO: Edit And Save `socket.handshake.user` Properties

I am using Node.JS (0.10.28), Passport.JS (0.2.0) + Passport-Google (0.3.0), and Passport.SocketIO (3.0.1).


Currently, I am able to access the user created by Passport.JS in my app's paths by using req.user:

app.get('/profile', function(req, res) {
  // send user data
  res.send(req.user);
});

Using Passport.SocketIO, I am also able to access the user in:

io.sockets.on('connection', function(socket) {
  // get user data
  console.log(socket.handshake.user);

  //...
});

It is also possible to edit req.user and 'save' it by using req._passport.session.user.property = new_property_value in the app.get/post/all(...) scope. The updates then show up in io.sockets.on(...) user object.

My question is: Is it possible to edit and 'save' socket.handshake.user in the io.sockets.on(...) scope so that the updated user will show the changes in req.user in app.get/post/all(...)? I have tried the following to no avail:

io.sockets.on('connection', function(socket) {
  // rename username
  socket.handshake.user.username = 'new_username';

  //...
});

...

app.get('/profile', function(req, res) {
  // send user data
  res.send(req.user); // returns {..., username: 'old_username', ...}
});

Source: (StackOverflow)

Passport.socketio has issues finding session

I am trying to access the session from sockets, but can't seem to make a connection. Without fail, authorization fails and I get the fail callback with the following message:

failed connection to socket.io: No session found

I will place all my code here so that it might be easier to spot what I'm doing wrong.

var express  = require('express');
var app      = express();
var http     = require('http');
var socketio = require('socket.io')
var passportSocketIo = require('passport.socketio');
var port     = process.env.PORT || 3000;
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');
var MongoStore   = require('connect-mongo')(session);

var server   = http.createServer(app);
var io       = socketio.listen(server);

var dbConfig = require('./config/database.js');
mongoose.connect(dbConfig.url);
var sessionStore = new MongoStore({ db: mongoose.connection.db });

require('./config/passport')(passport);

app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.set('view engine', 'ejs');

app.use(session({
    key: 'connect.sid',
    secret: 'secret',
    store: sessionStore,
    resave: true,
    saveUninitialized: true
}));

app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(express.static(__dirname + '/public'));

require('./app/routes.js')(app, passport);

server.listen(3000, function() {
    console.log('App running on port: ' + port);
});

io.use(passportSocketIo.authorize({
    passport:     passport,
    cookieParser: cookieParser,
    key:          'connect.sid',
    secret:       'secret',
    store:        sessionStore,
    success:      onAuthorizeSuccess,
    fail:         onAuthorizeFail
}));

function onAuthorizeSuccess(data, accept){
  console.log('successful connection to socket.io');
  accept(null, true);
}

function onAuthorizeFail(data, message, error, accept){
  if(error)
    throw new Error(message);
  console.log('failed connection to socket.io:', message);
  accept(null, false);
}

io.sockets.on('connection', function(socket) {
    var date = new Date();
    var time = date.getHours() + ":" + date.getMinutes();
    socket.emit('message', {username: 'Server', message: 'welcome to the chat'});
    socket.on('send', function(data) {
        io.sockets.emit('message', data);
    });
});

How should I be establishing a connection to the session with socket.io?

Also, I have seen that the user data is accessed via socket.handshake.user. Would that be correct in this case?

And for clarity, the versions are as follows:

express: 4.8.5
passport: 0.2.0
socket.io: 1.0.6
passport.socketio: 3.2.0

EDIT

It appears that part of the issue was the localhost versus 127.0.0.1 bug that already exists. However, now I don't get any handshake data back.


Source: (StackOverflow)

How to open a socket connection when a user is authorized to be added to the session?

I am attempting to set up an express server where a socket connection will be initiated upon user authentication using passport-local. I have been getting the error "TypeError: object is not a function" on the final line in the file that I configure my passport in.

This is my passport.js file:

var LocalStrategy   = require('passport-local').Strategy;
var Player          = require('../app/models/playerModel.js');

module.exports = function(passport) {
passport.serializeUser(function(player, done) {
    done(null, player.id);
});

passport.deserializeUser(function(id, done) {
    Player.findById(id, function(err, player) {
        done(err, player);
    });
});

//login
passport.use('local-login', new LocalStrategy({
    usernameField : 'username',
    passwordField : 'password',
    passReqToCallback : true 
},
function(req, username, password, done) { // callback with username and password from our form

    // find a user whose username is the same as the forms username
    // we are checking to see if the user trying to login already exists
    Player.findOne({ 'local.username' :  username }, function(err, player) {
        // if there are any errors, return the error before anything else
        if (err)
            return done('test' + err);

        // if no user is found, return the message
        if (!player)
            return done(null, false, console.log('No user found.'));

    // if the user is found but the password is wrong
        if (!player.validPassword(password))
            return done(null, false, console.log('Oops! Wrong password.')); 

        // THIS IS THE LINE THAT THROWS THE ERROR
        return done(null, player);
    });

}));
};

Here is my server.js file:

var
 express  = require('express'), // framework
 http     = require('http'),
 io = require('socket.io'),
 mongoose = require('mongoose'), // object modeling for mongodb
 passport = require('passport'), // user authentication and authorization
 passportSocketIo = require('passport.socketio'),
 routes   = require('./app/routes.js'),
 configDB = require('./config/database.js'),
 MemoryStore = express.session.MemoryStore,
 sessionStore = new MemoryStore(),

 app      = express(),
 server   = http.createServer(app),
 port     = process.env.PORT || 8080;

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

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

app.configure(function() {

// set up our express application
    app.use(express.logger('dev')); // log every request to the console
    app.use(express.cookieParser()); // read cookies (needed for auth)
    app.use(express.bodyParser()); // get information from html forms
    app.use(express.methodOverride()); // used for creating RESTful services
    app.use(express.static( __dirname + '/app')); // defines root directory for static files

// required for passport
    app.use(express.session({ secret: 'secret', key: 'express.sid' , store: sessionStore})); // session secret
    app.use(passport.initialize());
    app.use(passport.session()); // persistent login sessions
});

routes.configRoutes(app, server, passport); // load our routes and pass in our app and fully configured passport

server.listen(port);
io = io.listen(server);

io.set('authorization', passportSocketIo.authorize({
    cookieParser: express.cookieParser,
    key:         'express.sid',       // the name of the cookie where express/connect  stores its session_id
    secret:      'session_secret',    // the session_secret to parse the cookie
    store:       sessionStore,        
    success:     onAuthorizeSuccess,  // *optional* callback on success - read more below
    fail:        onAuthorizeFail,     // *optional* callback on fail/error - read more below
 }));

function onAuthorizeSuccess(data, accept){
  console.log('successful connection to socket.io');
  accept(null, true);
}

function onAuthorizeFail(data, message, error, accept){
  if(error)
    throw new Error(message);
  accept(null, false);
}

the part of my routes.js that handles login:

app.get('/login', function(req, res) {
console.log("log in");
});

// process the login form
app.post('/login', passport.authenticate('local-login', {
    successRedirect : '/', // redirect to the secure profile section
    failureRedirect : '/test', // redirect back to the signup page if there is an error
    failureFlash : true // allow flash messages
}));

If I comment out the io.set('authorization' function, the user seems to authenticate. I thought that all the function does is use the passport authentication function to allow a socket connection to be established. Why does it all of a sudden not authenticate when I attempt to start a socket connection?

I don't think I fully understand the way the authentication works. When I submit my login form, I send a post to "dirname/login", which is handled in my routes.js file. passport.authenticate is the callback to be run when the post is recieved, which then searches my db for the player and if the correct username and password is recieved the player object is serialized and added to the session. Where does socket.io come in? Does the io.set('authorization' function add a listener to see when the user is authenticated?

Sorry for the wall of code, I'm new to node and I don't fully understand the process.


Source: (StackOverflow)

Java Socket.io client with socket.io passport server authentication

I am using the https://github.com/nkzawa/socket.io-client.java library, and it works. My issue is that my server is running socket.io passport and requires authentication. Does anyone know how I can authenticate my client using the socket.io-client.java library? Thanks in advance.


Source: (StackOverflow)

Socket.io won't connect with Passport.socketio implemented

I'm making a game using Express, Passport.js, and Socket.io. I need the user to authenticate and then I need to access their properties within the Socket.io connection in order to send their properties to my client side JS.

Here's what I have running on my server:

var express = require('express');
var app = express();

var server = require('http').createServer(app);
var io = require('socket.io')(server);
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var expressSession = require('express-session');
var RedisStore = require('connect-redis')(expressSession);
var passportSocketIo = require("passport.socketio");
var http = require("http");
var mongojs = require("mongojs");
var uri = "mongodb://xUser:xPassword@dbUrl";
var db = mongojs.connect(uri, ["users"]);
var users = db.collection('users');
var sessionStore = new RedisStore();

app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

 app.use(expressSession({
  key: 'express.sid',
  store: sessionStore,
  secret: process.env.SESSION_SECRET || 'secret',
  saveUninitialized: false,
  resave: false
}));

passport.use(new FacebookStrategy({
 clientID: 'x',
 clientSecret: 'XX',
 callbackURL: 'http://localhost:3000/auth/facebook/callback'
},
function(accessToken, refreshToken, profile, done) {
     db.users.find({id: profile.id}, function (err, data) {
         if (data[0] === undefined) {


             users.insert({ 
                id: profile.id,
                username: profile.name.givenName, 
                balance: 1000
            });
             db.users.find({id: profile.id}, function (err, data) {
                 done(null, {id: data[0].id, balance: data[0].balance});
             });


         } else if (data[0] != undefined) {
            done(null, {id: data[0].id, balance: data[0].balance});  
         }

     });
}
));

passport.serializeUser(function(user, done) {
    done(null, user.id);
});
passport.deserializeUser(function (id, done) {
    db.users.find({id: id}, function (err, user) {
        done(null, {confirmation: user[0].id, id: user[0].username, balance: user[0].balance });
    });   
});


app.use(passport.initialize());
app.use(passport.session());






io.use(passportSocketIo.authorize({
  cookieParser: cookieParser, 
  key:          'express.sid',      
  secret:       process.env.SESSION_SECRET || 'secret',     
  store:        sessionStore,  
success:        onAuthorizeSuccess,
  fail:          onAuthorizeFail,
}));

function onAuthorizeSuccess(data, accept){
  console.log('successful connection to socket.io');
  accept();
}

function onAuthorizeFail(data, message, error, accept){
  console.log('failed connection to socket.io:', data, message);
  if(error)
    accept(new Error(message));
}

app.get('/logout', function (req, res) {
    req.logout();
    res.redirect('/');
});

app.get('/', function(req, res){
    res.render('index', {
        isAuthenticated: req.isAuthenticated(),
        user: req.user
    }); 
});

var jackpotVal = 0;
var bidPrc = 1;
var endTime;
var winningUser = '';


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

      console.log(socket.request.user);

      socket.on('bid', function(msg){
          if (socket.request.user === undefined){} 
          else if (bidPrc <= socket.request.user.balance) {
                //game mechanics
                io.emit('bid', {jackpot: jackpotVal, bidPrice: bidPrc, user: socket.request.user, endTime: endTime, balance: socket.request.user.balance
                });   
          }
      });
      socket.on('gameStarted', function(check){
          //game mechanics
          io.emit('gameStarted', {jackpot: jackpotVal, bidPrice: bidPrc, user: socket.request.user, endTime: endTime
                               });   

      });



});

app.get('/auth/facebook', passport.authenticate('facebook'));
app.get('/auth/facebook/callback', 
  passport.authenticate('facebook', { successRedirect: '/',
                                      failureRedirect: '/' }));


var port = process.env.PORT || 3000;
server.listen(port, function () {
  console.log('Server listening at port %d', port);
});

This all works fine to log in and everything, until someone emits a bid or gameStarted from client side, at which point it does nothing. It doesn't console.log(socket.request.user) when someone loads the page either. I don't get any errors in my console or anything. I'm not exactly sure what I'm supposed to put in the "key" or "secret" fields, or if that has anything to do with why my code isn't working.

The bids are received and emitted properly when I take out the io.use(passportSocketIo.authorize({...})); portion.

What's wrong with my code?


Source: (StackOverflow)

How do I connect clients to a Socket.io socket without authenticating them? [duplicate]

This question is an exact duplicate of:

I'm building an application using Express, Socket.io, Passport.js, Firebase, and Passport.socketio to authenticate users into my socket connection. Before I implemented Passport.socketio clients were connected to the socket by default when they load the page regardless of whether or not they were signed in with Passport, but since implementing Passport.socketio users won't see emissions from other users until they sign in. The only reason I set it up this way is so I could have access to socket.request.user within the connection to emit user data.

Sever code:

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var passport = require('passport');
passportLocal = require('passport-local');
var FacebookStrategy = require('passport-facebook').Strategy;
var bodyParser = require('body-parser');
app.use(bodyParser.json());
var cookieParser = require('cookie-parser');
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

var options = {
  host: 'x',
  reapInterval: 600000
};

var session = require('express-session'),
  FirebaseStore = require('connect-firebase')(session);
var sessionStore = new FirebaseStore(options);
app.use(session({
  store: sessionStore, 
    key: 'connect.sid',
  secret: process.env.SESSION_SECRET || 'secret',
    saveUninitialized: false,
    resave: false

}));
var passportSocketIo = require("passport.socketio");

var http = require("http"),
    mongojs = require("mongojs");


var uri = "x",
    db = mongojs.connect(uri, ["users"]);

app.use(passport.initialize());
app.use(passport.session());


passport.use(new FacebookStrategy({
 clientID: 'x',
 clientSecret: 'x',
 callbackURL: 'http://x/auth/facebook/callback'
},
function(accessToken, refreshToken, profile, done) {
     //Facebook sign up
}
));

passport.serializeUser(function(user, done) {
    done(null, user.id);
});
passport.deserializeUser(function (id, done) {
    db.users.find({id: id}, function (err, user) {
        done(null, {confirmation: user[0].id, id: user[0].username, balance: user[0].balance, photo: user[0].photo});
    });   
});



io.use(passportSocketIo.authorize({
  cookieParser: cookieParser, 
  key:          'connect.sid',     
  secret:       process.env.SESSION_SECRET || 'secret',    
  store:        sessionStore, 
success:        onAuthorizeSuccess,
  fail:          onAuthorizeFail,
}));

function onAuthorizeSuccess(data, accept){
  console.log('successful connection to socket.io');
  accept();
}
function onAuthorizeFail(data, message, error, accept){
  console.log('failed connection to socket.io:', data, message);
  if(error)
    accept(new Error(message));
}


var users = db.collection('users');

//Local sign up method
passport.use(new passportLocal.Strategy(function(username, password, done) {
    db.users.find({username: username, password: password}, function(err, echoData) {
        console.log(echoData);
        if (echoData[0] != undefined) {
            done(null, {id: echoData[0].id, balance: echoData[0].balance});
        } else {
            done(null, null);
        };
    });


}));


app.post('/signup', function (req,res) {
    //user sign up 
});

app.post('/login', passport.authenticate('local', {
    successRedirect: '/',
    failureRedirect: '/' })
);


app.get('/logout', function (req, res) {
    req.logout();
    res.redirect('/');
});

 app.get('/login', function(req, res){
    res.render('login', {
        isAuthenticated: req.isAuthenticated(),
        user: req.user
    }); 
});

app.get('/', function(req, res){
    res.render('index', {
        isAuthenticated: req.isAuthenticated(),
        user: req.user
    }); 
});


io.on('connection', function(socket){
    //socket stuff I want unauthorized users to see
    socket.on('bid', function(msg){
      if (socket.request.logged_in === false){} 
      else if (bidPrc <= socket.request.user.balance) {
            //game mechanics
            io.emit('bid', {bidPrice: bidPrc, user: socket.request.user});   
      }
  });
});

app.get('/auth/facebook', passport.authenticate('facebook'));
app.get('/auth/facebook/callback', 
  passport.authenticate('facebook', { successRedirect: '/',
                                      failureRedirect: '/' }));



var port = process.env.PORT || 3000;
server.listen(port, function () {
  console.log('Server listening at port %d', port);
});

Here's basically all I'm doing client side:

var socket = io();
$('#button').click(function () {
  socket.emit('bid', {});
});
socket.on('bid', function (data) {
  //do stuff
});

When I load the page as a signed out client, I get immediately in my Git Bash "User not authorized through Passport" indicating that it's not allowing that person to connect to the socket. I do want unauthorized users to connect to the Socket, just not be able to bid (which I've already safeguarded against by making an if statement on socket.request.logged_in). Is there any way to explicitly allow everyone to connect with the way I have this set up?


Source: (StackOverflow)

What's the better way of implementing security with MEAN.js

I'm working with mean.js, and I have a little doubt about authentication and authorization here...

MEAN.js come with a out of the box passport.js implementation that seems to be working good enough for me just to know when a user is logged in. But at the moment of authorization some question pop up in my mind.. doing my research I reach some answers and I don’t know what is the best way of implementing security API calls in my app.

So far, I'm taking this solution:

Using express.all() function to set in one file all my authorization functions ( I guess it is a good practice right ? ).. creating a file with the following code example:

'use strict';
var passport = require('passport');
module.exports = function(app) {

    app.route('/private/p/*').all(function(req, res, next){
        if(!req.isAuthenticated()){
            res.send(401);
        }else{
            next();
        }
    });

    app.route('/private/byRoles/*').all(function(req, res, next){
        if(!req.isAuthenticated()){
            res.send(401);
        }else{
             var urlRoles = ['admin', 'godlike'];
            // ROLE LOGICS THAT ARE GOING TO BE ADDED TO MY USER
            // GETTING MY USER ID BY THE DE-SERIALIZE PASSPORT FUNCTION AND GETTING MY 
            // MONGO MODEL FOR MY USER, WITH THE INFO OF ROLES IN THERE AND DOING 
            // SOME LOGICS HERE ABOUT THE ROLES AND URL PATTERN.
            if ( hasRole(urlRoles, user.roles)){
                next();
                }else{
                   res.send(401);
                }
        }
    });
};

So far this is the solution that I'm planning to implement, but I would like to be sure of what I'm doing here... is there a better way of implementing authorization in mean.js ? Is this authorization middle-ware wrong implemented with passport? I don't sure if is necessary to implement another strategy to this.. or if this implementation has a security lack ( sure it has to ).. is better to use Oauth or using api token ??? what should be the architecture to secure an app made in MEAN.js supporting roles and permissions ?? also in the future I would need to secure my socket.. I was looking at passport-socketio.. but not sure if is there a better solution.


Source: (StackOverflow)

how to use both express.io and passport.socketio authentication features globally

socket.io supports a single global authorization method with no middleware feature. Both express.io and passport.socketio depend on this feature as an injection point for their logic.

express.io attaches the express session to the request, and passport.socketio attaches the inflated user object. how do I combine the two features elegantly?


Source: (StackOverflow)