2019-12-07 21:02:00 +02:00
|
|
|
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/reducers';
|
2019-12-07 13:28:52 +02:00
|
|
|
|
|
|
|
import { changeLang } from './actions';
|
2016-08-07 22:17:58 +03:00
|
|
|
import bearerHeaderMiddleware from './middlewares/bearerHeaderMiddleware';
|
|
|
|
import refreshTokenMiddleware from './middlewares/refreshTokenMiddleware';
|
|
|
|
|
2019-12-07 13:28:52 +02:00
|
|
|
let promise: Promise<void>;
|
2016-08-09 22:17:49 +03:00
|
|
|
|
2016-05-10 08:17:40 +03:00
|
|
|
/**
|
|
|
|
* Initializes User state with the fresh data
|
|
|
|
*
|
2016-07-31 16:53:16 +03:00
|
|
|
* @param {object} store - redux store
|
2016-05-10 08:17:40 +03:00
|
|
|
*
|
2019-11-27 11:03:32 +02:00
|
|
|
* @returns {Promise<User>} - a promise, that resolves in User state
|
2016-05-10 08:17:40 +03:00
|
|
|
*/
|
2019-12-07 13:28:52 +02:00
|
|
|
export function factory(store: Store): Promise<void> {
|
2020-05-24 02:08:24 +03:00
|
|
|
if (promise) {
|
|
|
|
return promise;
|
|
|
|
}
|
2016-08-09 22:17:49 +03:00
|
|
|
|
2020-05-24 02:08:24 +03:00
|
|
|
request.addMiddleware(refreshTokenMiddleware(store));
|
|
|
|
request.addMiddleware(bearerHeaderMiddleware(store));
|
2016-08-07 22:17:58 +03:00
|
|
|
|
2020-05-24 02:08:24 +03:00
|
|
|
promise = Promise.resolve()
|
|
|
|
.then(() => store.dispatch(logoutStrangers()))
|
|
|
|
.then(async () => {
|
|
|
|
const activeAccount = getActiveAccount(store.getState());
|
2016-12-05 21:14:38 +02:00
|
|
|
|
2020-05-24 02:08:24 +03:00
|
|
|
if (activeAccount) {
|
|
|
|
// authorizing user if it is possible
|
|
|
|
await store.dispatch(authenticate(activeAccount));
|
2019-12-07 13:28:52 +02:00
|
|
|
|
2020-05-24 02:08:24 +03:00
|
|
|
return;
|
|
|
|
}
|
2016-12-05 21:14:38 +02:00
|
|
|
|
2020-05-24 02:08:24 +03:00
|
|
|
throw new Error('No active account found');
|
|
|
|
})
|
|
|
|
.catch(async () => {
|
|
|
|
// the user is guest or user authentication failed
|
|
|
|
const { user } = store.getState();
|
2016-12-05 21:14:38 +02:00
|
|
|
|
2020-05-24 02:08:24 +03:00
|
|
|
// auto-detect guest language
|
|
|
|
await store.dispatch(changeLang(user.lang));
|
|
|
|
});
|
2016-08-09 22:17:49 +03:00
|
|
|
|
2020-05-24 02:08:24 +03:00
|
|
|
return promise;
|
2016-05-10 08:17:40 +03:00
|
|
|
}
|