Skip to content

Commit

Permalink
fix: fix CasbinJsGetPermissionForUser() (#251)
Browse files Browse the repository at this point in the history
* fix: fix CasbinJsGetPermissionForUser()

it has unexpected side affect, will change policies when it read from
that

Signed-off-by: Zxilly <zhouxinyu1001@gmail.com>

* test: enhance CasbinJsGetPermissionForUser() tests

Signed-off-by: Zxilly <zhouxinyu1001@gmail.com>

* feat: add deepCopy function

Signed-off-by: Zxilly <zhouxinyu1001@gmail.com>

* style: remove comment

Signed-off-by: Zxilly <zhouxinyu1001@gmail.com>

* feat: add missing import

Signed-off-by: Zxilly <zhouxinyu1001@gmail.com>
  • Loading branch information
Zxilly authored Apr 5, 2021
1 parent 92f8d05 commit 98c11f1
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/frontend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
// limitations under the License.

import { Enforcer } from './enforcer';
import { deepCopy } from './util';

/**
* Experiment!
Expand Down Expand Up @@ -41,7 +42,7 @@ export async function casbinJsGetPermissionForUser(e: Enforcer, user: string): P
s += '[matchers]\n';
s += `m = ${m.get('m')?.get('m')?.value.replace(/_/g, '.')}`;
obj['m'] = s;
obj['p'] = await e.getPolicy();
obj['p'] = deepCopy(await e.getPolicy());
for (const arr of obj['p']) {
arr.splice(0, 0, 'p');
}
Expand Down
12 changes: 12 additions & 0 deletions src/util/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,17 @@ async function generatorRunAsync(iterator: Generator<any>): Promise<any> {
}
}

function deepCopy(obj: Array<any> | any): any {
if (typeof obj !== 'object') return;
const newObj: any = obj instanceof Array ? [] : {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
}
}
return newObj;
}

export {
escapeAssertion,
removeComments,
Expand All @@ -175,4 +186,5 @@ export {
getEvalValue,
generatorRunSync,
generatorRunAsync,
deepCopy,
};
5 changes: 5 additions & 0 deletions test/frontend.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ import { casbinJsGetPermissionForUser } from '../src/frontend';

test('TestCasbinJsGetPermissionForUser', async () => {
const e = await newEnforcer('examples/rbac_model.conf', 'examples/rbac_with_hierarchy_policy.csv');
const a = await casbinJsGetPermissionForUser(e, 'alice');
const b = await casbinJsGetPermissionForUser(e, 'alice');
if (a !== b) {
throw new Error('Unexpected side affect.');
}
const received = JSON.parse(await casbinJsGetPermissionForUser(e, 'alice'));
const expectedModelStr = readFileSync('examples/rbac_model.conf').toString();
expect(received['m']).toBe(expectedModelStr.replace(/\n\n/g, '\n'));
Expand Down

0 comments on commit 98c11f1

Please sign in to comment.