permissions.model.ts
2.36 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
/**
* Created by tuukka on 22/09/18.
*/
class PermissionFields {
USER = false;
INFO = false;
ADMIN = false;
}
export class Permissions {
static referencePermission = new Permissions();
VIPLIST: PermissionFields = new PermissionFields();
BILLING: PermissionFields = new PermissionFields();
SITE: PermissionFields = new PermissionFields();
SHOP: PermissionFields = new PermissionFields();
POLL: PermissionFields = new PermissionFields();
INVITE: PermissionFields = new PermissionFields();
MAP: PermissionFields = new PermissionFields();
COMPO: PermissionFields = new PermissionFields();
FOOD: PermissionFields = new PermissionFields();
USER: PermissionFields = new PermissionFields();
TOURNAMENT: PermissionFields = new PermissionFields();
CREDIT: PermissionFields = new PermissionFields();
LECTURE: PermissionFields = new PermissionFields();
constructor() {
}
/**
*
* Returns function, which will check user permissions against desired roles.
*
* Returned function can be used as a permission checked.
*
*
* @param requiredPermissions Permissions which are allowed. Example: {VIPLIST: 'ADMIN', BILLING: 'INFO'}
* @constructor
*/
static GeneratePermissionFunction(allowedPermissions: any): ((permissions: Permissions) => boolean) {
// no defines, always true
if (!allowedPermissions) {
return function (permissions: Permissions): boolean {
return true;
};
}
// Check if all permissions exists
// Think this as a runtime typecheck
for (const target in allowedPermissions) {
if (!allowedPermissions.hasOwnProperty(target)) {
continue;
}
if (!(target in Permissions.referencePermission)) {
throw Error('Invalid permission key ' + target);
}
switch (allowedPermissions[target]) {
default:
throw Error('Invalid permission role ' + allowedPermissions[target]);
case 'ADMIN':
case 'INFO':
case 'USER':
}
}
return function (permissions: Permissions): boolean {
// Go trought allowed permissions. If permissions contains allowed permission, return true.
for (const target in allowedPermissions) {
if (permissions[target][allowedPermissions[target]]) {
return true;
}
}
// no permission found, return false
return false;
};
}
}