-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.js
89 lines (83 loc) · 3 KB
/
socket.js
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const { config } = require('./config')
const socket = require('socket.io')
const child_process = require('child_process')
const { verifyToken } = require('./auth/utils')
/**
*
* @param {object} server Http or Https server
*/
const initSocket = (server) => {
const io = socket(server, {
cors: {
origin: '*'
}
})
io.on("connection", socket => {
console.log('[socket.io] Socket connection initiated');
if (config.auth) {
console.log('[socket.io] Attemping verify the connection');
if (socket.handshake.query && socket.handshake.query.jwt) {
const isAuth = verifyToken(socket.handshake.query.jwt)
switch (isAuth.status) {
case 'authorized':
console.log('[socket.io] Connect verified');
socketOperations(socket)
break
case 'unauthorized':
socket.emit('unauthorized', isAuth.message)
setTimeout(() => socket.disconnect(), 3000);
console.log('[socket.io] Unauthorized connection to socket');
break
case 'error':
socket.emit('error', isAuth.message)
setTimeout(() => socket.disconnect(), 3000);
console.log('[socket.io] Invalid token provided by connection');
break
default:
socket.emit('unKnownError', 'It looks like you\'ve found a bug')
setTimeout(() => socket.disconnect(), 3000);
console.log('[socket.io] Verifing token error');
}
}
else {
socket.emit('no_token', 'No token provided')
setTimeout(() => socket.disconnect(), 3000);
console.log('[socket.io] No token received from connect. Socket closed');
}
}
else {
console.log('[socket.io] Authorization is not enabled');
socketOperations(socket)
}
})
}
/**
*
* @param {object} socket Socket object
*/
const socketOperations = socket => {
socket.emit('connected', 'Socket connected')
socket.emit('ON_SCAN_PAGE', 'Connection to server established.')
socket.on("scan", res => {
if (res === 'START_SCAN') {
scanner = child_process.fork('./filesystem/scanner.js')
scanner.on('message', msg => {
if (msg.status) {
socket.emit('scan_completed', msg.message)
}
else {
socket.emit('progress', msg)
}
})
}
else {
socket.emit('progress', 'Not scanning')
}
})
socket.on('disconnect', reason => {
console.log(`[socket.io] Connection to client was disconnected, reason: ${reason}`);
})
}
module.exports = {
initSocket
}