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

44 lines
1.2 KiB
JavaScript
Raw Normal View History

2016-11-05 15:41:41 +05:30
import { changeLang } from 'components/user/actions';
import { authenticate } 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} - 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(() => {
2016-11-05 15:41:41 +05:30
const {user, accounts} = store.getState();
2016-05-20 01:11:43 +05:30
2016-11-05 15:41:41 +05:30
if (accounts.active || user.token) {
// authorizing user if it is possible
return store.dispatch(authenticate(accounts.active || user));
}
2016-05-20 01:11:43 +05:30
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;
}