-
Notifications
You must be signed in to change notification settings - Fork 12
/
permission.service.ts
68 lines (61 loc) · 1.82 KB
/
permission.service.ts
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
import { Injectable, Signal, signal } from '@angular/core';
import { map, Observable, ReplaySubject } from 'rxjs';
import { Profile, ProfileService, Permission } from './profile/profile.service';
import { AdminSettingsNavigationData } from './navigation/navigation.service';
@Injectable({
providedIn: 'root'
})
export class PermissionService {
private profile: Signal<Profile | undefined> = signal(undefined);
private profile$: Observable<Profile | undefined>;
constructor(profileService: ProfileService) {
this.profile = profileService.profile;
this.profile$ = profileService.profile$;
}
checkSignal(action: string, resource: string): boolean {
return (
this.profile &&
this.hasPermission(this.profile()!.permissions, action, resource)
);
}
check(action: string, resource: string): Observable<boolean> {
return this.profile$.pipe(
map((profile) => {
if (profile === undefined) {
return false;
} else {
return this.hasPermission(profile.permissions, action, resource);
}
})
);
}
private hasPermission(
permissions: Permission[],
action: string,
resource: string
) {
if (!permissions) {
return false;
}
let permission = permissions.find((p) =>
this.checkPermission(p, action, resource)
);
return permission !== undefined;
}
private checkPermission(
permission: Permission,
action: string,
resource: string
) {
let actionRegExp = this.expandPattern(permission.action);
if (actionRegExp.test(action)) {
let resourceRegExp = this.expandPattern(permission.resource);
return resourceRegExp.test(resource);
} else {
return false;
}
}
private expandPattern(pattern: string): RegExp {
return new RegExp(`^${pattern.replaceAll('*', '.*')}$`);
}
}