common-ui/src/lib/permissions/directives/allow.directive.ts
2023-03-19 14:33:40 +02:00

73 lines
2.2 KiB
TypeScript

import { Directive, Input, OnDestroy, OnInit, TemplateRef } from '@angular/core';
import { Observable } from 'rxjs';
import { List } from '../../utils';
import { assertTemplate, IqserPermissionsDirective } from './permissions.directive';
@Directive({
selector: '[allow]',
standalone: true,
})
export class IqserAllowDirective extends IqserPermissionsDirective implements OnDestroy, OnInit {
/**
* Assert the correct type of the expression bound to the `allow` input within the template.
*
* The presence of this static field is a signal to the Ivy template type check compiler that
* when the `IqserPermissionsDirective` structural directive renders its template, the type of the expression bound
* to `allow` should be narrowed in some way.
* For `allow`, the binding expression itself is used to
* narrow its type, which allows the strictNullChecks feature of TypeScript to work with `IqserPermissionsDirective`.
*/
static ngTemplateGuard_allow: 'binding';
#deny?: string | List;
@Input()
set allow(value: string | List) {
this.setPermissions(value);
}
@Input()
set allowThen(template: TemplateRef<unknown>) {
assertTemplate('allowThen', template);
this.setThenTemplateRef(template);
}
@Input()
set allowElse(template: TemplateRef<unknown>) {
assertTemplate('allowElse', template);
this.setElseTemplateRef(template);
}
@Input()
set allowDeny(value: string | List) {
this.#deny = value;
this._updateView.next();
}
@Input()
set allowIf(value: boolean | Promise<boolean> | Observable<boolean>) {
this.setIf(value);
}
get #hasDenyPermission() {
if (!this.#deny) {
return false;
}
return this._permissionsService.hasSome(this.#deny) || this._rolesService.hasSome(this.#deny);
}
protected override _validate() {
const hasDenyPermission = this.#hasDenyPermission;
if (!this._permissions) {
return !hasDenyPermission;
}
if (hasDenyPermission) {
return false;
}
return this._permissionsService.has(this._permissions) || this._rolesService.has(this._permissions);
}
}