2016-11-05 15:41:41 +05:30
|
|
|
import { changeLang } from 'components/user/actions';
|
2016-12-06 00:44:38 +05:30
|
|
|
import { authenticate, logoutStrangers } 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-12-07 02:38:51 +05:30
|
|
|
* @return {Promise<User>} - 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-12-06 00:44:38 +05:30
|
|
|
promise = Promise.resolve()
|
|
|
|
.then(() => store.dispatch(logoutStrangers()))
|
|
|
|
.then(() => {
|
2017-03-29 10:20:15 +05:30
|
|
|
const {accounts} = store.getState();
|
2016-12-06 00:44:38 +05:30
|
|
|
|
2017-03-29 10:20:15 +05:30
|
|
|
if (accounts.active) {
|
2016-12-06 00:44:38 +05:30
|
|
|
// authorizing user if it is possible
|
2017-03-29 10:20:15 +05:30
|
|
|
return store.dispatch(authenticate(accounts.active));
|
2016-12-06 00:44:38 +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;
|
2016-05-10 10:47:40 +05:30
|
|
|
}
|