UNPKG

casbin-pg-adapter-with-schema

Version:

PostgreSQL native adapter for Node-Casbin with advanced filter capability and improved performance.

77 lines (76 loc) 2.37 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PostgresAdapter = void 0; const casbin_1 = require("casbin"); const repository_1 = require("./repository"); class PostgresAdapter { constructor(options) { this.filtered = true; this.repo = new repository_1.CasbinRepository(options); } static async newAdapter(options) { const adapter = new PostgresAdapter(options); await adapter.open(); return adapter; } static async migrate(options) { const repo = new repository_1.CasbinRepository(options); await repo.migrate(); await repo.close(); } async open() { await this.repo.open(); } async close() { await this.repo.close(); } isFiltered() { return this.filtered; } enabledFiltered(enabled) { this.filtered = enabled; } async loadPolicy(model) { const rules = await this.repo.getAllPolicies(); loadPolicyLines(model, rules); } async loadFilteredPolicy(model, filter) { const rules = await this.repo.getFilteredPolicies(filter); loadPolicyLines(model, rules); } async savePolicy(model) { await this.repo.clearPolicies(); const rules = []; let astMap = model.model.get("p"); for (const [ptype, ast] of astMap) { for (const rule of ast.policy) { rules.push({ ptype, rule }); } } astMap = model.model.get("g"); for (const [ptype, ast] of astMap) { for (const rule of ast.policy) { rules.push({ ptype, rule }); } } if (rules.length) { await this.repo.insertPolicies(rules); } return rules.length > 0; } addPolicy(sec, ptype, rule) { return this.repo.insertPolicy(ptype, rule); } removePolicy(sec, ptype, rule) { return this.repo.deletePolicies(ptype, rule); } removeFilteredPolicy(sec, ptype, fieldIndex, ...fieldValues) { return this.repo.deletePolicies(ptype, fieldValues, fieldIndex); } } exports.PostgresAdapter = PostgresAdapter; function loadPolicyLines(model, rules) { rules.forEach(rule => { casbin_1.Helper.loadPolicyLine(`${rule.ptype}, ${rule.rule.join(", ")}`, model); }); }