mirror of
https://github.com/elyby/accounts-frontend.git
synced 2024-11-06 08:11:20 +05:30
47 lines
1.3 KiB
JavaScript
47 lines
1.3 KiB
JavaScript
import { changeLang } from 'components/user/actions';
|
|
import { authenticate, logoutStrangers } from 'components/accounts/actions';
|
|
|
|
import request from 'services/request';
|
|
import bearerHeaderMiddleware from './middlewares/bearerHeaderMiddleware';
|
|
import refreshTokenMiddleware from './middlewares/refreshTokenMiddleware';
|
|
|
|
let promise;
|
|
|
|
/**
|
|
* Initializes User state with the fresh data
|
|
*
|
|
* @param {object} store - redux store
|
|
*
|
|
* @return {Promise<User>} - a promise, that resolves in User state
|
|
*/
|
|
export function factory(store) {
|
|
if (promise) {
|
|
return promise;
|
|
}
|
|
|
|
request.addMiddleware(refreshTokenMiddleware(store));
|
|
request.addMiddleware(bearerHeaderMiddleware(store));
|
|
|
|
promise = Promise.resolve()
|
|
.then(() => store.dispatch(logoutStrangers()))
|
|
.then(() => {
|
|
const {accounts} = store.getState();
|
|
|
|
if (accounts.active) {
|
|
// authorizing user if it is possible
|
|
return store.dispatch(authenticate(accounts.active));
|
|
}
|
|
|
|
return Promise.reject();
|
|
})
|
|
.catch(() => {
|
|
// the user is guest or user authentication failed
|
|
const {user} = store.getState();
|
|
|
|
// auto-detect guest language
|
|
return store.dispatch(changeLang(user.lang));
|
|
});
|
|
|
|
return promise;
|
|
}
|