Skip to content

Commit

Permalink
fix: add support for legacy array definition method (#313)
Browse files Browse the repository at this point in the history
* fix: add support for legacy array definition method

Signed-off-by: Zxilly <zhouxinyu1001@gmail.com>
  • Loading branch information
Zxilly authored Aug 13, 2021
1 parent 76f4969 commit 635eece
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/coreEnforcer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
generatorRunSync,
generatorRunAsync,
customIn,
bracketCompatible,
} from './util';
import { getLogger, logPrint } from './log';
import { MatchingFunc } from './rbac';
Expand Down Expand Up @@ -61,6 +62,7 @@ export class CoreEnforcer {

let expression = this.matcherMap.get(matcherKey);
if (!expression) {
exp = bracketCompatible(exp);
expression = asyncCompile ? compileAsync(exp) : compile(exp);
this.matcherMap.set(matcherKey, expression);
}
Expand Down
22 changes: 22 additions & 0 deletions src/util/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,27 @@ function customIn(a: number | string, b: number | string): number {
return ((a in (b as any)) as unknown) as number;
}

function bracketCompatible(exp: string): string {
// TODO: This function didn't support nested bracket.
if (!(exp.includes(' in ') && exp.includes(' ('))) {
return exp;
}

const re = / \([^)]*\)/g;
const array = exp.split('');

let reResult: RegExpExecArray | null;
while ((reResult = re.exec(exp)) !== null) {
if (!(reResult[0] as string).includes(',')) {
continue;
}
array[reResult.index + 1] = '[';
array[re.lastIndex - 1] = ']';
}
exp = array.join('');
return exp;
}

export {
escapeAssertion,
removeComments,
Expand All @@ -195,4 +216,5 @@ export {
generatorRunAsync,
deepCopy,
customIn,
bracketCompatible,
};
11 changes: 11 additions & 0 deletions test/util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,3 +168,14 @@ test('test getEvalValue', () => {
expect(util.arrayEquals(util.getEvalValue('eval(a) && eval(b) && a && b && c'), ['a', 'b']));
expect(util.arrayEquals(util.getEvalValue('a && eval(a) && eval(b) && b && c'), ['a', 'b']));
});

test('bracketCompatible', () => {
expect(util.bracketCompatible("g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act || r.obj in ('data2', 'data3')")).toEqual(
"g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act || r.obj in ['data2', 'data3']"
);
expect(
util.bracketCompatible(
"g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act || r.obj in ('data2', 'data3') || r.obj in ('data4', 'data5')"
)
).toEqual("g(r.sub, p.sub) && r.obj == p.obj && r.act == p.act || r.obj in ['data2', 'data3'] || r.obj in ['data4', 'data5']");
});

0 comments on commit 635eece

Please sign in to comment.