Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,25 @@ server.listen(port, function () {
// Attach WS to solid
solidWs(server, app)
```

### With authorization

You can pass an `authorize` callback to control which subscriptions are allowed:

```javascript
var SolidWs = require('solid-ws')

var solidWs = SolidWs(server, app, {
authorize: function (iri, req, callback) {
// iri: the resource URL being subscribed to
// req: the HTTP upgrade request (for auth headers/cookies)
// callback(err, allowed): call with allowed=true to permit, false to deny

checkUserAccess(iri, req, function (err, hasAccess) {
callback(err, hasAccess)
})
}
})
```

If authorization fails, the client receives `err <url> forbidden` instead of `ack`.
30 changes: 23 additions & 7 deletions lib/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,19 @@ function defaultToChannel(iri) {
return url.parse(iri).path
}

// Default authorize function allows all subscriptions
function defaultAuthorize (iri, req, callback) {
callback(null, true)
}

function WsServer (server, opts) {
var self = this

opts = opts || {}
this.suffix = opts.suffix || '.changes'
this.store = opts.store || new InMemory(opts)
var toChannel = opts.toChannel || defaultToChannel
var authorize = opts.authorize || defaultAuthorize

// Starting WSS server
var wss = new WebSocketServer({
Expand All @@ -26,9 +32,10 @@ function WsServer (server, opts) {
})

// Handling a single connection
wss.on('connection', function (client) {
// The 'ws' library passes the upgrade request as the second argument
wss.on('connection', function (client, req) {
debug('New connection')
// var location = url.parse(client.upgradeReq.url, true)
client.upgradeReq = req

// Handling messages
client.on('message', function (message) {
Expand All @@ -47,14 +54,23 @@ function WsServer (server, opts) {
return
}

var channel = toChannel ? toChannel(iri) : iri
self.store.subscribe(channel, iri, client, function (err, uuid) {
if (err) {
// TODO Should return an error
// Check authorization before allowing subscription
authorize(iri, client.upgradeReq, function (err, allowed) {
if (err || !allowed) {
debug('Subscription denied for ' + iri)
client.send('err ' + iri + ' forbidden')
return
}

client.send('ack ' + tuple[1])
var channel = toChannel ? toChannel(iri) : iri
self.store.subscribe(channel, iri, client, function (err, uuid) {
if (err) {
// TODO Should return an error
return
}

client.send('ack ' + tuple[1])
})
})
})

Expand Down