accounts-frontend/src/components/user/factory.js

47 lines
1.3 KiB
JavaScript
Raw Normal View History

2016-11-05 15:41:41 +05:30
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';
2016-08-10 00:47:49 +05:30
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) {
2016-08-10 00:47:49 +05:30
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));
});
2016-08-10 00:47:49 +05:30
return promise;
}