From 7de9fd853679421cf2331c44db6807aa19efd87a Mon Sep 17 00:00:00 2001 From: markuczy <129275100+markuczy@users.noreply.github.com> Date: Mon, 29 Jul 2024 14:55:39 +0200 Subject: [PATCH] feat: permission checker is optional for permission directive (#346) --- .../lib/directives/if-permission.directive.ts | 20 ++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/libs/angular-accelerator/src/lib/directives/if-permission.directive.ts b/libs/angular-accelerator/src/lib/directives/if-permission.directive.ts index a2f60633..ed98fbc6 100644 --- a/libs/angular-accelerator/src/lib/directives/if-permission.directive.ts +++ b/libs/angular-accelerator/src/lib/directives/if-permission.directive.ts @@ -10,6 +10,7 @@ import { TemplateRef, ViewContainerRef, } from '@angular/core' +import { UserService } from '@onecx/angular-integration-interface' export interface HasPermissionChecker { hasPermission(permissionKey: string): boolean @@ -20,7 +21,7 @@ export interface HasPermissionChecker { */ export class AlwaysGrantPermissionChecker implements HasPermissionChecker { hasPermission(_permissionKey: string): boolean { - return true; + return true } } @@ -42,16 +43,25 @@ export class IfPermissionDirective implements OnInit { this.ocxIfPermissionPermissions = value } + private permissionChecker: HasPermissionChecker | undefined negate = false constructor( private renderer: Renderer2, private el: ElementRef, private viewContainer: ViewContainerRef, + @Optional() @Inject(HAS_PERMISSION_CHECKER) - private permissionChecker: HasPermissionChecker, - @Optional() private templateRef?: TemplateRef - ) {} + private hasPermissionChecker?: HasPermissionChecker, + @Optional() private templateRef?: TemplateRef, + @Optional() private userService?: UserService + ) { + if (!(hasPermissionChecker || userService)) { + throw 'IfPermission requires UserService or HasPermissionChecker to be provided!' + } + + this.permissionChecker = hasPermissionChecker ?? userService + } ngOnInit() { if (this.permission) { @@ -77,6 +87,6 @@ export class IfPermissionDirective implements OnInit { } return result } - return this.permissionChecker.hasPermission(permission) + return this.permissionChecker?.hasPermission(permission) } }