-
-
Notifications
You must be signed in to change notification settings - Fork 215
/
defaultRoleManager.ts
355 lines (307 loc) · 10.3 KB
/
defaultRoleManager.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
// Copyright 2018 The Casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { RoleManager } from './roleManager';
import { getLogger, logPrint } from '../log';
export type MatchingFunc = (arg1: string, arg2: string) => boolean;
// DEFAULT_DOMAIN defines the default domain space.
const DEFAULT_DOMAIN = 'casbin::default';
// loadOrDefault returns the existing value for the key if present.
// Otherwise, it stores and returns the given value.
function loadOrDefault<K, V>(map: Map<K, V>, key: K, value: V): V {
const read = map.get(key);
if (read === undefined) {
map.set(key, value);
return value;
}
return read;
}
/**
* Role represents the data structure for a role in RBAC.
*/
class Role {
public name: string;
private roles: Role[];
constructor(name: string) {
this.name = name;
this.roles = [];
}
public addRole(role: Role): void {
if (this.roles.some((n) => n.name === role.name)) {
return;
}
this.roles.push(role);
}
public deleteRole(role: Role): void {
this.roles = this.roles.filter((n) => n.name !== role.name);
}
public hasRole(name: string, hierarchyLevel: number): boolean {
if (this.name === name) {
return true;
}
if (hierarchyLevel <= 0) {
return false;
}
for (const role of this.roles) {
if (role.hasRole(name, hierarchyLevel - 1)) {
return true;
}
}
return false;
}
public hasDirectRole(name: string): boolean {
return this.roles.some((n) => n.name === name);
}
public toString(): string {
return this.name + this.roles.join(', ');
}
public getRoles(): string[] {
return this.roles.map((n) => n.name);
}
}
class Roles extends Map<string, Role> {
constructor() {
super();
}
public hasRole(name: string, matchingFunc?: MatchingFunc): boolean {
let ok = false;
if (matchingFunc) {
this.forEach((value, key) => {
if (matchingFunc(name, key)) {
ok = true;
}
});
} else {
return this.has(name);
}
return ok;
}
public createRole(name: string, matchingFunc?: MatchingFunc): Role {
const role = loadOrDefault(this, name, new Role(name));
if (matchingFunc) {
this.forEach((value, key) => {
if (matchingFunc(name, key) && name !== key) {
// Add new role to matching role
const role1 = loadOrDefault(this, key, new Role(key));
role.addRole(role1);
}
});
}
return role;
}
}
// RoleManager provides a default implementation for the RoleManager interface
export class DefaultRoleManager implements RoleManager {
private allDomains: Map<string, Roles>;
private maxHierarchyLevel: number;
private hasPattern = false;
private hasDomainPattern = false;
private hasDomainHierarchy = false;
private domainHierarchyManager: RoleManager;
private matchingFunc: MatchingFunc;
private domainMatchingFunc: MatchingFunc;
/**
* DefaultRoleManager is the constructor for creating an instance of the
* default RoleManager implementation.
*
* @param maxHierarchyLevel the maximized allowed RBAC hierarchy level.
*/
constructor(maxHierarchyLevel: number) {
this.allDomains = new Map<string, Roles>();
this.allDomains.set(DEFAULT_DOMAIN, new Roles());
this.maxHierarchyLevel = maxHierarchyLevel;
}
/**
* addMatchingFunc support use pattern in g
* @param name name
* @param fn matching function
* @deprecated
*/
public async addMatchingFunc(name: string, fn: MatchingFunc): Promise<void>;
/**
* addMatchingFunc support use pattern in g
* @param fn matching function
*/
public async addMatchingFunc(fn: MatchingFunc): Promise<void>;
/**
* addMatchingFunc support use pattern in g
* @param name name
* @param fn matching function
* @deprecated
*/
public async addMatchingFunc(name: string | MatchingFunc, fn?: MatchingFunc): Promise<void> {
this.hasPattern = true;
if (typeof name === 'string' && fn) {
this.matchingFunc = fn;
} else if (typeof name === 'function') {
this.matchingFunc = name;
} else {
throw new Error('error: domain should be 1 parameter');
}
}
/**
* addDomainMatchingFunc support use domain pattern in g
* @param fn domain matching function
* ```
*/
public async addDomainMatchingFunc(fn: MatchingFunc): Promise<void> {
this.hasDomainPattern = true;
this.domainMatchingFunc = fn;
}
/**
* addDomainHierarchy sets a rolemanager to define role inheritance between domains
* @param rm RoleManager to define domain hierarchy
*/
public async addDomainHierarchy(rm: RoleManager): Promise<void> {
if (!rm?.syncedHasLink) throw Error('Domain hierarchy must be syncronous.');
this.hasDomainHierarchy = true;
this.domainHierarchyManager = rm;
}
private generateTempRoles(domain: string): Roles {
if (!this.hasPattern && !this.hasDomainPattern && !this.hasDomainHierarchy) {
return loadOrDefault(this.allDomains, domain, new Roles());
}
const extraDomain = new Set([domain]);
if (this.hasDomainPattern || this.hasDomainHierarchy) {
this.allDomains.forEach((value, key) => {
if (
(this.hasDomainPattern && this.domainMatchingFunc(domain, key)) ||
(this.domainHierarchyManager?.syncedHasLink && this.domainHierarchyManager.syncedHasLink(key, domain))
) {
extraDomain.add(key);
}
});
}
const allRoles = new Roles();
extraDomain.forEach((dom) => {
loadOrDefault(this.allDomains, dom, new Roles()).forEach((value, key) => {
const role1 = allRoles.createRole(value.name, this.matchingFunc);
value.getRoles().forEach((n) => {
role1.addRole(allRoles.createRole(n, this.matchingFunc));
});
});
});
return allRoles;
}
/**
* addLink adds the inheritance link between role: name1 and role: name2.
* aka role: name1 inherits role: name2.
* domain is a prefix to the roles.
*/
public async addLink(name1: string, name2: string, ...domain: string[]): Promise<void> {
if (domain.length === 0) {
domain = [DEFAULT_DOMAIN];
} else if (domain.length > 1) {
throw new Error('error: domain should be 1 parameter');
}
const allRoles = loadOrDefault(this.allDomains, domain[0], new Roles());
const role1 = loadOrDefault(allRoles, name1, new Role(name1));
const role2 = loadOrDefault(allRoles, name2, new Role(name2));
role1.addRole(role2);
}
/**
* clear clears all stored data and resets the role manager to the initial state.
*/
public async clear(): Promise<void> {
this.allDomains = new Map();
this.allDomains.set(DEFAULT_DOMAIN, new Roles());
}
/**
* deleteLink deletes the inheritance link between role: name1 and role: name2.
* aka role: name1 does not inherit role: name2 any more.
* domain is a prefix to the roles.
*/
public async deleteLink(name1: string, name2: string, ...domain: string[]): Promise<void> {
if (domain.length === 0) {
domain = [DEFAULT_DOMAIN];
} else if (domain.length > 1) {
throw new Error('error: domain should be 1 parameter');
}
const allRoles = loadOrDefault(this.allDomains, domain[0], new Roles());
if (!allRoles.has(name1) || !allRoles.has(name2)) {
return;
}
const role1 = loadOrDefault(allRoles, name1, new Role(name1));
const role2 = loadOrDefault(allRoles, name2, new Role(name2));
role1.deleteRole(role2);
}
/**
* hasLink determines whether role: name1 inherits role: name2.
* domain is a prefix to the roles.
*/
public syncedHasLink(name1: string, name2: string, ...domain: string[]): boolean {
if (domain.length === 0) {
domain = [DEFAULT_DOMAIN];
} else if (domain.length > 1) {
throw new Error('error: domain should be 1 parameter');
}
if (name1 === name2) {
return true;
}
const allRoles = this.generateTempRoles(domain[0]);
if (!allRoles.hasRole(name1, this.matchingFunc) || !allRoles.hasRole(name2, this.matchingFunc)) {
return false;
}
const role1 = allRoles.createRole(name1, this.matchingFunc);
return role1.hasRole(name2, this.maxHierarchyLevel);
}
public async hasLink(name1: string, name2: string, ...domain: string[]): Promise<boolean> {
return new Promise((resolve) => resolve(this.syncedHasLink(name1, name2, ...domain)));
}
/**
* getRoles gets the roles that a subject inherits.
* domain is a prefix to the roles.
*/
public async getRoles(name: string, ...domain: string[]): Promise<string[]> {
if (domain.length === 0) {
domain = [DEFAULT_DOMAIN];
} else if (domain.length > 1) {
throw new Error('error: domain should be 1 parameter');
}
const allRoles = this.generateTempRoles(domain[0]);
if (!allRoles.hasRole(name, this.matchingFunc)) {
return [];
}
return allRoles.createRole(name, this.matchingFunc).getRoles();
}
/**
* getUsers gets the users that inherits a subject.
* domain is an unreferenced parameter here, may be used in other implementations.
*/
public async getUsers(name: string, ...domain: string[]): Promise<string[]> {
if (domain.length === 0) {
domain = [DEFAULT_DOMAIN];
} else if (domain.length > 1) {
throw new Error('error: domain should be 1 parameter');
}
const allRoles = this.generateTempRoles(domain[0]);
if (!allRoles.hasRole(name, this.matchingFunc)) {
return [];
}
const users = [];
for (const user of allRoles.values()) {
if (user.hasDirectRole(name)) users.push(user.name);
}
return users;
}
/**
* printRoles prints all the roles to log.
*/
public async printRoles(): Promise<void> {
if (getLogger().isEnable()) {
[...this.allDomains.values()].forEach((n) => {
logPrint(n.toString());
});
}
}
}