]> git.proxmox.com Git - ceph.git/blob - ceph/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/auth-storage.directive.ts
5f130902a23c59087961d3e20f5e8e64c8bbedf4
[ceph.git] / ceph / src / pybind / mgr / dashboard / frontend / src / app / shared / directives / auth-storage.directive.ts
1 import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';
2
3 import _ from 'lodash';
4
5 import { Permission, Permissions } from '~/app/shared/models/permissions';
6 import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
7
8 type Condition = string | string[] | Partial<{ [Property in keyof Permissions]: keyof Permission }>;
9
10 @Directive({
11 selector: '[cdScope]'
12 })
13 export class AuthStorageDirective {
14 permissions: Permissions;
15
16 constructor(
17 private templateRef: TemplateRef<any>,
18 private viewContainer: ViewContainerRef,
19 private authStorageService: AuthStorageService
20 ) {}
21
22 @Input('cdScope') set cdScope(condition: Condition) {
23 this.permissions = this.authStorageService.getPermissions();
24 if (this.isAuthorized(condition)) {
25 this.viewContainer.createEmbeddedView(this.templateRef);
26 } else {
27 this.viewContainer.clear();
28 }
29 }
30
31 @Input() cdScopeMatchAll = true;
32
33 private isAuthorized(condition: Condition): boolean {
34 const everyOrSome = this.cdScopeMatchAll ? _.every : _.some;
35
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]);
43 });
44 }
45
46 return false;
47 }
48 }