-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathindex.js
More file actions
83 lines (64 loc) · 2.05 KB
/
index.js
File metadata and controls
83 lines (64 loc) · 2.05 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
var fs = require('fs');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const port = process.env.PORT || 3000;
const notificationSecret = process.env.NOTIFICATION_SECRET || 'NOTIFICATION_SECRET';
const notificationKey = process.env.NOTIFICATION_KEY || 'NOTIFICATION_KEY'
const EVENTS = {
newNotification: 'NEW_NOTIFICATION'
};
var server;
if(process.env.SSL_KEY && process.env.SSL_CERT) {
var options = {
key: fs.readFileSync(process.env.SSL_KEY),
cert: fs.readFileSync(process.env.SSL_CERT)
};
server = require('https').createServer(options, app);
} else {
server = require('http').createServer(app);
}
const io = require('socket.io')(server);
server.listen(port, () => console.log('Server listening at port %d', port));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(__dirname + '/public'));
app.post('/send', (req, res) => {
const data = req.body;
const dispath = (channel, notification) => {
io.to(channel).emit(EVENTS.newNotification, data.notification);
};
if (!req.headers || req.headers.notification_secret !== notificationSecret) {
return res.status(401).json('invalid notification secret');
}
if (data && data.notification && data.channel) {
if (data.channel.forEach) {
data.channel.forEach(function (channel) {
dispath(channel, data.notification);
});
} else {
dispath(data.channel, data.notification);
}
return res.status(200).json('ok');
}
return res.status(406).json('Missing parameters');
});
io.on('connection', (socket) => {
if(!validateConnection(socket.handshake.query)) {
return;
}
socket.on('join', (channel) => {
socket.join(channel);
});
socket.on('leave', (channel) => {
socket.leave(channel);
});
});
function validateConnection(query) {
if (query.notificationKey !== notificationKey) {
return;
}
return true;
}