mirror of
https://gitee.com/nocobase/nocobase.git
synced 2024-12-02 20:27:49 +08:00
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:
parent
818dd6f03e
commit
948a6345e0
@ -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 () => {
|
||||
|
@ -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',
|
||||
|
Loading…
Reference in New Issue
Block a user