-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathhas-role.directive.ts
More file actions
70 lines (57 loc) · 1.69 KB
/
has-role.directive.ts
File metadata and controls
70 lines (57 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import {
Directive,
effect,
inject,
input,
TemplateRef,
ViewContainerRef,
} from '@angular/core';
import { Role } from './user.model';
import { UserStore } from './user.store';
@Directive({ selector: '[hasRole]' })
export class HasRoleDirective {
private readonly templateRef = inject(TemplateRef<unknown>);
private readonly vcRef = inject(ViewContainerRef);
private readonly userStore = inject(UserStore);
hasRole = input<Role[], Role | Role[]>([], {
alias: 'hasRole',
transform: (v: Role | Role[]) => {
return typeof v === 'string' ? [v] : v;
},
});
effect = effect(() => {
const user = this.userStore.getUser();
const userRoles = user()?.roles ?? [];
const requiredRoles = this.hasRole() ?? [];
this.updateView(userRoles, requiredRoles);
});
private updateView(userRoles: Role[], requiredRoles: Role[]) {
this.vcRef.clear();
if (requiredRoles.length === 0) {
this.vcRef.createEmbeddedView(this.templateRef);
return;
}
const canAccess = requiredRoles.some((role) =>
userRoles.includes(role as any),
);
if (canAccess) {
this.vcRef.createEmbeddedView(this.templateRef);
}
}
}
@Directive({ selector: '[isSuperAdmin]' })
export class IsSuperAdminDirective {
private readonly templateRef = inject(TemplateRef<unknown>);
private readonly vcRef = inject(ViewContainerRef);
private readonly userStore = inject(UserStore);
effect = effect(() => {
const user = this.userStore.getUser();
this.updateView(user()?.isAdmin);
});
private updateView(isAdminUser: boolean | undefined) {
this.vcRef.clear();
if (isAdminUser) {
this.vcRef.createEmbeddedView(this.templateRef);
}
}
}