-
Notifications
You must be signed in to change notification settings - Fork 0
/
permission.service.ts
60 lines (50 loc) · 1.79 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
import { Injectable } from '@angular/core';
import { map, Observable } from 'rxjs';
import { Profile, ProfileService, Permission } from './profile/profile.service';
@Injectable({
providedIn: 'root'
})
export class PermissionService {
private profile$: Observable<Profile | undefined>;
constructor(profileService: ProfileService) {
this.profile$ = profileService.profile$;
}
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);
}
})
);
}
checkPID(postPID: number): Observable<boolean> {
return this.profile$.pipe(
map(profile => {
if (profile === undefined) {
return false;
} else {
return profile.pid === postPID
}
})
)
}
private hasPermission(permissions: Permission[], action: string, resource: string) {
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('*', '.*')}$`);
}
}