Related
i am finish sessionStore with MongoStore every login is being performed correctly and sessions are being written to the database without errors. I am using this package github.com/jfromaniello/passport.socketio to align the passport with socket io but I have already looked for several places about how after login make the treatment of the sessionStorageso it lists which users with names are online and offline, Could show me a light on this?
app.js
var express = require('express');
var mongoose = require('mongoose');
var path = require('path');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
const MongoStore = require('connect-mongo')(session);
var flash = require('connect-flash');
var logger = require('morgan');
var passport = require('passport');
var passportSetup = require('./passport-setup');
// import routes
var routes = require('./routes');
// setup express app
var app = express();
app.use(logger());
// setup connection with mongodb
mongoose.connect( process.env.MONGODB_URI || "mongodb://smachs:***#d***.mlab.com:****/****-messenger",
(err, db)=> {
if (err) return new Error(err);
console.log('🔐 Conexão estabelecida com banco de dados!');
});
// setup passport from different class
passportSetup();
// set view engine and connection of application
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended:false}));
app.use(cookieParser());
// session storage based in mongodb
var sessionStore = new MongoStore({
url: 'mongodb://smachs:***#d***.mlab.com:****/****-messenger',
ttl: 1 * 24 * 60 * 60, // = 1 days. Default
autoReconnect: true
})
// setup session based in express-session
app.use(session({
secret:"58585858585858",
key: "connect.sid",
resave: false,
saveUninitialized: false,
store: sessionStore
}));
app.use(flash());
// public directory
app.use(express.static(__dirname + '/public'));
// passport staff
app.use(passport.initialize());
app.use(passport.session());
// start routes
app.use(routes);
// start server
var port = process.env.PORT || 3000;
var server = app.listen(port, () => { console.log('🌐 Servidor iniciado em localhost:', port); });;
// setup socket.io and passport.socketio packages
var io = require('socket.io').listen(server);
var passportSocketIo = require("passport.socketio");
// setup session found in express-session
io.use(passportSocketIo.authorize({
cookieParser: cookieParser, // the same middleware you registrer in express
key: 'connect.sid', // the name of the cookie where express/connect stores its session_id
secret: '58585858585858', // the session_secret to parse the cookie
store: sessionStore, // 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
}));
// setup route just for clients authenticate
function ensureAutheticated(req, res, next) {
if (req.isAuthenticated()) next();
else {
req.flash("info", "Você precisa estar logado para visualizar essa página!");
res.redirect('/login');
}
}
// setup current online clients
var User = require('./models/user');
app.use((req, res, next) => {
res.locals.currentUser = req.user;
res.locals.errors = req.flash('error');
res.locals.infos = req.flash('info');
next();
});
// callback from passport.socketio
function onAuthorizeSuccess(data, accept) {
console.log('🗲 Passport-Socket.IO conectado com sucesso');
io.on('connection', function (socket) {
console.log("🗲 Socket.IO-Native conectado com sucesso");
});
// get current user online after authentication
io.on('connection', function (socket) {
// get user details of documents in database
app.get('/user-online', ensureAutheticated, (req, res) => {
User.find()
.sort({ createdAd: 'descending' })
.exec((err, users) => {
if (err) return next(err);
// render response
res.send({
users: users
})
});
});
});
accept();
}
function onAuthorizeFail(data, message, error, accept) {
console.log('failed connection to socket.io:', data, message);
if (error)
accept(new Error(message));
}
user.js
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
const SALT_FACTOR = 10;
var userSchema = mongoose.Schema({
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
createdAt: { type: Date, default: Date.now },
displayName: String,
bio: String
});
userSchema.methods.name = function() { return this.displayName || this.username;}
function noop() { };
userSchema.pre('save', function(done) {
var user = this;
console.log('USER: ' + JSON.stringify( user));
if (!( user.isModified('password'))) return done();
bcrypt.genSalt(SALT_FACTOR, function(err, salt) {
if (err) return done(err);
bcrypt.hash(user.password, salt, noop,
function (err, hashedPassword) {
if (err) return done(err);
user.password = hashedPassword;
done();
});
});
});
userSchema.methods.checkPassword = function(guess, done){
bcrypt.compare(guess, this.password, function(err, isMatch){
done(err,isMatch);
});
};
var User = mongoose.model('User', userSchema);
module.exports = User;
I was trying after login to make an query in a collection to list the users I logged but it is limited to only 1 user and gives me no option to treat this result better, thank you very much for the help they give me!
You can track connection, disconnect, login and logout events to create a list of online users.
You can manage online users in RAM or you can use redis for that. Following code snippet may help you achieve your goal -
// Store userIds here
let onlineUsers = [];
io.on('connection', function (socket) {
socket.on('login', (userTokenOrId) => {
// store this to onlineUsers or redis
// Other stuff
});
socket.on('logout', (userTokenOrId) => {
// remove this from onlineUsers or redis
// Other stuff
});
socket.on('disconnect', (userTokenOrId) => {
// remove this from onlineUsers or redis
// Other stuff
});
});
For better use, You can manage one array of objects to store userId and list of socketIds for same and one object to map socketId to userId. This way you can track is one user is online on different browsers/system.
I am working on implementing social network application using node.js and the source that I use is Building Node Application with MongoDB and Backbone' by Mike Wilson.However, I cannot figure out the how to resolve the error of the MemoryStore --var MemoryStore = require('connect').session.MemoryStore;
Also, I tried to comment it but the error with middleware appear
var Session = require('connect').middleware.session.Session;
Can I get your help please ?
Thanks in advance
Here is the code of app.js
var express = require('express');
var http = require('http');
var app = express();
var nodemailer = require('nodemailer');
var MemoryStore = require('connect').session.MemoryStore;
var dbPath = 'mongodb://10.168.122.123:27017/socialnet';
var fs = require('fs');
var events = require('events');
// Create an http server
app.server = http.createServer(app);
// Create an event dispatcher
var eventDispatcher = new events.EventEmitter();
app.addEventListener = function (eventName, callback) {
eventDispatcher.on(eventName, callback);
};
app.removeEventListener = function (eventName, callback) {
eventDispatcher.removeListener(eventName, callback);
};
app.triggerEvent = function (eventName, eventOptions) {
eventDispatcher.emit(eventName, eventOptions);
};
// Create a session store
app.sessionStore = new MemoryStore();
// Import the data layer
var mongoose = require('mongoose');
var config = {
mail: require('./config/mail')
};
// Import the model
var models = {
Account: require('./models/Account')(app, config, mongoose, nodemailer)
}
// Configure the application
app.configure(function(){
app.sessionSecret = 'SocialNet secret key';
app.set('view engine', 'jade');
app.use(express.static(__dirname + '/public'));
app.use(express.limit('1mb'));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
secret: app.sessionSecret,
key: 'express.sid',
store: app.sessionStore
}));
mongoose.connect(dbPath, function onMongooseError(err) {
if (err) throw err;
});
});
// Import the routes located in ./routes
fs.readdirSync('routes').forEach(function(file) {
if (file[0] == '.') return;
var routeName = file.substr(0, file.indexOf('.'));
require('./routes/' + routeName)(app, models);
});
// -----
// GET /
// -----
app.get('/', function(req, res){
res.render("index.jade", {layout: false});
});
// -------------------
// POST /contacts/find
// -------------------
app.post('/contacts/find', function(req, res) {
var searchStr = req.param('searchStr', null);
if (null == searchStr) {
res.send(400);
return;
}
models.Account.findByString(searchStr, function onSearchDone(err, accounts) {
if (err || accounts.length == 0) {
res.send(404);
} else {
// TODO: Check if these accounts were already contacts
// if so, mark them as isContact so the views/Contact
// knows not to add a addButton
res.send(accounts);
}
});
});
// Let the server listen to 8000 (instead of the app)
app.server.listen(8000);
console.log('SocialNet listening to port 8000');
Your problem:
app.use(app.router)
, mounts your routes in that position in the call chain. You have it before your session middleware, so there is no req.session yet. When you leave it out, your routes will be positioned whenever you do your first app.get (or app.post and so on). If you still wish to control where your routes should be,
you can just:
move app.use(app.router) below the session middleware.
How can I share a session with Socket.io 1.0 and Express 4.x? I use a Redis Store, but I believe it should not matter. I know I have to use a middleware to look at cookies and fetch session, but don't know how. I searched but could not find any working
var RedisStore = connectRedis(expressSession);
var session = expressSession({
store: new RedisStore({
client: redisClient
}),
secret: mysecret,
saveUninitialized: true,
resave: true
});
app.use(session);
io.use(function(socket, next) {
var handshake = socket.handshake;
if (handshake.headers.cookie) {
var str = handshake.headers.cookie;
next();
} else {
next(new Error('Missing Cookies'));
}
});
The solution is surprisingly simple. It's just not very well documented. It is possible to use the express session middleware as a Socket.IO middleware too with a small adapter like this:
sio.use(function(socket, next) {
sessionMiddleware(socket.request, socket.request.res, next);
});
Here's a full example with express 4.x, Socket.IO 1.x and Redis:
var express = require("express");
var Server = require("http").Server;
var session = require("express-session");
var RedisStore = require("connect-redis")(session);
var app = express();
var server = Server(app);
var sio = require("socket.io")(server);
var sessionMiddleware = session({
store: new RedisStore({}), // XXX redis server config
secret: "keyboard cat",
});
sio.use(function(socket, next) {
sessionMiddleware(socket.request, socket.request.res || {}, next);
});
app.use(sessionMiddleware);
app.get("/", function(req, res){
req.session // Session object in a normal request
});
sio.sockets.on("connection", function(socket) {
socket.request.session // Now it's available from Socket.IO sockets too! Win!
});
server.listen(8080);
Just a month and a half ago I dealt with the same problem and afterwards wrote an extensive blog post on this topic which goes together with a fully working demo app hosted on GitHub. The solution relies upon express-session, cookie-parser and connect-redis node modules to tie everything up. It allows you to access and modify sessions from both the REST and Sockets context which is quite useful.
The two crucial parts are middleware setup:
app.use(cookieParser(config.sessionSecret));
app.use(session({
store: redisStore,
key: config.sessionCookieKey,
secret: config.sessionSecret,
resave: true,
saveUninitialized: true
}));
...and SocketIO server setup:
ioServer.use(function (socket, next) {
var parseCookie = cookieParser(config.sessionSecret);
var handshake = socket.request;
parseCookie(handshake, null, function (err, data) {
sessionService.get(handshake, function (err, session) {
if (err)
next(new Error(err.message));
if (!session)
next(new Error("Not authorized"));
handshake.session = session;
next();
});
});
});
They go together with a simple sessionService module I made which allows you to do some basic operations with sessions and that code looks like this:
var config = require('../config');
var redisClient = null;
var redisStore = null;
var self = module.exports = {
initializeRedis: function (client, store) {
redisClient = client;
redisStore = store;
},
getSessionId: function (handshake) {
return handshake.signedCookies[config.sessionCookieKey];
},
get: function (handshake, callback) {
var sessionId = self.getSessionId(handshake);
self.getSessionBySessionID(sessionId, function (err, session) {
if (err) callback(err);
if (callback != undefined)
callback(null, session);
});
},
getSessionBySessionID: function (sessionId, callback) {
redisStore.load(sessionId, function (err, session) {
if (err) callback(err);
if (callback != undefined)
callback(null, session);
});
},
getUserName: function (handshake, callback) {
self.get(handshake, function (err, session) {
if (err) callback(err);
if (session)
callback(null, session.userName);
else
callback(null);
});
},
updateSession: function (session, callback) {
try {
session.reload(function () {
session.touch().save();
callback(null, session);
});
}
catch (err) {
callback(err);
}
},
setSessionProperty: function (session, propertyName, propertyValue, callback) {
session[propertyName] = propertyValue;
self.updateSession(session, callback);
}
};
Since there is more code to the whole thing than this (like initializing modules, working with sockets and REST calls on both the client and the server side), I won't be pasting all the code here, you can view it on the GitHub and you can do whatever you want with it.
express-socket.io-session
is a ready-made solution for your problem. Normally the session created at socket.io end has different sid than the ones created in express.js
Before knowing that fact, when I was working through it to find the solution, I found something a bit weird. The sessions created from express.js instance were accessible at the socket.io end, but the same was not possible for the opposite. And soon I came to know that I have to work my way through managing sid to resolve that problem. But, there was already a package written to tackle such issue. It's well documented and gets the job done. Hope it helps
Using Bradley Lederholz's answer, this is how I made it work for myself. Please refer to Bradley Lederholz's answer, for more explanation.
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io');
var cookieParse = require('cookie-parser')();
var passport = require('passport');
var passportInit = passport.initialize();
var passportSession = passport.session();
var session = require('express-session');
var mongoStore = require('connect-mongo')(session);
var mongoose = require('mongoose');
var sessionMiddleware = session({
secret: 'some secret',
key: 'express.sid',
resave: true,
httpOnly: true,
secure: true,
ephemeral: true,
saveUninitialized: true,
cookie: {},
store:new mongoStore({
mongooseConnection: mongoose.connection,
db: 'mydb'
});
});
app.use(sessionMiddleware);
io = io(server);
io.use(function(socket, next){
socket.client.request.originalUrl = socket.client.request.url;
cookieParse(socket.client.request, socket.client.request.res, next);
});
io.use(function(socket, next){
socket.client.request.originalUrl = socket.client.request.url;
sessionMiddleware(socket.client.request, socket.client.request.res, next);
});
io.use(function(socket, next){
passportInit(socket.client.request, socket.client.request.res, next);
});
io.use(function(socket, next){
passportSession(socket.client.request, socket.client.request.res, next);
});
io.on('connection', function(socket){
...
});
...
server.listen(8000);
Working Example for PostgreSQL & Solving the problem of getting "an object with empty session info and only cookies":
Server-Side (Node.js + PostgreSQL):
const express = require("express");
const Server = require("http").Server;
const session = require("express-session");
const pg = require('pg');
const expressSession = require('express-session');
const pgSession = require('connect-pg-simple')(expressSession);
const PORT = process.env.PORT || 5000;
const pgPool = new pg.Pool({
user : 'user',
password : 'pass',
database : 'DB',
host : '127.0.0.1',
connectionTimeoutMillis : 5000,
idleTimeoutMillis : 30000
});
const app = express();
var ioServer = require('http').createServer(app);
var io = require('socket.io')(ioServer);
var sessionMiddleware = session({
store: new RedisStore({}), // XXX redis server config
secret: "keyboard cat",
});
io.use(function(socket, next) {
session(socket.request, {}, next);
});
app.use(session);
io.on("connection", socket => {
const ioSession = socket.request.session;
socket.on('userJoined', (data) => {
console.log('---ioSession---', ioSession)
}
}
Client-Side (react-native app):
To solve the problem of getting "empty session object" you need to add withCredentials: true
this.socket = io(`http://${ip}:5000`, {
withCredentials: true,
});
I have kinda solved it, but it is not perfect. Does not support signed cookies etc. I used express-session 's getcookie function. The modified function is as follows:
io.use(function(socket, next) {
var cookie = require("cookie");
var signature = require('cookie-signature');
var debug = function() {};
var deprecate = function() {};
function getcookie(req, name, secret) {
var header = req.headers.cookie;
var raw;
var val;
// read from cookie header
if (header) {
var cookies = cookie.parse(header);
raw = cookies[name];
if (raw) {
if (raw.substr(0, 2) === 's:') {
val = signature.unsign(raw.slice(2), secret);
if (val === false) {
debug('cookie signature invalid');
val = undefined;
}
} else {
debug('cookie unsigned')
}
}
}
// back-compat read from cookieParser() signedCookies data
if (!val && req.signedCookies) {
val = req.signedCookies[name];
if (val) {
deprecate('cookie should be available in req.headers.cookie');
}
}
// back-compat read from cookieParser() cookies data
if (!val && req.cookies) {
raw = req.cookies[name];
if (raw) {
if (raw.substr(0, 2) === 's:') {
val = signature.unsign(raw.slice(2), secret);
if (val) {
deprecate('cookie should be available in req.headers.cookie');
}
if (val === false) {
debug('cookie signature invalid');
val = undefined;
}
} else {
debug('cookie unsigned')
}
}
}
return val;
}
var handshake = socket.handshake;
if (handshake.headers.cookie) {
var req = {};
req.headers = {};
req.headers.cookie = handshake.headers.cookie;
var sessionId = getcookie(req, "connect.sid", mysecret);
console.log(sessionId);
myStore.get(sessionId, function(err, sess) {
console.log(err);
console.log(sess);
if (!sess) {
next(new Error("No session"));
} else {
console.log(sess);
socket.session = sess;
next();
}
});
} else {
next(new Error("Not even a cookie found"));
}
});
// Session backend config
var RedisStore = connectRedis(expressSession);
var myStore = new RedisStore({
client: redisClient
});
var session = expressSession({
store: myStore,
secret: mysecret,
saveUninitialized: true,
resave: true
});
app.use(session);
Now, the original accepted answer doesn't work for me either. Same as #Rahil051, I used express-socket.io-session module, and it still works. This module uses cookie-parser, to parse session id before entering express-session middleware.
I think it's silmiar to #pootzko, #Mustafa and #Kosar's answer.
I'm using these modules:
"dependencies":
{
"debug": "^2.6.1",
"express": "^4.14.1",
"express-session": "^1.15.1",
"express-socket.io-session": "^1.3.2
"socket.io": "^1.7.3"
}
check out the data in socket.handshake:
const debug = require('debug')('ws');
const sharedsession = require('express-socket.io-session');
module.exports = (server, session) => {
const io = require('socket.io').listen(server);
let connections = [];
io.use(sharedsession(session, {
autoSave: true,
}));
io.use(function (socket, next) {
debug('check handshake %s', JSON.stringify(socket.handshake, null, 2));
debug('check headers %s', JSON.stringify(socket.request.headers));
debug('check socket.id %s', JSON.stringify(socket.id));
next();
});
io.sockets.on('connection', (socket) => {
connections.push(socket);
});
};
I'm currently playing around with express and socket.io and built an app that only accepts socket.io connections from users that have logged in. I put up a simple example. See the io.sockets.on('connection') part especially:
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io').listen(http);
var sessionStore = new express.session.MemoryStore();
io.set('authorization', function (handshake, accept)
{
// I got this from a gist.
// Don't know the link anymore, though.
var cookies = require('express/node_modules/cookie').parse(handshake.headers.cookie);
var parsed = require('express/node_modules/connect/lib/utils').parseSignedCookies(cookies, 'SESSION_SECRET');
sessionStore.get(parsed.sid, function (error, session)
{
if (error != null)
{
accept(error, false);
return;
}
if (session != null && session.user != null)
{
accept(null, true);
}
else
{
accept('Not a logged in user.', false);
}
});
});
io.sockets.on('connection', function (socket)
{
// client with an user object in his session (= logged in)
// connected. But how can I access this session in here?
});
app.use(express.cookieParser('COOKIE_SECRET'));
app.use(express.session({
secret: 'SESSION_SECRET',
key: 'sid',
store: sessionStore
}));
app.use(express.urlencoded());
app.use(express.json());
app.get('/', function (request, response)
{
response.sendfile('static/index.html');
});
app.post('/', function (request, response)
{
request.session.user = null;
var post = request.body;
if (post.username === 'admin' && post.password === 'admin')
{
request.session.user = post;
}
response.redirect('/');
});
http.listen(80);
Everything works to this point. Only users which have a user in their session (= they're logged in) can connect via socket.io. However, I'm currently stuck at the point when a client actually does so because I can't get a session on that point.
Any ideas?
If I've understood this question then you want express session later at some point with your socket object. You can do it like this:
if (session != null && session.user != null){
accept(null, true);
handshake.session = session;
}
And you can access this by doing this:
socket.handshake.session
Hope this will work
You can use passport.socketio.
I don't understand where is my problem.
When I put this:
io = require('socket.io').listen(server).of("/");
I my handshake looks like running fine, but all my socket.io's event (like connection) never works.
And when I when i put this
io = require('socket.io').listen(server);
I got this :
TypeError: Object # has no method 'authorization'
If I remove my handshake, all the socket.io's will works, but i need it :/
Here my app.js
const express = require('express')
, app = express()
, http = require('http')
, ejs = require('ejs')
, server = http.createServer(app)
, port = process.env.PORT || 1337
, io = require('socket.io').listen(server).of("/")
;
module.exports = { app: app, server: server };
// Grab "cookie" and "connect" from express
var connect = require('express/node_modules/connect')
var cookie = require('express/node_modules/cookie')
var connectes =[];
app.configure(function(){
this.use("/public", express.static(__dirname + '/public'));
this.use(express.cookieParser());
this.use(express.json());
this.use(express.urlencoded());
this.sessionStore = new express.session.MemoryStore({ reapInterval: 60000 * 10 });
this.use(express.session({
"secret": "some private string",
"store": this.sessionStore
}));
});
app.engine('html', ejs.renderFile);
app.set('views', __dirname + '/views');
app.get('/', [requireLogin], function(request, response) {
var pseudo = request.session.pseudo;
response.render('index.ejs.html',{connectes:connectes});
});
app.get('/login', function(request, response) {
response.render('login.ejs.html');
});
app.post("/login", function(req, res){
if (req.param("user") != "") {
req.session.pseudo = req.param("user");
//socket.set('pseudo',req.param("user"));
connectes.push(req.param("user"));
res.render('index.ejs.html',{connectes:connectes});
}else{
res.render('login.ejs.html');
}
});
const parseCookie = require('connect').utils.parseCookie;
io.authorization(function (handshakeData, callback) {
var cookies = cookie.parse(handshakeData.headers.cookie);
console.log(cookie);
});
io.on('connection', function(socket){
console.log("This never appear in log :/");
socket.on('login',function(user,callback){
var pseudoValide = true;
for (var i = 0; i < connectes.length; i++) {
if(connectes[i]==user.pseudo){
pseudoValide = false;
callback(true);
}
}
if (pseudoValide) {
socket.set('pseudo',user.pseudo);
pseudo = user.pseudo;
socket.broadcast.emit('newuser', pseudo);
socket.broadcast.emit('nvluseronline', pseudo);
connectes.push(pseudo);
callback(false,pseudo);
}
});
socket.on('message',function(message){
messageUser = message.message;
socket.get('pseudo',function(error, pseudo){
io.sockets.emit('nouveauMessage',{pseudo:pseudo,message:messageUser});
})
});
socket.on('disconnect',function(){
socket.get('pseudo',function(error, pseudo){
connectes = unset(connectes, pseudo);
io.sockets.emit('nvldisc', pseudo);
})
});
});
function unset(array, value){
var output=[];
var index = array.indexOf(value)
{
var j = 0;
for(var i in array)
{
if (i!=index)
{
output[j]=array[i];
j++;
}
}
return output;
}
}
/** Middleware */
function requireLogin (req, res, next) {
if (req.session.pseudo) {
console.log(req.session.pseudo);
next();
}else{
res.redirect("/login");
}
}
if (!module.parent) {
server.listen(port, function () {
console.log('Listening', this.address());
})
}
Like you can see i'm a beginner lost !
Thank you guys !
You should read the documentation on authorization carefully. authorization method only exists for namespaces. When doing global authorization, you have to do:
io.configure(function (){
io.set('authorization', function (handshakeData, callback) {
callback(null, true); // error first callback style
});
});
It'll work fine if you have .of("/") as server endpoint, but it is a namespace. Without namespaces you would have to use above method.