summaryrefslogtreecommitdiffstats
path: root/server/lib/socketio.js
blob: 5cbedb789bd09a4281cae7f163ba6203c907140e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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')
  socket.join('broadcast ipxeBuild')

  // 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