2017-12-31 00:34:31 +05:30
|
|
|
// @flow
|
|
|
|
import { ensureToken, recoverFromTokenError } from 'components/accounts/actions';
|
|
|
|
import { getActiveAccount } from 'components/accounts/reducer';
|
2016-08-08 00:47:58 +05:30
|
|
|
|
|
|
|
/**
|
|
|
|
* Ensures, that all user's requests have fresh access token
|
|
|
|
*
|
|
|
|
* @param {object} store - redux store
|
|
|
|
* @param {function} store.getState
|
|
|
|
* @param {function} store.dispatch
|
|
|
|
*
|
|
|
|
* @return {object} - request middleware
|
|
|
|
*/
|
2017-12-31 00:34:31 +05:30
|
|
|
export default function refreshTokenMiddleware({dispatch, getState}: {dispatch: (Object) => *, getState: () => Object}) {
|
2016-08-08 00:47:58 +05:30
|
|
|
return {
|
2017-12-31 00:34:31 +05:30
|
|
|
before<T: {options: {token?: string}, url: string}>(req: T): Promise<T> {
|
|
|
|
const activeAccount = getActiveAccount(getState());
|
|
|
|
const disableMiddleware = !!req.options.token || req.options.token === null;
|
2016-11-05 15:41:41 +05:30
|
|
|
|
2016-10-30 17:42:49 +05:30
|
|
|
const isRefreshTokenRequest = req.url.includes('refresh-token');
|
2016-08-08 00:47:58 +05:30
|
|
|
|
2017-12-31 00:34:31 +05:30
|
|
|
if (!activeAccount || disableMiddleware || isRefreshTokenRequest) {
|
2017-01-06 11:04:39 +05:30
|
|
|
return Promise.resolve(req);
|
2016-08-08 00:47:58 +05:30
|
|
|
}
|
|
|
|
|
2017-12-31 00:34:31 +05:30
|
|
|
return dispatch(ensureToken()).then(() => req);
|
2016-08-08 00:47:58 +05:30
|
|
|
},
|
|
|
|
|
2017-12-31 00:34:31 +05:30
|
|
|
catch(resp: {status: number, message: string}, req: {options: { token?: string}}, restart: () => Promise<mixed>): Promise<*> {
|
|
|
|
const disableMiddleware = !!req.options.token || req.options.token === null;
|
2016-11-05 15:41:41 +05:30
|
|
|
|
2017-12-31 00:34:31 +05:30
|
|
|
if (disableMiddleware) {
|
|
|
|
return Promise.reject(resp);
|
2016-08-08 00:47:58 +05:30
|
|
|
}
|
|
|
|
|
2017-12-31 00:34:31 +05:30
|
|
|
return dispatch(recoverFromTokenError(resp)).then(restart);
|
2016-08-08 00:47:58 +05:30
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|