UNPKG

1.86 kBJavaScriptView Raw
1
2const Base = require("../Base")
3const d = require("debug")("raptorjs:permission")
4
5class Permission extends Base {
6
7 constructor(container, type) {
8 super(container)
9 this.type = type
10 if(!this.type) {
11 throw new Error("Permission type must be set")
12 }
13 }
14
15 getId(s) {
16 if(s instanceof String || s instanceof Number) {
17 return s
18 }
19 return s ? s.id || s.uuid : null
20 }
21
22 getUserId(s) {
23 return this.getId(s) || this.getContainer().Auth().getUser().id
24 }
25
26 get(subject, identity) {
27
28 const type = this.type
29 const sid = this.getUserId(subject)
30 const iid = this.getId(identity)
31
32 d("Get permission of %s for %s by %s", type, sid, iid)
33
34 if(!type)
35 throw new Error("permissions.get(): Missing permission type")
36
37 const url = identity ?
38 this.route("PERMISSION_BY_USER", type, sid, iid) : this.route("PERMISSION_GET", type, sid)
39
40 return this.getClient().get(url)
41 }
42
43 set(subject, permissions, identity) {
44
45 const type = this.type
46 const sid = this.getId(subject)
47 const iid = this.getUserId(identity)
48
49 d("Set permissions %j of %s for %s by %s", permissions, type, sid, iid)
50
51 if(!type)
52 throw new Error("permissions.set(): Missing permission type")
53
54 if(typeof permissions === "string")
55 permissions = [permissions]
56
57 if(!iid)
58 throw new Error("permissions.set(): Missing id field for user")
59
60 if(!(permissions instanceof Array))
61 throw new Error("permissions.set(): Permissions must be an array")
62
63 return this.getClient().put(this.route("PERMISSION_SET", type, sid), {
64 permissions: permissions,
65 user: iid
66 })
67 }
68}
69
70
71module.exports = Permission