fix(acl): use default role when x-role does not belong to the current user (#4507)

* fix(acl): use default role when `x-role` does not belong to the current user

* fix: test
This commit is contained in:
YANG QIA 2024-05-29 11:53:44 +08:00 committed by GitHub
parent 818dd6f03e
commit 948a6345e0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 8 additions and 11 deletions

View File

@ -67,7 +67,7 @@ describe('role', () => {
expect(ctx.state.currentRole).toBe('root');
});
it('should throw 401', async () => {
it('should use default role when the role does not belong to the user', async () => {
ctx.state.currentUser = await db.getRepository('users').findOne({
appends: ['roles'],
});
@ -79,11 +79,7 @@ describe('role', () => {
const throwFn = vi.fn();
ctx.throw = throwFn;
await setCurrentRole(ctx, () => {});
expect(throwFn).lastCalledWith(401, {
code: 'ROLE_NOT_FOUND_ERR',
message: 'The user role does not exist. Please try signing in again',
});
expect(ctx.state.currentRole).not.toBeDefined();
expect(ctx.state.currentRole).toBe('root');
});
it('should set role with anonymous', async () => {

View File

@ -46,16 +46,17 @@ export async function setCurrentRole(ctx: Context, next) {
const userRoles = Array.from(rolesMap.values());
ctx.state.currentUser.roles = userRoles;
let role: string | undefined;
// 1. If the X-Role is set, use the specified role
if (currentRole) {
ctx.state.currentRole = userRoles.find((role) => role.name === currentRole)?.name;
role = userRoles.find((role) => role.name === currentRole)?.name;
}
// 2. If the X-Role is not set, use the default role
else {
// 2. If the X-Role is not set, or the X-Role does not belong to the user, use the default role
if (!role) {
const defaultRole = userRoles.find((role) => role?.rolesUsers?.default);
ctx.state.currentRole = (defaultRole || userRoles[0])?.name;
role = (defaultRole || userRoles[0])?.name;
}
ctx.state.currentRole = role;
if (!ctx.state.currentRole) {
return ctx.throw(401, {
code: 'ROLE_NOT_FOUND_ERR',