I created my application using angular 2 and PrimeNG. I am trying to implement directives for checking user authority when a button is clicked. The issue I am facing is that even though there is no authority, the click event continues to be triggered. How can I halt the process if the checkAuth() function returns false?
This is a blockquote
@Directive({
selector: '[checkAuthOnClick]'
})
export class CheckAuthorizationOnClickDirective {
user: Observable<User>;
@Input() allowedClaim: any;
observer: MutationObserver;
constructor(private element: ElementRef, private store: Store<fromRoot.State>) {
this.element = element.nativeElement;
}
@Output()
stop: EventEmitter<Event> = new EventEmitter;
@HostListener('click', ['$event, $event.target'])
onClick(event, targetElement) {
if (!this.checkAuth()) {
event.stopPropagation();
event.preventDefault();
event.cancelBuble = true;
event.stopImmediatePropagation();
this.stop.emit(event);
}
}
private checkAuth(): boolean {
this.user = this.store.select(fromRoot.currentUser);
if (this.user != undefined && this.allowedClaim != undefined) {
var hasClaim = false;
var description;
this.user.subscribe(x => {
if (Array.isArray(this.allowedClaim)) {
for (let i = 0; i < this.allowedClaim.length; i++) {
hasClaim = x.hasClaim(this.allowedClaim[i])
if (hasClaim)
break;
}
description = this.allowedClaim[0].Description;
}
else {
hasClaim = x.hasClaim(this.allowedClaim);
description = this.allowedClaim.Description;
}
});
if (hasClaim == false) {
var message = "You do not have permission for this action.";
if (description != undefined) {
message = description + ' You do not have permission.'
}
this.store.dispatch(new ui.ToastMessagePushAction({ severity: 'warning', summary: message, detail: '' }));
}
}
return hasClaim;
}
}
Using this directive in HTML would look like this;
<button type="button" pButton icon="fa fa-file-code-o" (click)="createForm()" checkAuthOnClick [allowedClaim]="systemDefinedClaims?.CreateInvoiceDesign"></button>