Making a Socket io singleton class to be used in any file #4173
-
|
I need access to the When I comment out all the middleware, it works. But I don't want that, I want the connection to be only made when the user is logged in. The here's my const session = require('express-session');
const { Server } = require("socket.io");
const passport = require('passport');
class SocketManager{
constructor() {
this.io = null;
}
start(server) {
this.io = new Server(server);
// convert a connect middleware to a Socket.IO middleware
const wrap = middleware => (socket, next) => middleware(socket.request, {}, next);
const sessionMiddleware = session({
secret: 'MySecrectKey',
resave: true,
saveUninitialized: true
});
this.io.use(wrap(sessionMiddleware));
this.io.use(wrap(passport.initialize()));
this.io.use(wrap(passport.session()));
this.io.use((socket, next) => {
if (socket.request.user) {
next();
} else {
next(new Error('unauthorized'))
}
});
}
get() {
return this.io;
}
}
module.exports = new SocketManager();Here's my ...
const SocketManager = require('./socketClass');
const server = http.createServer(app);
SocketManager.start(server);
const io = SocketManager.get();
io.on('connect', async (socket) => {
console.log(`new connection ${socket.id}`);
socket.on('whoami', (cb) => {
cb(socket.request.user ? socket.request.user.username : '');
});
}); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
The You will find a complete example with Passport here: https://github.com/socketio/socket.io/tree/master/examples/passport-example |
Beta Was this translation helpful? Give feedback.
The
connectevent is not emitted, because the connection is denied withnext(new Error('unauthorized')). Thesocket.request.sessionis defined, but passport is not able to fetch the user from it. I think you are missing an authentication strategy, like http://www.passportjs.org/docs/username-password/.You will find a complete example with Passport here: https://github.com/socketio/socket.io/tree/master/examples/passport-example