-
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathPermission.ts
79 lines (67 loc) · 2.23 KB
/
Permission.ts
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
71
72
73
74
75
76
77
78
79
import {StringKV} from './types';
export default class Permission {
private actObjData : Map<string, Array<string>>;
private objActData : Map<string, Array<string>>;
public constructor() {
this.actObjData = new Map<string, Array<string>>();
this.objActData = new Map<string, Array<string>>();
}
public load(permission : string | Record<string, unknown>) : void {
let p : StringKV;
if (typeof(permission) == 'string') {
p = JSON.parse(permission) as StringKV;
} else {
p = permission as StringKV;
}
// Generate data: {key:Actions, value: Array of objects}
for (const act in p) {
this.actObjData.set(act, p[act] as Array<string>);
}
// Generate data: {key:Objects, value: Array of actions}
const tmp : StringKV = {};
for (const act in p) {
for (const obj in p[act]) {
if (!(obj in tmp)) {
tmp[obj] = [];
}
tmp[obj].push(act);
}
}
for (const obj in tmp) {
this.objActData.set(obj, tmp[obj] as Array<string>);
}
}
public getPermissionJsonObject() : StringKV {
const obj : StringKV = {};
this.actObjData.forEach((value, key) => (obj[key] = value));
return obj;
}
/*
Parse the permission into JSON string
*/
public getPermissionString() : string {
return JSON.stringify(this.getPermissionJsonObject());
}
public getTargetsFromAction(action: string) : Array<string> {
const result = this.actObjData.get(action);
if (result === undefined) {
return new Array<string>();
} else {
return result;
}
}
public getActionsObjects() : Map<string, Array<string>> {
return this.actObjData;
}
public getObjectsActions() : Map<string, Array<string>> {
return this.objActData;
}
public check(action : string, object : string) : boolean {
const objects = this.actObjData.get(action);
if (objects == undefined) {
return false;
} else {
return objects.includes(object);
}
}
}