-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsubscriber.js
More file actions
70 lines (59 loc) · 1.81 KB
/
subscriber.js
File metadata and controls
70 lines (59 loc) · 1.81 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
class Subscriber {
constructor(sseClient, allTargetsAuthorized, authorizedTargets, topics, lastEventId) {
this.sseClient = sseClient;
this.allTargetsAuthorized = allTargetsAuthorized;
this.authorizedTargets = authorizedTargets;
this.topics = topics; // URI templates (RFC 6570)
this.lastEventId = lastEventId;
}
toValue() {
return {
topics: this.topics.map(t => t.toString()),
ip: this.sseClient.req.socket.localAddress,
all: this.allTargetsAuthorized,
last: this.lastEventId,
authorized: this.authorizedTargets
}
}
send(update) {
this.sseClient.send(update.event);
}
async sendAsync(update) {
this.sseClient.send(update.event);
}
closeConnection() {
// Ends the response.
this.sseClient.close();
// Manually closes the connection.
this.sseClient.res.emit('close');
}
canReceive(update) {
return this.isAuthorized(update) && this.isSubscribed(update);
}
isAuthorized(update) {
// Check if the subscriber's JWT claims a target '*' and/or wants public updates.
if (this.allTargetsAuthorized || this.authorizedTargets.length === 0) {
// Either :
// - the subscriber is authorized to receive updates destined for all targets
// - the subscriber is authorized to receive public updates
// => Allow all updates.
return true;
}
if (update.targets === null) {
// The update can be sent to all subscribers.
return true;
}
return this.authorizedTargets.some(target => update.targets.includes(target));
}
isSubscribed(update) {
for (const subscriberTopic of this.topics) {
for (const updateTopic of update.topics) {
if (subscriberTopic.test(updateTopic)) {
return true;
}
}
}
return false;
}
}
module.exports = Subscriber;