mirror of
https://github.com/Tria-plc/emaui.git
synced 2026-08-26 13:02:50 +00:00
60 lines
1.7 KiB
TypeScript
60 lines
1.7 KiB
TypeScript
import { configureStore } from '@reduxjs/toolkit';
|
|
import {
|
|
baseApi,
|
|
configureSessionScope,
|
|
configureTokenRefresh,
|
|
} from '@ema-platform/api';
|
|
import {
|
|
authReducer,
|
|
signupReducer,
|
|
configureAuthStorage,
|
|
authStorage,
|
|
refreshAccessToken,
|
|
logout,
|
|
setToken,
|
|
} from '@ema-platform/auth';
|
|
import type { AuthUser, CurrentProfile } from '@ema-platform/auth';
|
|
import { preferencesReducer } from './preferences.slice';
|
|
|
|
configureAuthStorage('ema-backoffice', true);
|
|
// Cookies are shared across ports on localhost, so the API layer must be told
|
|
// which app it belongs to — otherwise it reads the portal's token.
|
|
configureSessionScope('ema-backoffice');
|
|
|
|
const preloadedAuth = (() => {
|
|
const token = authStorage.getToken();
|
|
const user = authStorage.getUser<AuthUser>();
|
|
const profile = authStorage.getProfile<CurrentProfile>();
|
|
if (token && user) {
|
|
return { token, user, isAuthenticated: true, currentProfile: profile ?? null };
|
|
}
|
|
return undefined;
|
|
})();
|
|
|
|
export const store = configureStore({
|
|
reducer: {
|
|
auth: authReducer,
|
|
signup: signupReducer,
|
|
preferences: preferencesReducer,
|
|
[baseApi.reducerPath]: baseApi.reducer,
|
|
},
|
|
preloadedState: preloadedAuth ? { auth: preloadedAuth } : undefined,
|
|
middleware: (getDefaultMiddleware) =>
|
|
getDefaultMiddleware().concat(baseApi.middleware),
|
|
});
|
|
|
|
configureTokenRefresh({
|
|
onTokenExpired: async () => {
|
|
const token = await refreshAccessToken();
|
|
store.dispatch(setToken(token));
|
|
return token;
|
|
},
|
|
onAuthFailure: () => {
|
|
store.dispatch(logout());
|
|
window.location.href = '/';
|
|
},
|
|
});
|
|
|
|
export type RootState = ReturnType<typeof store.getState>;
|
|
export type AppDispatch = typeof store.dispatch;
|