-
-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathindex.ts
79 lines (67 loc) · 2.16 KB
/
index.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
69
70
71
72
73
74
75
76
77
78
79
import axios from 'axios';
import Permission from './permission';
import { StringKV } from './types';
interface BaseResponse {
message: string;
data: any;
}
export class Authorizer {
private endpoint: string | undefined;
private user : string | undefined;
private permission = new Permission();
public constructor(endpoint?: string) {
this.endpoint = endpoint;
}
/**
* Get the permission.
*/
public getPermission() : StringKV {
return this.permission.getPermissionJson();
}
public setPermission(permission : Record<string, unknown> | string) : void{
this.permission.load(permission);
}
/**
* Get the authority of a given user from Casbin core
*/
public async syncUserPermission(): Promise<void> {
if (this.endpoint !== undefined) {
const resp = await axios.get<BaseResponse>(`${this.endpoint}?casbin_subject=${this.user}`);
this.permission.load(resp.data.data);
console.log("syncUserPermission is called")
}
}
/**
* Set the user subject for the authroizer
* @param user The current user
*/
public async setUser(user : string) : Promise<void> {
// Sync with the server and fetch the latest permission of the new user
if (user != this.user) {
this.user = user;
await this.syncUserPermission()
}
}
public can(action: string, object: string): boolean {
return this.permission.check(action, object);
}
public cannot(action: string, object: string): boolean {
return !this.permission.check(action, object);
}
public canAll(action: string, objects: Array<string>) : boolean {
for (let i = 0; i < objects.length; ++i) {
if (!this.permission.check(action, objects[i])) {
return false;
}
}
return true;
}
public canAny(action: string, objects: Array<string>) : boolean {
for (let i = 0; i < objects.length; ++i) {
if (this.permission.check(action, objects[i])) {
return true;
}
}
return false;
}
}