2016-11-05 15:41:41 +05:30
|
|
|
import { changeLang } from 'components/user/actions';
|
|
|
|
import { authenticate } from 'components/accounts/actions';
|
2016-05-10 10:47:40 +05:30
|
|
|
|
2016-08-08 00:47:58 +05:30
|
|
|
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;
|
|
|
|
|
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
|
|
|
*
|
2016-08-08 00:47:58 +05:30
|
|
|
* @return {Promise} - a promise, that resolves in User state
|
2016-05-10 10:47:40 +05:30
|
|
|
*/
|
|
|
|
export function factory(store) {
|
2016-08-10 00:47:49 +05:30
|
|
|
if (promise) {
|
|
|
|
return promise;
|
|
|
|
}
|
|
|
|
|
2016-08-08 00:47:58 +05:30
|
|
|
request.addMiddleware(refreshTokenMiddleware(store));
|
|
|
|
request.addMiddleware(bearerHeaderMiddleware(store));
|
|
|
|
|
2016-11-20 15:06:15 +05:30
|
|
|
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) {
|
2016-05-10 10:47:40 +05:30
|
|
|
// authorizing user if it is possible
|
2016-11-20 15:06:15 +05:30
|
|
|
return store.dispatch(authenticate(accounts.active || user));
|
2016-05-10 10:47:40 +05:30
|
|
|
}
|
2016-05-20 01:11:43 +05:30
|
|
|
|
2016-11-20 15:06:15 +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-05-10 10:47:40 +05:30
|
|
|
});
|
2016-08-10 00:47:49 +05:30
|
|
|
|
|
|
|
return promise;
|
2016-05-10 10:47:40 +05:30
|
|
|
}
|