forked from tolustar/cerbos-authorization
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthorization.js
40 lines (32 loc) · 1.01 KB
/
authorization.js
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
const { GRPC } = require("@cerbos/grpc");
const { users } = require("./db");
// The Cerbos PDP instance
const cerbos = new GRPC("localhost:3593", {
tls: false,
});
const SHOW_PDP_REQUEST_LOG = false;
module.exports = async (principalId, action, resourceAtrr = {}) => {
const user = users.find((item) => item.id === Number(principalId));
const cerbosObject = {
resource: {
kind: "blogpost",
policyVersion: "default",
id: resourceAtrr.id + "" || "new",
attributes: resourceAtrr,
},
principal: {
id: principalId + "" || "0",
policyVersion: "default",
roles: [user?.role || "unknown"],
attributes: user,
},
actions: [action],
};
SHOW_PDP_REQUEST_LOG &&
console.log("cerbosObject \n", JSON.stringify(cerbosObject, null, 4));
const cerbosCheck = await cerbos.checkResource(cerbosObject);
const isAuthorized = cerbosCheck.isAllowed(action);
if (!isAuthorized)
throw new Error("You are not authorized to visit this resource");
return true;
};