-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbroker.js
67 lines (48 loc) · 1.74 KB
/
broker.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
var mosca = require('mosca');
// Accepts the connection if the username and password are valid
var authenticate = function(client, username, password, callback) {
var authorized = ((username === 'pub' || username =='sub') && password.toString() === 'secret');
if (authorized) client.user = username;
callback(null, authorized);
}
// In this case the client authorized as alice can publish to /users/alice taking
// the username from the topic and verifing it is the same of the authorized user
var authorizePublish = function(client, topic, payload, callback) {
callback(null, client.user == "pub");
}
// In this case the client authorized as alice can subscribe to /users/alice taking
// the username from the topic and verifing it is the same of the authorized user
var authorizeSubscribe = function(client, topic, callback) {
callback(null, client.user == "sub");
}
var SECURE_KEY = __dirname + '/certificate_authority/server_key.pem';
var SECURE_CERT = __dirname + '/certificate_authority/server.pem';
var settings = {
port: 1883,
logger: {
name: "secureExample",
level: 40,
},
secure : {
port: 8883,
keyPath: SECURE_KEY,
certPath: SECURE_CERT,
}
}
var server = new mosca.Server(settings);
server.on('clientConnected', function(client) {
console.log('client connected', client.id);
});
// fired when a message is received
server.on('published', function(packet, client) {
console.log('Published', packet.payload);
});
server.on('ready', setup);
// fired when the mqtt server is ready
function setup() {
server.authenticate = authenticate;
server.authorizePublish = authorizePublish;
server.authorizeSubscribe = authorizeSubscribe;
console.log(server);
console.log('Mosca server is up and running');
}