I\'m trying to get authentication working over sockets with sailsjs
and passport
.
The challenge seems to be the fact that a socket connection d
Thanks to Kasper Isager there will be a passport generator for sails.js in the near future (Sails.js Version 0.10).
He implement Passport by using policies (sails middleware).
api/services/passport.js
var passport = require('passport');
passport.serializeUser(function(user, next) {
next(null, user.id);
});
passport.deserializeUser(function(id, next) {
User.findOne(id).done(next);
});
// Put your Passport config logic here
// Make passport globally available
module.exports = passport;
api/policies/passport.js
module.exports = function (req, res, next) {
// Initialize Passport
passport.initialize()(req, res, function () {
// Use the built-in sessions
passport.session()(req, res, function () {
// Make the user available throughout the frontend
res.locals.user = req.user;
next();
});
});
};
config/policies.js
module.exports.policies = {
'*': [ 'passport' ],
// MyCustomController: {
// update: [
// 'passport',
// 'authorize'
// ]
// }
};
This will make the the passport request methods (logIn, etc.) available in socket requests as well.
After a successful login your server-side session object will look like this:
{
// Express
cookie: {
originalMaxAge: null,
expires: null,
httpOnly: true,
path: '/'
},
// Passport
passport: {
user: '52fc98e108b31348a537fa43' // userId
}
}
You may access it in any policy with req.session
or even on socket callbacks like:
config/sockets.js
onConnect: function(session, socket){}
onDisconnect: function(session, socket){}
If you want to see the Kaspers full implementation check out his repository: sails-generate-auth