forked from onury/accesscontrol
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAccessControl.ts
781 lines (740 loc) · 27.8 KB
/
AccessControl.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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
import { Access, IAccessInfo, Query, IQueryInfo, Permission, AccessControlError } from './core';
import { Action, Possession, actions, possessions } from './enums';
import { utils, ERR_LOCK } from './utils';
/**
* @classdesc
* AccessControl class that implements RBAC (Role-Based Access Control) basics
* and ABAC (Attribute-Based Access Control) <i>resource</i> and <i>action</i>
* attributes.
*
* Construct an `AccessControl` instance by either passing a grants object (or
* array fetched from database) or simple omit `grants` parameter if you are
* willing to build it programmatically.
*
* <p><pre><code> const grants = {
* role1: {
* resource1: {
* "create:any": [ attrs ],
* "read:own": [ attrs ]
* },
* resource2: {
* "create:any": [ attrs ],
* "update:own": [ attrs ]
* }
* },
* role2: { ... }
* };
* const ac = new AccessControl(grants);</code></pre></p>
*
* The `grants` object can also be an array, such as a flat list
* fetched from a database.
*
* <p><pre><code> const flatList = [
* { role: 'role1', resource: 'resource1', action: 'create:any', attributes: [ attrs ] },
* { role: 'role1', resource: 'resource1', action: 'read:own', attributes: [ attrs ] },
* { role: 'role2', ... },
* ...
* ];</code></pre></p>
*
* We turn this list into a hashtable for better performance. We aggregate
* the list by roles first, resources second. If possession (in action
* value or as a separate property) is omitted, it will default to `"any"`.
* e.g. `"create"` —» `"create:any"`
*
* Below are equivalent:
* <p><pre><code> const grants = { role: 'role1', resource: 'resource1', action: 'create:any', attributes: [ attrs ] }
* const same = { role: 'role1', resource: 'resource1', action: 'create', possession: 'any', attributes: [ attrs ] }</code></pre></p>
*
* So we can also initialize with this flat list of grants:
* <p><pre><code> const ac = new AccessControl(flatList);
* console.log(ac.getGrants());</code></pre></p>
*
* @author Onur Yıldırım <[email protected]>
* @license MIT
*
* @class
* @global
*
* @example
* const ac = new AccessControl(grants);
*
* ac.grant('admin').createAny('profile');
*
* // or you can chain methods
* ac.grant('admin')
* .createAny('profile')
* .readAny('profile', ["*", "!password"])
* .readAny('video')
* .deleteAny('video');
*
* // since these permissions have common resources, there is an alternative way:
* ac.grant('admin')
* .resource('profile').createAny().readAny(null, ["*", "!password"])
* .resource('video').readAny()..deleteAny();
*
* ac.grant('user')
* .readOwn('profile', ["uid", "email", "address.*", "account.*", "!account.roles"])
* .updateOwn('profile', ["uid", "email", "password", "address.*", "!account.roles"])
* .deleteOwn('profile')
* .createOwn('video', ["*", "!geo.*"])
* .readAny('video')
* .updateOwn('video', ["*", "!geo.*"])
* .deleteOwn('video');
*
* // now we can check for granted or denied permissions
* const permission = ac.can('admin').readAny('profile');
* permission.granted // true
* permission.attributes // ["*", "!password"]
* permission.filter(data) // { uid, email, address, account }
* // deny permission
* ac.deny('admin').createAny('profile');
* ac.can('admin').createAny('profile').granted; // false
*
* // To add a grant but deny access via attributes
* ac.grant('admin').createAny('profile', []); // no attributes allowed
* ac.can('admin').createAny('profile').granted; // false
*
* // To prevent any more changes:
* ac.lock();
*/
class AccessControl {
/**
* @private
*/
private _grants: any;
/**
* @private
*/
private _isLocked: boolean = false;
/**
* Initializes a new instance of `AccessControl` with the given grants.
* @ignore
*
* @param {Object|Array} [grants] - A list containing the access grant
* definitions. See the structure of this object in the examples.
*/
constructor(grants?: any) {
// explicit undefined is not allowed
if (arguments.length === 0) grants = {};
this.setGrants(grants);
}
// -------------------------------
// PUBLIC PROPERTIES
// -------------------------------
/**
* Specifies whether the underlying grants object is frozen and all
* functionality for modifying it is disabled.
* @name AccessControl#isLocked
* @type {Boolean}
*/
get isLocked(): boolean {
return this._isLocked && Object.isFrozen(this._grants);
}
// -------------------------------
// PUBLIC METHODS
// -------------------------------
/**
* Gets the internal grants object that stores all current grants.
*
* @return {Object} - Hash-map of grants.
*
* @example
* ac.grant('admin')
* .createAny(['profile', 'video'])
* .deleteAny(['profile', 'video'])
* .readAny(['video'])
* .readAny('profile', ['*', '!password'])
* .grant('user')
* .readAny(['profile', 'video'], ['*', '!id', '!password'])
* .createOwn(['profile', 'video'])
* .deleteOwn(['video']);
* // logging underlying grants model
* console.log(ac.getGrants());
* // outputs:
* {
* "admin": {
* "profile": {
* "create:any": ["*"],
* "delete:any": ["*"],
* "read:any": ["*", "!password"]
* },
* "video": {
* "create:any": ["*"],
* "delete:any": ["*"],
* "read:any": ["*"]
* }
* },
* "user": {
* "profile": {
* "read:any": ["*", "!id", "!password"],
* "create:own": ["*"]
* },
* "video": {
* "read:any": ["*", "!id", "!password"],
* "create:own": ["*"],
* "delete:own": ["*"]
* }
* }
* }
*/
getGrants(): any {
return this._grants;
}
/**
* Sets all access grants at once, from an object or array. Note that this
* will reset the object and remove all previous grants.
* @chainable
*
* @param {Object|Array} grantsObject - A list containing the access grant
* definitions.
*
* @returns {AccessControl} - `AccessControl` instance for chaining.
*
* @throws {AccessControlError} - If called after `.lock()` is called or if
* passed grants object fails inspection.
*/
setGrants(grantsObject: any): AccessControl {
if (this.isLocked) throw new AccessControlError(ERR_LOCK);
this._grants = utils.getInspectedGrants(grantsObject);
return this;
}
/**
* Resets the internal grants object and removes all previous grants.
* @chainable
*
* @returns {AccessControl} - `AccessControl` instance for chaining.
*
* @throws {AccessControlError} - If called after `.lock()` is called.
*/
reset(): AccessControl {
if (this.isLocked) throw new AccessControlError(ERR_LOCK);
this._grants = {};
return this;
}
/**
* Freezes the underlying grants model and disables all functionality for
* modifying it. This is useful when you want to restrict any changes. Any
* attempts to modify (such as `#setGrants()`, `#reset()`, `#grant()`,
* `#deny()`, etc) will throw after grants are locked. Note that <b>there
* is no `unlock()` method</b>. It's like you lock the door and swallow the
* key. ;)
*
* Remember that this does not prevent the `AccessControl` instance from
* being altered/replaced. Only the grants inner object is locked.
*
* <b>A note about performance</b>: This uses recursive `Object.freeze()`.
* In NodeJS & V8, enumeration performance is not impacted because of this.
* In fact, it increases the performance because of V8 optimization.
* @chainable
*
* @returns {AccessControl} - `AccessControl` instance for chaining.
*
* @example
* ac.grant('admin').create('product');
* ac.lock(); // called on the AccessControl instance.
* // or
* ac.grant('admin').create('product').lock(); // called on the chained Access instance.
*
* // After this point, any attempt of modification will throw
* ac.setGrants({}); // throws
* ac.grant('user'); // throws..
* // underlying grants model is not changed
*/
lock(): AccessControl {
utils.lockAC(this);
return this;
}
/**
* Extends the given role(s) with privileges of one or more other roles.
* @chainable
*
* @param {string|Array<String>} roles Role(s) to be extended. Single role
* as a `String` or multiple roles as an `Array`. Note that if a
* role does not exist, it will be automatically created.
*
* @param {string|Array<String>} extenderRoles Role(s) to inherit from.
* Single role as a `String` or multiple roles as an `Array`. Note
* that if a extender role does not exist, it will throw.
*
* @returns {AccessControl} - `AccessControl` instance for chaining.
*
* @throws {AccessControlError} - If a role is extended by itself or a
* non-existent role. Or if called after `.lock()` is called.
*/
extendRole(roles: string | string[], extenderRoles: string | string[]): AccessControl {
if (this.isLocked) throw new AccessControlError(ERR_LOCK);
utils.extendRole(this._grants, roles, extenderRoles);
return this;
}
/**
* Removes all the given role(s) and their granted permissions, at once.
* @chainable
*
* @param {string|Array<String>} roles - An array of roles to be removed.
* Also accepts a string that can be used to remove a single role.
*
* @returns {AccessControl} - `AccessControl` instance for chaining.
*
* @throws {AccessControlError} - If called after `.lock()` is called.
*/
removeRoles(roles: string | string[]): AccessControl {
if (this.isLocked) throw new AccessControlError(ERR_LOCK);
let rolesToRemove: string[] = utils.toStringArray(roles);
if (rolesToRemove.length === 0 || !utils.isFilledStringArray(rolesToRemove)) {
throw new AccessControlError(`Invalid role(s): ${JSON.stringify(roles)}`);
}
rolesToRemove.forEach((roleName: string) => {
if (!this._grants[roleName]) {
throw new AccessControlError(`Cannot remove a non-existing role: "${roleName}"`);
}
delete this._grants[roleName];
});
// also remove these roles from $extend list of each remaining role.
utils.eachRole(this._grants, (roleItem: any, roleName: string) => {
if (Array.isArray(roleItem.$extend)) {
roleItem.$extend = utils.subtractArray(roleItem.$extend, rolesToRemove);
}
});
return this;
}
/**
* Removes all the given resources for all roles, at once.
* Pass the `roles` argument to remove access to resources for those
* roles only.
* @chainable
*
* @param {string|Array<String>} resources - A single or array of resources to
* be removed.
* @param {string|Array<String>} [roles] - A single or array of roles to
* be removed. If omitted, permissions for all roles to all given
* resources will be removed.
*
* @returns {AccessControl} - `AccessControl` instance for chaining.
*
* @throws {AccessControlError} - If called after `.lock()` is called.
*/
removeResources(resources: string | string[], roles?: string | string[]): AccessControl {
if (this.isLocked) throw new AccessControlError(ERR_LOCK);
// _removePermission has a third argument `actionPossession`. if
// omitted (like below), removes the parent resource object.
this._removePermission(resources, roles);
return this;
}
/**
* Gets all the unique roles that have at least one access information.
*
* @returns {Array<String>}
*
* @example
* ac.grant('admin, user').createAny('video').grant('user').readOwn('profile');
* console.log(ac.getRoles()); // ["admin", "user"]
*/
getRoles(): string[] {
return Object.keys(this._grants);
}
/**
* Gets the list of inherited roles by the given role.
* @name AccessControl#getInheritedRolesOf
* @alias AccessControl#getExtendedRolesOf
* @function
*
* @param {string} role - Target role name.
*
* @returns {Array<String>}
*/
getInheritedRolesOf(role: string): string[] {
let roles: string[] = utils.getRoleHierarchyOf(this._grants, role);
roles.shift();
return roles;
}
/**
* Alias of `getInheritedRolesOf`
* @private
*/
getExtendedRolesOf(role: string): string[] {
return this.getInheritedRolesOf(role);
}
/**
* Gets all the unique resources that are granted access for at
* least one role.
*
* @returns {Array<String>}
*/
getResources(): string[] {
return utils.getResources(this._grants);
}
/**
* Checks whether the grants include the given role or roles.
*
* @param {string|string[]} role - Role to be checked. You can also pass an
* array of strings to check multiple roles at once.
*
* @returns {Boolean}
*/
hasRole(role: string | string[]): boolean {
if (Array.isArray(role)) {
return role.every((item: string) => this._grants.hasOwnProperty(item));
}
return this._grants.hasOwnProperty(role);
}
/**
* Checks whether grants include the given resource or resources.
*
* @param {string|string[]} resource - Resource to be checked. You can also pass an
* array of strings to check multiple resources at once.
*
* @returns {Boolean}
*/
hasResource(resource: string | string[]): boolean {
let resources = this.getResources();
if (Array.isArray(resource)) {
return resource.every((item: string) => resources.indexOf(item) >= 0);
}
if (typeof resource !== 'string' || resource === '') return false;
return resources.indexOf(resource) >= 0;
}
/**
* Gets an instance of `Query` object. This is used to check whether the
* defined access is allowed for the given role(s) and resource. This
* object provides chainable methods to define and query the access
* permissions to be checked.
* @name AccessControl#can
* @alias AccessControl#query
* @function
* @chainable
*
* @param {string|Array|IQueryInfo} role - A single role (as a string), a
* list of roles (as an array) or an
* {@link ?api=ac#AccessControl~IQueryInfo|`IQueryInfo` object} that fully
* or partially defines the access to be checked.
*
* @returns {Query} - The returned object provides chainable methods to
* define and query the access permissions to be checked. See
* {@link ?api=ac#AccessControl~Query|`Query` inner class}.
*
* @example
* const ac = new AccessControl(grants);
*
* ac.can('admin').createAny('profile');
* // equivalent to:
* ac.can().role('admin').createAny('profile');
* // equivalent to:
* ac.can().role('admin').resource('profile').createAny();
*
* // To check for multiple roles:
* ac.can(['admin', 'user']).createOwn('profile');
* // Note: when multiple roles checked, acquired attributes are unioned (merged).
*/
can(role: string | string[] | IQueryInfo): Query {
// throw on explicit undefined
if (arguments.length !== 0 && role === undefined) {
throw new AccessControlError('Invalid role(s): undefined');
}
// other explicit invalid values will be checked in constructor.
return new Query(this._grants, role);
}
/**
* Alias of `can()`.
* @private
*/
query(role: string | string[] | IQueryInfo): Query {
return this.can(role);
}
/**
* Gets an instance of `Permission` object that checks and defines the
* granted access permissions for the target resource and role. Normally
* you would use `AccessControl#can()` method to check for permissions but
* this is useful if you need to check at once by passing a `IQueryInfo`
* object; instead of chaining methods (as in
* `.can(<role>).<action>(<resource>)`).
*
* @param {IQueryInfo} queryInfo - A fulfilled
* {@link ?api=ac#AccessControl~IQueryInfo|`IQueryInfo` object}.
*
* @returns {Permission} - An object that provides properties and methods
* that defines the granted access permissions. See
* {@link ?api=ac#AccessControl~Permission|`Permission` inner class}.
*
* @example
* const ac = new AccessControl(grants);
* const permission = ac.permission({
* role: "user",
* action: "update:own",
* resource: "profile"
* });
* permission.granted; // Boolean
* permission.attributes; // Array e.g. [ 'username', 'password', 'company.*']
* permission.filter(object); // { username, password, company: { name, address, ... } }
*/
permission(queryInfo: IQueryInfo): Permission {
return new Permission(this._grants, queryInfo);
}
/**
* Gets an instance of `Grant` (inner) object. This is used to grant access
* to specified resource(s) for the given role(s).
* @name AccessControl#grant
* @alias AccessControl#allow
* @function
* @chainable
*
* @param {string|Array<String>|IAccessInfo} [role] A single role (as a
* string), a list of roles (as an array) or an
* {@link ?api=ac#AccessControl~IAccessInfo|`IAccessInfo` object} that
* fully or partially defines the access to be granted. This can be omitted
* and chained with `.role()` to define the role.
*
* @return {Access} - The returned object provides chainable properties to
* build and define the access to be granted. See the examples for details.
* See {@link ?api=ac#AccessControl~Access|`Access` inner class}.
*
* @throws {AccessControlError} - If `role` is explicitly set to an invalid value.
* @throws {AccessControlError} - If called after `.lock()` is called.
*
* @example
* const ac = new AccessControl();
* let attributes = ['*'];
*
* ac.grant('admin').createAny('profile', attributes);
* // equivalent to:
* ac.grant().role('admin').createAny('profile', attributes);
* // equivalent to:
* ac.grant().role('admin').resource('profile').createAny(null, attributes);
* // equivalent to:
* ac.grant({
* role: 'admin',
* resource: 'profile',
* }).createAny(null, attributes);
* // equivalent to:
* ac.grant({
* role: 'admin',
* resource: 'profile',
* action: 'create:any',
* attributes: attributes
* });
* // equivalent to:
* ac.grant({
* role: 'admin',
* resource: 'profile',
* action: 'create',
* possession: 'any', // omitting this will default to 'any'
* attributes: attributes
* });
*
* // To grant same resource and attributes for multiple roles:
* ac.grant(['admin', 'user']).createOwn('profile', attributes);
*
* // Note: when attributes is omitted, it will default to `['*']`
* // which means all attributes (of the resource) are allowed.
*/
grant(role?: string | string[] | IAccessInfo): Access {
if (this.isLocked) throw new AccessControlError(ERR_LOCK);
// throw on explicit undefined
if (arguments.length !== 0 && role === undefined) {
throw new AccessControlError('Invalid role(s): undefined');
}
// other explicit invalid values will be checked in constructor.
return new Access(this, role, false);
}
/**
* Alias of `grant()`.
* @private
*/
allow(role?: string | string[] | IAccessInfo): Access {
return this.grant(role);
}
/**
* Gets an instance of `Access` object. This is used to deny access to
* specified resource(s) for the given role(s). Denying will only remove a
* previously created grant. So if not granted before, you don't need to
* deny an access.
* @name AccessControl#deny
* @alias AccessControl#reject
* @function
* @chainable
*
* @param {string|Array<String>|IAccessInfo} role A single role (as a
* string), a list of roles (as an array) or an
* {@link ?api=ac#AccessControl~IAccessInfo|`IAccessInfo` object} that
* fully or partially defines the access to be denied.
*
* @return {Access} The returned object provides chainable properties to
* build and define the access to be granted. See
* {@link ?api=ac#AccessControl~Access|`Access` inner class}.
*
* @throws {AccessControlError} - If `role` is explicitly set to an invalid value.
* @throws {AccessControlError} - If called after `.lock()` is called.
*
* @example
* const ac = new AccessControl();
*
* ac.deny('admin').createAny('profile');
* // equivalent to:
* ac.deny().role('admin').createAny('profile');
* // equivalent to:
* ac.deny().role('admin').resource('profile').createAny();
* // equivalent to:
* ac.deny({
* role: 'admin',
* resource: 'profile',
* }).createAny();
* // equivalent to:
* ac.deny({
* role: 'admin',
* resource: 'profile',
* action: 'create:any'
* });
* // equivalent to:
* ac.deny({
* role: 'admin',
* resource: 'profile',
* action: 'create',
* possession: 'any' // omitting this will default to 'any'
* });
*
* // To deny same resource for multiple roles:
* ac.deny(['admin', 'user']).createOwn('profile');
*/
deny(role?: string | string[] | IAccessInfo): Access {
if (this.isLocked) throw new AccessControlError(ERR_LOCK);
// throw on explicit undefined
if (arguments.length !== 0 && role === undefined) {
throw new AccessControlError('Invalid role(s): undefined');
}
// other explicit invalid values will be checked in constructor.
return new Access(this, role, true);
}
/**
* Alias of `deny()`.
* @private
*/
reject(role?: string | string[] | IAccessInfo): Access {
return this.deny(role);
}
// -------------------------------
// PRIVATE METHODS
// -------------------------------
/**
* @private
*/
_removePermission(resources: string | string[], roles?: string | string[], actionPossession?: string) {
resources = utils.toStringArray(resources);
// resources is set but returns empty array.
if (resources.length === 0 || !utils.isFilledStringArray(resources)) {
throw new AccessControlError(`Invalid resource(s): ${JSON.stringify(resources)}`);
}
if (roles !== undefined) {
roles = utils.toStringArray(roles);
// roles is set but returns empty array.
if (roles.length === 0 || !utils.isFilledStringArray(roles)) {
throw new AccessControlError(`Invalid role(s): ${JSON.stringify(roles)}`);
}
}
utils.eachRoleResource(this._grants, (role: string, resource: string, permissions: any) => {
if (resources.indexOf(resource) >= 0
// roles is optional. so remove if role is not defined.
// if defined, check if the current role is in the list.
&& (!roles || roles.indexOf(role) >= 0)) {
if (actionPossession) {
// e.g. 'create' » 'create:any'
// to parse and normalize actionPossession string:
const ap: string = utils.normalizeActionPossession({ action: actionPossession }, true) as string;
// above will also validate the given actionPossession
delete this._grants[role][resource][ap];
} else {
// this is used for AccessControl#removeResources().
delete this._grants[role][resource];
}
}
});
}
// -------------------------------
// PUBLIC STATIC PROPERTIES
// -------------------------------
/**
* Documented separately in enums/Action
* @private
*/
static get Action(): any {
return Action;
}
/**
* Documented separately in enums/Possession
* @private
*/
static get Possession(): any {
return Possession;
}
/**
* Documented separately in AccessControlError
* @private
*/
static get Error(): any {
return AccessControlError;
}
// -------------------------------
// PUBLIC STATIC METHODS
// -------------------------------
/**
* A utility method for deep cloning the given data object(s) while
* filtering its properties by the given attribute (glob) notations.
* Includes all matched properties and removes the rest.
*
* Note that this should be used to manipulate data / arbitrary objects
* with enumerable properties. It will not deal with preserving the
* prototype-chain of the given object.
*
* @param {Object|Array} data - A single or array of data objects
* to be filtered.
* @param {Array|String} attributes - The attribute glob notation(s)
* to be processed. You can use wildcard stars (*) and negate
* the notation by prepending a bang (!). A negated notation
* will be excluded. Order of the globs do not matter, they will
* be logically sorted. Loose globs will be processed first and
* verbose globs or normal notations will be processed last.
* e.g. `[ "car.model", "*", "!car.*" ]`
* will be sorted as:
* `[ "*", "!car.*", "car.model" ]`.
* Passing no parameters or passing an empty string (`""` or `[""]`)
* will empty the source object.
*
* @returns {Object|Array} - Returns the filtered data object or array
* of data objects.
*
* @example
* var assets = { notebook: "Mac", car: { brand: "Ford", model: "Mustang", year: 1970, color: "red" } };
*
* var filtered = AccessControl.filter(assets, [ "*", "!car.*", "car.model" ]);
* console.log(assets); // { notebook: "Mac", car: { model: "Mustang" } }
*
* filtered = AccessControl.filter(assets, "*"); // or AccessControl.filter(assets, ["*"]);
* console.log(assets); // { notebook: "Mac", car: { model: "Mustang" } }
*
* filtered = AccessControl.filter(assets); // or AccessControl.filter(assets, "");
* console.log(assets); // {}
*/
static filter(data: any, attributes: string[]): any {
return utils.filterAll(data, attributes);
}
/**
* Checks whether the given object is an instance of `AccessControl.Error`.
* @name AccessControl.isACError
* @alias AccessControl.isAccessControlError
* @function
*
* @param {Any} object
* Object to be checked.
*
* @returns {Boolean}
*/
static isACError(object: any): boolean {
return object instanceof AccessControlError;
}
/**
* Alias of `isACError`
* @private
*/
static isAccessControlError(object: any): boolean {
return AccessControl.isACError(object);
}
}
export { AccessControl };