-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
42 lines (39 loc) · 1.35 KB
/
index.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
var createDoorknob = require('doorknob/server')
var authSocket = require('auth-socket')
var multilevel = require('multilevel')
var websocket = require('websocket-stream')
var url = require('url')
module.exports = function(opts) {
var server = createDoorknob(opts)
return authSocket({ httpServer: server }, function onSocket(err, req, socket, head) {
if (err && err !== 'not logged in') return console.error(err)
else if (err && err === 'not logged in') var loggedOut = true
var parsed = url.parse(req.url, true)
var id = parsed.pathname.split('/')[1]
var db = server.doorknob.db.sublevel(id)
var ws = websocket(socket)
var multiOpts = {}
if (loggedOut) multiOpts = { access: accessControl }
var multilevelServer = multilevel.server(db, multiOpts)
ws.on('end', function() {
multilevelServer.destroy()
})
ws.pipe(multilevelServer).pipe(ws)
if (opts.verbose) {
ws.on('data', function(op) {
console.log(id, 'incoming', op.trim())
})
multilevelServer.on('data', function(op) {
console.log(id, 'outgoing', op.trim())
})
}
})
function accessControl(user, db, method, args) {
if (!user || user.name !== 'root') {
//do not allow any write access
if (/^put|^del|^batch|write/i.test(method)) {
throw new Error('read-only access')
}
}
}
}