import { AccessControlProvider } from "@refinedev/core";
import { newModel, StringAdapter, newEnforcer } from "casbin";
import { IAccessControlRule } from "interfaces";
import { store } from "redux/store";
const model = newModel(`
[request_definition]
r = subject, object, action
[policy_definition]
p = subject, object, action, eft
[role_definition]
g = _, _
[policy_effect]
e = some(where (p.eft == allow)) \
&& !some(where (p.eft == deny))
[matchers]
m = g(r.subject, p.subject) \
&& regexMatch(r.object, p.object) \
&& regexMatch(r.action, p.action)
`);
export const accessControlProvider: AccessControlProvider = {
can: async ({ resource, action, params }) => {
const role = store?.getState()?.user?.role;
const accessControlRules = store?.getState()?.temp?.accessControlRules;
const ruleString = accessControlRules
?.map((item: IAccessControlRule) => {
return `p, ${item?.role}, ${item?.route}, ${item?.permissions?.join(
"|"
)}`;
})
?.join("\n");
let targetUrl = params?.route || resource;
if (targetUrl?.charAt(0) === "/") targetUrl = targetUrl.slice(1);
const adapter = new StringAdapter(ruleString || `p, guest, /, *`);
const enforcer = await newEnforcer(model, adapter);
const can = await enforcer.enforce(role, targetUrl, action);
return Promise.resolve({ can });
},
};