-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathserve-handshake-auth.js
More file actions
61 lines (56 loc) · 1.96 KB
/
Copy pathserve-handshake-auth.js
File metadata and controls
61 lines (56 loc) · 1.96 KB
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
/**
* This file is part of the Elephant.io package
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*
* @copyright ElephantIO
* @copyright Wisembly
* @license http://www.opensource.org/licenses/MIT-License MIT License
*/
const ExampleServer = require('./serve');
/**
* An example of authorization using handshake server.
*/
class HandshakeAuthServer extends ExampleServer {
initialize() {
this.namespace = 'handshake-auth';
}
handle() {
if (typeof this.nsp.use === 'function') {
this.nsp.use((socket, next) => {
if (socket.handshake && socket.handshake.auth) {
const user = socket.handshake.auth.user;
const token = socket.handshake.auth.token;
if (user && token) {
this.log('auth token', token);
// do some security check with token
// for example:
if (user === 'random@example.com' && token === 'my-secret-token') {
this.log('successfully authenticated');
next();
} else {
next(new Error('invalid credentials'));
}
} else {
next(new Error('missing auth from the handshake'));
}
} else {
next();
}
});
}
this.nsp.on('connection', socket => {
this.log('connected: %s', socket.id);
socket
.on('disconnect', () => {
this.log('disconnected: %s', socket.id);
})
.on('echo', message => {
socket.emit('echo', message);
});
});
return true;
}
}
module.exports = HandshakeAuthServer;