Refactor permissions check code

Directly check permissions and no subscription (uisettings is always initialized on frontend startup)
update permission directive to accept single string
add explicit management permission name
This commit is contained in:
Michael Shamoon
2022-11-11 14:32:18 -08:00
parent 084fe2c050
commit 5c5486d2ea
25 changed files with 74 additions and 125 deletions

View File

@@ -1,9 +0,0 @@
import { IfPermissionsDirective } from './if-permissions.directive'
// TODO - Must be implemented
describe('IfPermissionsDirective', () => {
it('should create an instance', () => {
const directive = new IfPermissionsDirective()
expect(directive).toBeTruthy()
})
})

View File

@@ -4,18 +4,15 @@ import {
Directive,
ViewContainerRef,
TemplateRef,
OnDestroy,
} from '@angular/core'
import { Subscription } from 'rxjs'
import { SettingsService } from '../services/settings.service'
@Directive({
selector: '[ifPermissions]',
})
export class IfPermissionsDirective implements OnInit, OnDestroy {
private subscription: Subscription[] = []
export class IfPermissionsDirective implements OnInit {
// The role the user must have
@Input() public ifPermissions: Array<string>
@Input() public ifPermissions: Array<string> | string
/**
* @param {ViewContainerRef} viewContainerRef -- The location where we need to render the templateRef
@@ -29,32 +26,14 @@ export class IfPermissionsDirective implements OnInit, OnDestroy {
) {}
public ngOnInit(): void {
this.subscription.push(
this.settingsService.permissions().subscribe((permission) => {
if (!permission) {
// Remove element from DOM
this.viewContainerRef.clear()
}
// User permissions are checked by a permission mention in DOM
const idx = permission.findIndex(
(element) => this.ifPermissions.indexOf(element) !== -1
)
if (idx < 0) {
this.viewContainerRef.clear()
} else {
// Appends the ref element to DOM
this.viewContainerRef.createEmbeddedView(this.templateRef)
}
})
)
}
/**
* On destroy cancels the API if its fetching.
*/
public ngOnDestroy(): void {
this.subscription.forEach((subscription: Subscription) =>
subscription.unsubscribe()
)
if (
[]
.concat(this.ifPermissions)
.every((perm) => this.settingsService.currentUserCan(perm))
) {
this.viewContainerRef.createEmbeddedView(this.templateRef)
} else {
this.viewContainerRef.clear()
}
}
}

View File

@@ -1,8 +0,0 @@
import { SortableDirective } from './sortable.directive'
describe('SortableDirective', () => {
it('should create an instance', () => {
const directive = new SortableDirective()
expect(directive).toBeTruthy()
})
})