I'm developing RESTful API on express, with JWT and passport for authorization. I want to implement socket.io connection for notification and signalling purposes (WebRTC session establishing). I don't want to implement standard session management, don't want to deal with cookies, but somehow I have to be able to address particular user via socket. I have event handling in all my routes, so app is aware of auth-ed requests and corresponding user ids. One approach(probably) is to create socket io group with user id, add socket to this group and emit there. (Engaging reconnection handling and checking socket existence on every subsequent request - that's way overcomplicated). I guess there should be a better approach. I also use Redis, so I can leverage that in this scheme. Any suggestion is appreciated, thank you
Well, I managed to solve that in such a manner.
Server:
import jwt from 'jwt-simple'; //I'm using ES6/Babel
module.exports = function(app) {
var io = app.get('io'); //Import io any possible way,
//here I do it like so because I set
//app.set('io', io) in my index.js
var user_id;
io.on('connection', socket => {
// Recieve encoded token from client, decode and find user id
// To do - check againt database
socket.on('auth', token => {
if (token) {
var decoded = jwt.decode(token, 'secret')
user_id = decoded.sub
socket.emit('auth', user_id);
}
})
// Join room proposed by client - user id string
socket.on('room', room => {
socket.join(room)
console.log('Server joined room...', room)
//emit message to user id from anywhere in the app
io.sockets.in(user_id).emit('message', 'what is going on, party people?');
})
})
}
client:
var token = localStorage.getItem('token');
var socket = io();
socket.on('connect', data => {
socket.emit('auth', token);
socket.on('auth', user_id => {
socket.emit('room', user_id);
})
})
Now to address specific user I can always emit to room id equal to user id, provided that user has got credentials. Even after browser refresh.
Photo: the left client has valid token in localStorage, the right one doesn't