1 import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
3 import _ from 'lodash';
5 import { Permission, Permissions } from '~/app/shared/models/permissions';
6 import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
8 type Condition = string | string[] | Partial<{ [Property in keyof Permissions]: keyof Permission }>;
13 export class AuthStorageDirective {
14 permissions: Permissions;
17 private templateRef: TemplateRef<any>,
18 private viewContainer: ViewContainerRef,
19 private authStorageService: AuthStorageService
22 @Input('cdScope') set cdScope(condition: Condition) {
23 this.permissions = this.authStorageService.getPermissions();
24 if (this.isAuthorized(condition)) {
25 this.viewContainer.createEmbeddedView(this.templateRef);
27 this.viewContainer.clear();
31 @Input() cdScopeMatchAll = true;
33 private isAuthorized(condition: Condition): boolean {
34 const everyOrSome = this.cdScopeMatchAll ? _.every : _.some;
36 if (_.isString(condition)) {
37 return _.get(this.permissions, [condition, 'read'], false);
38 } else if (_.isArray(condition)) {
39 return everyOrSome(condition, (permission) => this.permissions[permission]['read']);
40 } else if (_.isObject(condition)) {
41 return everyOrSome(condition, (value, key) => {
42 return everyOrSome(value, (val) => this.permissions[key][val]);