Page MenuHomeSealhub

roles.ts
No OneTemporary

roles.ts

/* eslint-disable @typescript-eslint/consistent-type-assertions */
import type { ActionName, Collection, Context } from "sealious";
import { Policies } from "sealious";
import { Policy, QueryTypes } from "sealious";
export class Roles extends Policy {
static type_name = "roles";
allowed_roles: string[];
constructor(allowed_roles: string[]) {
super(allowed_roles);
this.allowed_roles = allowed_roles;
}
async countMatchingRoles(context: Context) {
const user_id = context.user_id;
context.app.Logger.debug2("ROLES", "Checking the roles for user", user_id);
const roles = await context.cache("roles_for_this_user", async () => {
const { items: user_roles } = await (
context.app.collections["user-roles"] as Collection
)
.suList()
.filter({ user: user_id })
.fetch();
const roles = user_roles.map(
// eslint-disable-next-line @typescript-eslint/consistent-type-assertions
(user_role) => user_role.get("role") as string
);
return roles;
});
return this.allowed_roles.filter((allowed_role) => roles.includes(allowed_role))
.length;
}
async _getRestrictingQuery(context: Context) {
if (context.is_super) {
return new QueryTypes.AllowAll();
}
if (context.user_id === null) {
return new QueryTypes.DenyAll();
}
const matching_roles_count = await this.countMatchingRoles(context);
return matching_roles_count > 0
? new QueryTypes.AllowAll()
: new QueryTypes.DenyAll();
}
async checkerFunction(context: Context) {
if (context.user_id === null) {
return Policy.deny(context.app.i18n("policy_logged_in_deny"));
}
const matching_roles_count = await this.countMatchingRoles(context);
return matching_roles_count > 0
? Policy.allow(
context.app.i18n("policy_roles_allow", [
this.allowed_roles.join(", "),
])
)
: Policy.deny(
context.app.i18n("policy_roles_deny", [this.allowed_roles.join(", ")])
);
}
}
export function CRUDRoles(
collection_names: string[],
fallbacks: Partial<Record<ActionName, Policy>> = {}
) {
const result = Object.fromEntries(
(["show", "create", "edit", "delete"] as ActionName[]).map((action_name) => {
const crud_policy = new Roles([
"admin",
...collection_names.map(
(collection_name) => collection_name + "_" + action_name
),
]);
const fallback_policy = fallbacks[action_name];
return [
action_name,
fallback_policy
? new Policies.Or([crud_policy, fallback_policy])
: crud_policy,
];
})
);
// console.log(collection_names, result);
return result;
}

File Metadata

Mime Type
text/x-java
Expires
Thu, Jul 3, 19:58 (7 h, 24 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
796331
Default Alt Text
roles.ts (2 KB)

Event Timeline