fix(acl): refresh the page when the user's role is incorrect (#5821)

* fix(acl): refresh the page when the user's role is incorrect

* fix: refresh

* fix: test error
This commit is contained in:
chenos 2024-12-08 13:31:36 +08:00 committed by GitHub
parent 7668165841
commit 537bc23037
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 17 additions and 3 deletions

View File

@ -109,10 +109,15 @@ export class APIClient extends APIClientSDK {
// TODO(yangqia): improve error code and message
if (errs.find((error: { code?: string }) => error.code === 'ROLE_NOT_FOUND_ERR')) {
this.auth.setRole(null);
window.location.reload();
}
if (errs.find((error: { code?: string }) => error.code === 'TOKEN_INVALID')) {
this.auth.setToken(null);
}
if (errs.find((error: { code?: string }) => error.code === 'ROLE_NOT_FOUND_FOR_USER')) {
this.auth.setRole(null);
window.location.reload();
}
throw error;
},
);

View File

@ -7,10 +7,10 @@
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { vi } from 'vitest';
import Database from '@nocobase/database';
import UsersPlugin from '@nocobase/plugin-users';
import { MockServer } from '@nocobase/test';
import { vi } from 'vitest';
import { setCurrentRole } from '../middlewares/setCurrentRole';
import { prepareApp } from './prepare';
@ -67,7 +67,7 @@ describe('role', () => {
expect(ctx.state.currentRole).toBe('root');
});
it('should use default role when the role does not belong to the user', async () => {
it('should throw error', async () => {
ctx.state.currentUser = await db.getRepository('users').findOne({
appends: ['roles'],
});
@ -79,7 +79,10 @@ describe('role', () => {
const throwFn = vi.fn();
ctx.throw = throwFn;
await setCurrentRole(ctx, () => {});
expect(ctx.state.currentRole).toBe('root');
expect(throwFn).lastCalledWith(401, {
code: 'ROLE_NOT_FOUND_FOR_USER',
message: 'The role does not belong to the user',
});
});
it('should set role with anonymous', async () => {

View File

@ -50,6 +50,12 @@ export async function setCurrentRole(ctx: Context, next) {
// 1. If the X-Role is set, use the specified role
if (currentRole) {
role = userRoles.find((role) => role.name === currentRole)?.name;
if (!role) {
return ctx.throw(401, {
code: 'ROLE_NOT_FOUND_FOR_USER',
message: ctx.t('The role does not belong to the user', { ns: 'acl' }),
});
}
}
// 2. If the X-Role is not set, or the X-Role does not belong to the user, use the default role
if (!role) {