-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthorisationMiddleware.tsx
More file actions
55 lines (49 loc) · 1.66 KB
/
authorisationMiddleware.tsx
File metadata and controls
55 lines (49 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { createListenerMiddleware } from '@reduxjs/toolkit';
import { TokenUpdatedType } from '../actions/actions.types';
import { setAuthorisation, setIsAdminMode } from '../slices/authorisationSlice';
import { RootState, StorageRegistry } from '../store';
export const createAuthListenerMiddleware = (
getUserRoleFn: () => string | undefined,
storageRegistryDict: StorageRegistry
) => {
const middleware = createListenerMiddleware();
middleware.startListening({
type: TokenUpdatedType,
effect: async (_, listenerApi) => {
const state = listenerApi.getState() as RootState;
const privilegedRoles = state.config.settings.privilegedRoles;
const role = getUserRoleFn();
if (typeof role === 'string')
listenerApi.dispatch(
setAuthorisation({
role,
isAdminUser: privilegedRoles.includes(role),
})
);
},
});
middleware.startListening({
actionCreator: setIsAdminMode,
effect: async (_, listenerApi) => {
const state = listenerApi.getState() as RootState;
if (state.authorisation.isAdminUser) {
storageRegistryDict.authorisation.save(state.authorisation.isAdminMode);
} else {
storageRegistryDict.authorisation.clear();
}
},
});
middleware.startListening({
actionCreator: setAuthorisation,
effect: async (_, listenerApi) => {
const { isAdminUser, isAdminMode } = (listenerApi.getState() as RootState)
.authorisation;
if (!isAdminUser) {
storageRegistryDict.authorisation.clear();
} else {
storageRegistryDict.authorisation.save(isAdminMode);
}
},
});
return middleware;
};