Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: multiple section types #373

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions examples/mulitple_policy.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
p2, alice, data1, read
p2, bob, data2, write
42 changes: 33 additions & 9 deletions src/coreEnforcer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import { DefaultEffector, Effect, Effector } from './effect';
import { FunctionMap, Model, newModel, PolicyOp } from './model';
import { Adapter, FilteredAdapter, Watcher, BatchAdapter, UpdatableAdapter } from './persist';
import { DefaultRoleManager, RoleManager } from './rbac';
import { EnforceContext } from './enforceContext';

import {
escapeAssertion,
generateGFunction,
Expand Down Expand Up @@ -45,6 +47,7 @@ export class CoreEnforcer {
protected fm: FunctionMap = FunctionMap.loadFunctionMap();
protected eft: Effector = new DefaultEffector();
private matcherMap: Map<string, Matcher> = new Map();
private defaultEnforceContext: EnforceContext = new EnforceContext('r', 'p', 'e', 'm');

protected adapter: UpdatableAdapter | FilteredAdapter | Adapter | BatchAdapter;
protected watcher: Watcher | null = null;
Expand Down Expand Up @@ -368,7 +371,12 @@ export class CoreEnforcer {
}
}

private *privateEnforce(asyncCompile = true, explain = false, ...rvals: any[]): EnforceResult {
private *privateEnforce(
asyncCompile = true,
explain = false,
enforceContext: EnforceContext = new EnforceContext('r', 'p', 'e', 'm'),
...rvals: any[]
): EnforceResult {
if (!this.enabled) {
return true;
}
Expand All @@ -387,23 +395,23 @@ export class CoreEnforcer {
functions[key] = generateGFunction(rm);
});

const expString = this.model.model.get('m')?.get('m')?.value;
const expString = this.model.model.get('m')?.get(enforceContext.mType)?.value;
if (!expString) {
throw new Error('Unable to find matchers in model');
}

const effectExpr = this.model.model.get('e')?.get('e')?.value;
const effectExpr = this.model.model.get('e')?.get(enforceContext.eType)?.value;
if (!effectExpr) {
throw new Error('Unable to find policy_effect in model');
}

const HasEval: boolean = hasEval(expString);
let expression: Matcher | undefined = undefined;

const p = this.model.model.get('p')?.get('p');
const p = this.model.model.get('p')?.get(enforceContext.pType);
const policyLen = p?.policy?.length;

const rTokens = this.model.model.get('r')?.get('r')?.tokens;
const rTokens = this.model.model.get('r')?.get(enforceContext.rType)?.tokens;
const rTokensLen = rTokens?.length;

const effectStream = this.eft.newStream(effectExpr);
Expand Down Expand Up @@ -551,7 +559,11 @@ export class CoreEnforcer {
* @return whether to allow the request.
*/
public enforceSync(...rvals: any[]): boolean {
return generatorRunSync(this.privateEnforce(false, false, ...rvals));
if (rvals[0] instanceof EnforceContext) {
const enforceContext: EnforceContext = rvals.shift();
return generatorRunSync(this.privateEnforce(false, false, enforceContext, ...rvals));
}
return generatorRunSync(this.privateEnforce(false, false, this.defaultEnforceContext, ...rvals));
}

/**
Expand All @@ -565,7 +577,11 @@ export class CoreEnforcer {
* @return whether to allow the request and the reason rule.
*/
public enforceExSync(...rvals: any[]): [boolean, string[]] {
return generatorRunSync(this.privateEnforce(false, true, ...rvals));
if (rvals[0] instanceof EnforceContext) {
const enforceContext: EnforceContext = rvals.shift();
return generatorRunSync(this.privateEnforce(false, true, enforceContext, ...rvals));
}
return generatorRunSync(this.privateEnforce(false, true, this.defaultEnforceContext, ...rvals));
}

/**
Expand All @@ -584,7 +600,11 @@ export class CoreEnforcer {
* @return whether to allow the request.
*/
public async enforce(...rvals: any[]): Promise<boolean> {
return generatorRunAsync(this.privateEnforce(true, false, ...rvals));
if (rvals[0] instanceof EnforceContext) {
const enforceContext: EnforceContext = rvals.shift();
return generatorRunAsync(this.privateEnforce(true, false, enforceContext, ...rvals));
}
return generatorRunAsync(this.privateEnforce(true, false, this.defaultEnforceContext, ...rvals));
}

/**
Expand All @@ -596,7 +616,11 @@ export class CoreEnforcer {
* @return whether to allow the request and the reason rule.
*/
public async enforceEx(...rvals: any[]): Promise<[boolean, string[]]> {
return generatorRunAsync(this.privateEnforce(true, true, ...rvals));
if (rvals[0] instanceof EnforceContext) {
const enforceContext: EnforceContext = rvals.shift();
return generatorRunAsync(this.privateEnforce(true, true, enforceContext, ...rvals));
}
return generatorRunAsync(this.privateEnforce(true, true, this.defaultEnforceContext, ...rvals));
}

/**
Expand Down
20 changes: 20 additions & 0 deletions src/enforceContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { newEnforcer } from './enforcer';

export class EnforceContext {
public pType: string;
public rType: string;
public eType: string;
public mType: string;

constructor(rType: string, pType: string, eType: string, mType: string) {
this.pType = pType;
this.eType = eType;
this.mType = mType;
this.rType = rType;
}
}
export class NewEnforceContext {
constructor(index: string) {
return new EnforceContext('r' + index, 'p' + index, 'e' + index, 'm' + index);
}
}
4 changes: 2 additions & 2 deletions src/enforcer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

import { ManagementEnforcer } from './managementEnforcer';
import { Model, newModel } from './model';
import { Adapter, FileAdapter, StringAdapter } from './persist';
import { Adapter, FileAdapter, MemoryAdapter } from './persist';
import { getLogger } from './log';
import { arrayRemoveDuplicates } from './util';

Expand All @@ -40,7 +40,7 @@ export class Enforcer extends ManagementEnforcer {
* @param lazyLoad whether to load policy at initial time
*/
public async initWithString(modelPath: string, policyString: string, lazyLoad = false): Promise<void> {
const a = new StringAdapter(policyString);
const a = new MemoryAdapter(policyString);
await this.initWithAdapter(modelPath, a, lazyLoad);
}

Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,6 @@ export * from './model';
export * from './persist';
export * from './rbac';
export * from './log';
export { EnforceContext } from './enforceContext';
export * from './frontend';
export { Util };
5 changes: 4 additions & 1 deletion src/model/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,11 @@ export class Model {
/**
* constructor is the constructor for Model.
*/
constructor() {
constructor(text?: string) {
this.model = new Map<string, Map<string, Assertion>>();
if (text) {
this.loadModelFromText(text);
}
}

private loadAssertion(cfg: ConfigInterface, sec: string, key: string): boolean {
Expand Down
2 changes: 1 addition & 1 deletion src/persist/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export * from './adapter';
export * from './fileAdapter';
export * from './stringAdapter';
export * from './memoryAdapter';
export * from './helper';
export * from './watcher';
export * from './filteredAdapter';
Expand Down
105 changes: 105 additions & 0 deletions src/persist/memoryAdapter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { Adapter } from './adapter';
import { Model } from '../model';
import { Helper } from './helper';
import { BatchAdapter } from './batchAdapter';
import { arrayEquals, policyArrayToString, policyStringToArray } from '../util';

/**
* MemoryAdapter is the memory adapter for Casbin.
* It can load policy from a string.
*/
export class MemoryAdapter implements Adapter, BatchAdapter {
protected policies: string[][] = [];

/**
* MemoryAdapter is the constructor for MemoryAdapter.
* @param policy - policy formatted as a CSV string, or policy array.
*/
constructor(policy: string | string[][]) {
if (!policy) {
return;
}
if (typeof policy === 'string') {
this.policies = policyStringToArray(policy);
} else {
this.policies = policy;
}
}

/**
* hasPolicy checks if specific policy exists in storage.
*/
public hasPolicy(policy: string[]): boolean {
return this.policies.some((prePolicy) => {
return arrayEquals(prePolicy, policy);
});
}

/**
* loadPolicy loads data in adapter to model.
* @param model
*/
public async loadPolicy(model: Model): Promise<void> {
this.policies.forEach((n: string[]) => {
if (!n) {
return;
}
Helper.loadPolicyLine(policyArrayToString(n), model);
});
}

/**
* savePolicy saves all policy rules to the storage.
*/
public async savePolicy(model: Model): Promise<boolean> {
throw new Error('not implemented');
}

/**
* addPolicy adds a policy rule to the storage.
*/
public async addPolicy(sec: string, ptype: string, rule: string[]): Promise<void> {
const policy = rule.slice();
policy.unshift(ptype);
if (!this.hasPolicy(rule)) {
this.policies.push(policy);
}
}

/**
* removePolicy removes a policy rule from the storage.
*/
public async removePolicy(sec: string, ptype: string, rule: string[]): Promise<void> {
const ruleClone = rule.slice();
ruleClone.unshift(ptype);
this.policies = this.policies.filter((r) => !arrayEquals(ruleClone, r));
}

/**
* removeFilteredPolicy removes policy rules that match the filter from the storage.
*/
public async removeFilteredPolicy(sec: string, ptype: string, fieldIndex: number, ...fieldValues: string[]): Promise<void> {
throw new Error('not implemented');
}

/**
* addPolicies adds policy rules to the storage.
*/
public async addPolicies(sec: string, ptype: string, rules: string[][]): Promise<void> {
for (const rule of rules) {
if (!this.hasPolicy(rule)) {
await this.addPolicy(sec, ptype, rule);
}
}
}

/**
* removePolicies removes policy rules from the storage.
* This is part of the Auto-Save feature.
*/
public async removePolicies(sec: string, ptype: string, rules: string[][]): Promise<void> {
this.policies = this.policies.filter((rule) => {
return !rules.some((deleteRule) => arrayEquals(deleteRule, rule));
});
}
}
65 changes: 0 additions & 65 deletions src/persist/stringAdapter.ts

This file was deleted.

Loading