Skip to content

Commit fd0687d

Browse files
committed
add optional authorize callback and update dependencies
1 parent 5fe6597 commit fd0687d

File tree

5 files changed

+1310
-852
lines changed

5 files changed

+1310
-852
lines changed

lib/server.js

Lines changed: 41 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ function WsServer (server, opts) {
1616
opts = opts || {}
1717
this.suffix = opts.suffix || '.changes'
1818
this.store = opts.store || new InMemory(opts)
19+
this.authorize = opts.authorize // Authorization callback
1920
var toChannel = opts.toChannel || defaultToChannel
2021

2122
// Starting WSS server
@@ -26,14 +27,20 @@ function WsServer (server, opts) {
2627
})
2728

2829
// Handling a single connection
29-
wss.on('connection', function (client) {
30+
wss.on('connection', function (client, req) {
3031
debug('New connection')
31-
// var location = url.parse(client.upgradeReq.url, true)
32+
// Store the request for authorization checks
33+
client.upgradeReq = req
3234

3335
// Handling messages
3436
client.on('message', function (message) {
3537
debug('New message: ' + message)
3638

39+
// ws@8 may send Buffer, convert to string
40+
if (Buffer.isBuffer(message)) {
41+
message = message.toString()
42+
}
43+
3744
if (!message || typeof message !== 'string') {
3845
return
3946
}
@@ -47,15 +54,38 @@ function WsServer (server, opts) {
4754
return
4855
}
4956

50-
var channel = toChannel ? toChannel(iri) : iri
51-
self.store.subscribe(channel, iri, client, function (err, uuid) {
52-
if (err) {
53-
// TODO Should return an error
54-
return
55-
}
56-
57-
client.send('ack ' + tuple[1])
58-
})
57+
// Check authorization if callback is provided
58+
if (self.authorize) {
59+
self.authorize(iri, req, function (err, allowed) {
60+
if (err || !allowed) {
61+
debug('Subscription denied for ' + iri)
62+
client.send('err ' + iri + ' forbidden')
63+
return
64+
}
65+
66+
// Authorization passed, proceed with subscription
67+
var channel = toChannel ? toChannel(iri) : iri
68+
self.store.subscribe(channel, iri, client, function (err, uuid) {
69+
if (err) {
70+
client.send('err ' + iri + ' error')
71+
return
72+
}
73+
74+
client.send('ack ' + tuple[1])
75+
})
76+
})
77+
} else {
78+
// No authorization, proceed directly
79+
var channel = toChannel ? toChannel(iri) : iri
80+
self.store.subscribe(channel, iri, client, function (err, uuid) {
81+
if (err) {
82+
// TODO Should return an error
83+
return
84+
}
85+
86+
client.send('ack ' + tuple[1])
87+
})
88+
}
5989
})
6090

6191
// Respond to ping

0 commit comments

Comments
 (0)