From 82648439b945cc5d049886f7e79c2f0dd9d14ff9 Mon Sep 17 00:00:00 2001 From: Udo Walter Date: Mon, 26 Nov 2018 19:12:31 +0000 Subject: [webapp+server] Add first implementation of a websocket to alert webclients of events and to synchronize notification across multiple webapp instances of the same user --- server/lib/socketio.js | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 server/lib/socketio.js (limited to 'server/lib/socketio.js') diff --git a/server/lib/socketio.js b/server/lib/socketio.js new file mode 100644 index 0000000..37d20cd --- /dev/null +++ b/server/lib/socketio.js @@ -0,0 +1,41 @@ +var path = require('path') +var cookie = require('cookie') +var jwt = require('jsonwebtoken') +var io = require('socket.io')({ serveClient: false }); + +// ############################################################################ +// ####################### websocket middleware ############################# + +/* global __appdir */ +var auth = require(path.join(__appdir, 'lib', 'authentication')) +io.use(function (socket, next){ + socket.request.cookies = cookie.parse(socket.request.headers.cookie || '') + auth.verifyToken(socket.request, null, next); +}) + +// ############################################################################ +// ####################### websocket listeners ############################## + +io.on('connection', socket => { + console.log('Socket.io: A user connected.') + socket.on('disconnect', () => console.log('Socket.io: A user disconnected.')) + + var decodedToken = jwt.decode(socket.request.token, { complete: true }) + var userId = decodedToken.payload.user.id + + socket.join(userId) + + // Join broadcast rooms (TODO: check if user has permission to join those rooms) + socket.join('broadcast newClient') + + // Notification broadcasts + socket.on('notifications clearAll', () => socket.to(userId).emit('notifications clearAll')) + socket.on('notifications newAlert', data => socket.to(userId).emit('notifications newAlert', data)) + socket.on('notifications closeAlert', id => socket.to(userId).emit('notifications closeAlert', id)) + socket.on('notifications resetNewAlertCount', () => socket.to(userId).emit('notifications resetNewAlertCount')) +}) + +// ############################################################################ +// ############################################################################ + +module.exports = io \ No newline at end of file -- cgit v1.2.3-55-g7522