open-learning-exchange/planet

View on GitHub
src/app/shared/authorized-roles.directive.ts

Summary

Maintainability
A
0 mins
Test Coverage
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
import { UserService } from './user.service';

@Directive({
  selector: '[planetAuthorizedRoles]'
})
export class AuthorizedRolesDirective {

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef,
    private userService: UserService
  ) {}

  @Input()
  set planetAuthorizedRoles(rolesString: string) {
    const authorizedRoles = (rolesString || '').split(',').map(val => val.trim());
    const allowedAdmins = authorizedRoles[0] === 'only' ? [] : [ '_admin', 'manager' ];
    if (rolesString === '_any' || this.userService.doesUserHaveRole([ ...allowedAdmins, ...authorizedRoles ])) {
      this.viewContainer.createEmbeddedView(this.templateRef);
    } else {
      this.viewContainer.clear();
    }
  }

}