2016-12-06 00:44:38 +05:30
|
|
|
import { authenticate, logoutStrangers } from 'components/accounts/actions';
|
2017-12-31 00:34:31 +05:30
|
|
|
import { getActiveAccount } from 'components/accounts/reducer';
|
2016-08-08 00:47:58 +05:30
|
|
|
import request from 'services/request';
|
2019-12-07 16:58:52 +05:30
|
|
|
import { Store } from 'reducers';
|
|
|
|
|
|
|
|
import { changeLang } from './actions';
|
2016-08-08 00:47:58 +05:30
|
|
|
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
|
|
|
|
2016-05-10 10:47:40 +05:30
|
|
|
/**
|
|
|
|
* Initializes User state with the fresh data
|
|
|
|
*
|
2016-07-31 19:23:16 +05:30
|
|
|
* @param {object} store - redux store
|
2016-05-10 10:47:40 +05:30
|
|
|
*
|
2019-11-27 14:33:32 +05:30
|
|
|
* @returns {Promise<User>} - a promise, that resolves in User state
|
2016-05-10 10:47:40 +05:30
|
|
|
*/
|
2019-12-07 16:58:52 +05:30
|
|
|
export function factory(store: Store): Promise<void> {
|
2019-11-27 14:33:32 +05:30
|
|
|
if (promise) {
|
|
|
|
return promise;
|
|
|
|
}
|
2016-08-10 00:47:49 +05:30
|
|
|
|
2019-11-27 14:33:32 +05:30
|
|
|
request.addMiddleware(refreshTokenMiddleware(store));
|
|
|
|
request.addMiddleware(bearerHeaderMiddleware(store));
|
2016-08-08 00:47:58 +05:30
|
|
|
|
2019-11-27 14:33:32 +05:30
|
|
|
promise = Promise.resolve()
|
|
|
|
.then(() => store.dispatch(logoutStrangers()))
|
2019-12-07 16:58:52 +05:30
|
|
|
.then(async () => {
|
2019-11-27 14:33:32 +05:30
|
|
|
const activeAccount = getActiveAccount(store.getState());
|
2016-12-06 00:44:38 +05:30
|
|
|
|
2019-11-27 14:33:32 +05:30
|
|
|
if (activeAccount) {
|
|
|
|
// authorizing user if it is possible
|
2019-12-07 16:58:52 +05:30
|
|
|
await store.dispatch(authenticate(activeAccount));
|
|
|
|
|
|
|
|
return;
|
2019-11-27 14:33:32 +05:30
|
|
|
}
|
2016-12-06 00:44:38 +05:30
|
|
|
|
2019-11-27 14:33:32 +05:30
|
|
|
return Promise.reject();
|
|
|
|
})
|
2019-12-07 16:58:52 +05:30
|
|
|
.catch(async () => {
|
2019-11-27 14:33:32 +05:30
|
|
|
// the user is guest or user authentication failed
|
|
|
|
const { user } = store.getState();
|
2016-12-06 00:44:38 +05:30
|
|
|
|
2019-11-27 14:33:32 +05:30
|
|
|
// auto-detect guest language
|
2019-12-07 16:58:52 +05:30
|
|
|
await store.dispatch(changeLang(user.lang));
|
2019-11-27 14:33:32 +05:30
|
|
|
});
|
2016-08-10 00:47:49 +05:30
|
|
|
|
2019-11-27 14:33:32 +05:30
|
|
|
return promise;
|
2016-05-10 10:47:40 +05:30
|
|
|
}
|