-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathchat.js
62 lines (54 loc) · 1.47 KB
/
chat.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
var Hapi = require('hapi');
var jwt = require('jsonwebtoken');
var server = Hapi.createServer('0.0.0.0', 5445);
var mqtt = require('mqtt');
var client = mqtt.createClient(1883, 'test.mosquitto.org');
var privateKey = 'VODKAPUTINBALALAIKA';
var invalidTokenMSG={
message:"Your token is invalid"
};
var requestOK={
message:"OK"
};
server.route({
method: 'POST',
path: '/connect',
handler: function (request, reply) {
client.publish('room/'+request.payload.room+'/join', request.payload.username);
reply(jwt.sign(request.payload,privateKey));
}
});
server.route({
method: 'POST',
path: '/typing',
handler: function (request, reply) {
jwt.verify(request.payload.token, privateKey, function(err, decoded) {
if(err){
reply(invalidTokenMSG);
return;
}
client.publish('room/'+decoded.room+'/typing', decoded.username);
reply(requestOK);
});
}
});
server.route({
method: 'POST',
path: '/message',
handler: function (request, reply) {
jwt.verify(request.payload.token, privateKey, function(err, decoded) {
if(err){
reply(invalidTokenMSG);
return;
}
client.publish('room/'+decoded.room+'/message', decoded.username+':'+decoded.message);
reply(requestOK);
});
}
});
if (!module.parent) {
server.start(function() {
console.log("MQTTChat started", server.info.uri);
});
}
module.exports = server