fix(auth): user role not found (#2674)

This commit is contained in:
YANG QIA 2023-09-19 10:58:19 +08:00 committed by GitHub
parent 64dc385eb3
commit 4fffa07998
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 53 additions and 3 deletions

View File

@ -39,6 +39,20 @@ export class APIClient extends APIClientSDK {
});
super.interceptors();
this.useNotificationMiddleware();
this.axios.interceptors.response.use(
(response) => {
return response;
},
(error) => {
const errs = error?.response?.data?.errors || [{ message: 'Server error' }];
// Hard code here temporarily
// TODO(yangqia): improve error code and message
if (errs.find((error: { code?: string }) => error.code === 'ROLE_NOT_FOUND_ERR')) {
this.auth.setRole(null);
}
throw error;
},
);
}
useNotificationMiddleware() {

View File

@ -23,4 +23,40 @@ describe('APIClient', () => {
expect(apiClient.axios).toBe(instance);
});
});
test('should reset role when role is not found', async () => {
const instance = axios.create();
instance.interceptors.response.use(
(response) => response,
(error) => {
error = {
response: {
data: {
errors: [
{
code: 'ROLE_NOT_FOUND_ERR',
},
],
},
},
};
throw error;
},
);
const apiClient = new APIClient(instance);
apiClient.app = {} as any;
apiClient.auth.setRole('not-found');
expect(apiClient.auth.role).toBe('not-found');
try {
await apiClient.request({
method: 'GET',
url: '/api/test',
});
} catch (err) {
console.log(err);
expect(err).toBeDefined();
expect(err.response.data.errors[0].code).toBe('ROLE_NOT_FOUND_ERR');
}
expect(apiClient.auth.role).toBeFalsy();
});
});

View File

@ -67,7 +67,7 @@ describe('role', () => {
const throwFn = jest.fn();
ctx.throw = throwFn;
await setCurrentRole(ctx, () => {});
expect(throwFn).lastCalledWith(401, 'User role not found');
expect(throwFn).lastCalledWith(401, { code: 'ROLE_NOT_FOUND_ERR', message: 'The user role does not exist.' });
expect(ctx.state.currentRole).not.toBeDefined();
});

View File

@ -94,7 +94,7 @@ describe('actions', () => {
const rolesCheckResponse2 = (await loggedAgent.set('Accept', 'application/json').get('/roles:check')) as any;
expect(rolesCheckResponse2.status).toEqual(401);
expect(rolesCheckResponse2.body.errors[0].message).toEqual('User role not found');
expect(rolesCheckResponse2.body.errors[0].code).toEqual('ROLE_NOT_FOUND_ERR');
});
it('should destroy through table record when destroy role', async () => {

View File

@ -28,7 +28,7 @@ export async function setCurrentRole(ctx: Context, next) {
}
if (!ctx.state.currentRole) {
return ctx.throw(401, 'User role not found');
return ctx.throw(401, { code: 'ROLE_NOT_FOUND_ERR', message: 'The user role does not exist.' });
}
await next();