accounts-frontend/packages/app/components/user/factory.ts

51 lines
1.5 KiB
TypeScript
Raw Permalink Normal View History

import { authenticate, logoutStrangers } from 'app/components/accounts/actions';
import { getActiveAccount } from 'app/components/accounts/reducer';
import request from 'app/services/request';
import { Store } from 'app/types';
2019-12-07 16:58:52 +05:30
import { changeLang } from './actions';
import bearerHeaderMiddleware from './middlewares/bearerHeaderMiddleware';
import refreshTokenMiddleware from './middlewares/refreshTokenMiddleware';
2019-12-07 16:58:52 +05:30
let promise: Promise<void>;
2016-08-10 00:47:49 +05:30
/**
* Initializes User state with the fresh data
*
* @param {object} store - redux store
*
* @returns {Promise<User>} - a promise, that resolves in User state
*/
2019-12-07 16:58:52 +05:30
export function factory(store: Store): Promise<void> {
2020-05-24 04:38:24 +05:30
if (promise) {
return promise;
}
2016-08-10 00:47:49 +05:30
2020-05-24 04:38:24 +05:30
request.addMiddleware(refreshTokenMiddleware(store));
request.addMiddleware(bearerHeaderMiddleware(store));
2020-05-24 04:38:24 +05:30
promise = Promise.resolve()
.then(() => store.dispatch(logoutStrangers()))
.then(async () => {
const activeAccount = getActiveAccount(store.getState());
2020-05-24 04:38:24 +05:30
if (activeAccount) {
// authorizing user if it is possible
await store.dispatch(authenticate(activeAccount));
2019-12-07 16:58:52 +05:30
2020-05-24 04:38:24 +05:30
return;
}
2020-05-24 04:38:24 +05:30
throw new Error('No active account found');
})
.catch(async () => {
// the user is guest or user authentication failed
const { user } = store.getState();
2020-05-24 04:38:24 +05:30
// auto-detect guest language
await store.dispatch(changeLang(user.lang));
});
2016-08-10 00:47:49 +05:30
2020-05-24 04:38:24 +05:30
return promise;
}