/
if-permissions.directive.ts
69 lines (63 loc) · 2.44 KB
/
if-permissions.directive.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
import { ChangeDetectorRef, Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { of } from 'rxjs';
import { map, tap } from 'rxjs/operators';
import { Permission } from '../../common/generated-types';
import { PermissionsService } from '../../providers/permissions/permissions.service';
import { IfDirectiveBase } from './if-directive-base';
/**
* @description
* Conditionally shows/hides templates based on the current active user having the specified permission.
* Based on the ngIf source. Also support "else" templates:
*
* @example
* ```html
* <button *vdrIfPermissions="'DeleteCatalog'; else unauthorized">Delete Product</button>
* <ng-template #unauthorized>Not allowed!</ng-template>
* ```
*
* The permission can be a single string, or an array. If an array is passed, then _all_ of the permissions
* must match (logical AND)
*
* @docsCategory directives
*/
@Directive({
selector: '[vdrIfPermissions]',
})
export class IfPermissionsDirective extends IfDirectiveBase<Array<Permission[] | null>> {
private permissionToCheck: string[] | null = ['__initial_value__'];
constructor(
_viewContainer: ViewContainerRef,
templateRef: TemplateRef<any>,
private changeDetectorRef: ChangeDetectorRef,
private permissionsService: PermissionsService,
) {
super(_viewContainer, templateRef, permissions => {
if (permissions == null) {
return of(true);
} else if (!permissions) {
return of(false);
}
return this.permissionsService.currentUserPermissions$.pipe(
map(() => this.permissionsService.userHasPermissions(permissions)),
tap(() => this.changeDetectorRef.markForCheck()),
);
});
}
/**
* The permission to check to determine whether to show the template.
*/
@Input()
set vdrIfPermissions(permission: string | string[] | null) {
this.permissionToCheck =
(permission && (Array.isArray(permission) ? permission : [permission])) || null;
this.updateArgs$.next([this.permissionToCheck as Permission[]]);
}
/**
* A template to show if the current user does not have the specified permission.
*/
@Input()
set vdrIfPermissionsElse(templateRef: TemplateRef<any> | null) {
this.setElseTemplate(templateRef);
this.updateArgs$.next([this.permissionToCheck as Permission[]]);
}
}