mirror of
https://github.com/shishantbiswas/bknd.git
synced 2026-03-17 04:46:05 +00:00
refactor: restructure permission handling and enhance Guard functionality
- Introduced a new `createGuard` function to streamline the creation of Guard instances with permissions and roles. - Updated tests in `authorize.spec.ts` to reflect changes in permission checks, ensuring they now return undefined for denied permissions. - Added new `Permission` and `Policy` classes to improve type safety and flexibility in permission management. - Refactored middleware and controller files to utilize the updated permission structure, including context handling for permissions. - Created a new `SystemController.spec.ts` file to test the integration of the new permission system within the SystemController. - Removed legacy permission handling from core security files, consolidating permission logic within the new structure.
This commit is contained in:
42
app/src/auth/authorize/Policy.ts
Normal file
42
app/src/auth/authorize/Policy.ts
Normal file
@@ -0,0 +1,42 @@
|
||||
import { s, parse, recursivelyReplacePlaceholders } from "bknd/utils";
|
||||
import * as query from "core/object/query/object-query";
|
||||
|
||||
export const policySchema = s
|
||||
.strictObject({
|
||||
description: s.string(),
|
||||
condition: s.object({}).optional() as s.Schema<{}, query.ObjectQuery | undefined>,
|
||||
effect: s.string({ enum: ["allow", "deny", "filter"], default: "allow" }),
|
||||
filter: s.object({}).optional() as s.Schema<{}, query.ObjectQuery | undefined>,
|
||||
})
|
||||
.partial();
|
||||
export type PolicySchema = s.Static<typeof policySchema>;
|
||||
|
||||
export class Policy<Schema extends PolicySchema = PolicySchema> {
|
||||
public content: Schema;
|
||||
|
||||
constructor(content?: Schema) {
|
||||
this.content = parse(policySchema, content ?? {}, {
|
||||
withDefaults: true,
|
||||
}) as Schema;
|
||||
}
|
||||
|
||||
replace(context: object, vars?: Record<string, any>) {
|
||||
return vars ? recursivelyReplacePlaceholders(context, /^@([a-zA-Z_\.]+)$/, vars) : context;
|
||||
}
|
||||
|
||||
meetsCondition(context: object, vars?: Record<string, any>) {
|
||||
return query.validate(this.replace(this.content.condition!, vars), context);
|
||||
}
|
||||
|
||||
meetsFilter(subject: object, vars?: Record<string, any>) {
|
||||
return query.validate(this.replace(this.content.filter!, vars), subject);
|
||||
}
|
||||
|
||||
getFiltered<Given extends any[]>(given: Given): Given {
|
||||
return given.filter((item) => this.meetsFilter(item)) as Given;
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
return this.content;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user