2019-11-27 14:33:32 +05:30
|
|
|
import {
|
|
|
|
ensureToken,
|
|
|
|
recoverFromTokenError,
|
2019-12-08 00:32:00 +05:30
|
|
|
} from 'app/components/accounts/actions';
|
|
|
|
import { getActiveAccount } from 'app/components/accounts/reducer';
|
|
|
|
import { Store } from 'app/reducers';
|
|
|
|
import { Middleware } from 'app/services/request';
|
2016-08-08 00:47:58 +05:30
|
|
|
|
|
|
|
/**
|
|
|
|
* Ensures, that all user's requests have fresh access token
|
|
|
|
*
|
|
|
|
* @param {object} store - redux store
|
2019-11-27 14:33:32 +05:30
|
|
|
* @param {Function} store.getState
|
|
|
|
* @param {Function} store.dispatch
|
2016-08-08 00:47:58 +05:30
|
|
|
*
|
2019-11-27 14:33:32 +05:30
|
|
|
* @returns {object} - request middleware
|
2016-08-08 00:47:58 +05:30
|
|
|
*/
|
2019-11-27 14:33:32 +05:30
|
|
|
export default function refreshTokenMiddleware({
|
|
|
|
dispatch,
|
|
|
|
getState,
|
2019-12-07 16:58:52 +05:30
|
|
|
}: Store): Middleware {
|
2019-11-27 14:33:32 +05:30
|
|
|
return {
|
2019-12-07 16:58:52 +05:30
|
|
|
async before(req) {
|
2019-11-27 14:33:32 +05:30
|
|
|
const activeAccount = getActiveAccount(getState());
|
|
|
|
const disableMiddleware =
|
|
|
|
!!req.options.token || req.options.token === null;
|
2016-11-05 15:41:41 +05:30
|
|
|
|
2019-11-27 14:33:32 +05:30
|
|
|
const isRefreshTokenRequest = req.url.includes('refresh-token');
|
2016-08-08 00:47:58 +05:30
|
|
|
|
2019-11-27 14:33:32 +05:30
|
|
|
if (!activeAccount || disableMiddleware || isRefreshTokenRequest) {
|
|
|
|
return Promise.resolve(req);
|
|
|
|
}
|
2016-08-08 00:47:58 +05:30
|
|
|
|
2019-11-27 14:33:32 +05:30
|
|
|
return dispatch(ensureToken()).then(() => req);
|
|
|
|
},
|
2016-08-08 00:47:58 +05:30
|
|
|
|
2019-12-07 16:58:52 +05:30
|
|
|
async catch(
|
|
|
|
resp: { status: number; message: string },
|
|
|
|
req,
|
|
|
|
restart,
|
|
|
|
): Promise<any> {
|
2019-11-27 14:33:32 +05:30
|
|
|
const disableMiddleware =
|
|
|
|
!!req.options.token || req.options.token === null;
|
2016-11-05 15:41:41 +05:30
|
|
|
|
2019-11-27 14:33:32 +05:30
|
|
|
if (disableMiddleware) {
|
|
|
|
return Promise.reject(resp);
|
|
|
|
}
|
2016-08-08 00:47:58 +05:30
|
|
|
|
2019-11-27 14:33:32 +05:30
|
|
|
return dispatch(recoverFromTokenError(resp)).then(restart);
|
|
|
|
},
|
|
|
|
};
|
2016-08-08 00:47:58 +05:30
|
|
|
}
|