Skip to content

Commit 98c11f1

Browse files
authored
fix: fix CasbinJsGetPermissionForUser() (#251)
* 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>
1 parent 92f8d05 commit 98c11f1

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

src/frontend.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
// limitations under the License.
1414

1515
import { Enforcer } from './enforcer';
16+
import { deepCopy } from './util';
1617

1718
/**
1819
* Experiment!
@@ -41,7 +42,7 @@ export async function casbinJsGetPermissionForUser(e: Enforcer, user: string): P
4142
s += '[matchers]\n';
4243
s += `m = ${m.get('m')?.get('m')?.value.replace(/_/g, '.')}`;
4344
obj['m'] = s;
44-
obj['p'] = await e.getPolicy();
45+
obj['p'] = deepCopy(await e.getPolicy());
4546
for (const arr of obj['p']) {
4647
arr.splice(0, 0, 'p');
4748
}

src/util/util.ts

+12
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,17 @@ async function generatorRunAsync(iterator: Generator<any>): Promise<any> {
159159
}
160160
}
161161

162+
function deepCopy(obj: Array<any> | any): any {
163+
if (typeof obj !== 'object') return;
164+
const newObj: any = obj instanceof Array ? [] : {};
165+
for (const key in obj) {
166+
if (obj.hasOwnProperty(key)) {
167+
newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
168+
}
169+
}
170+
return newObj;
171+
}
172+
162173
export {
163174
escapeAssertion,
164175
removeComments,
@@ -175,4 +186,5 @@ export {
175186
getEvalValue,
176187
generatorRunSync,
177188
generatorRunAsync,
189+
deepCopy,
178190
};

test/frontend.test.ts

+5
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@ import { casbinJsGetPermissionForUser } from '../src/frontend';
1818

1919
test('TestCasbinJsGetPermissionForUser', async () => {
2020
const e = await newEnforcer('examples/rbac_model.conf', 'examples/rbac_with_hierarchy_policy.csv');
21+
const a = await casbinJsGetPermissionForUser(e, 'alice');
22+
const b = await casbinJsGetPermissionForUser(e, 'alice');
23+
if (a !== b) {
24+
throw new Error('Unexpected side affect.');
25+
}
2126
const received = JSON.parse(await casbinJsGetPermissionForUser(e, 'alice'));
2227
const expectedModelStr = readFileSync('examples/rbac_model.conf').toString();
2328
expect(received['m']).toBe(expectedModelStr.replace(/\n\n/g, '\n'));

0 commit comments

Comments
 (0)