2020-05-24 04:38:24 +05:30
|
|
|
import { ensureToken, recoverFromTokenError } from 'app/components/accounts/actions';
|
2019-12-08 00:32:00 +05:30
|
|
|
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
|
|
|
*/
|
2020-05-24 04:38:24 +05:30
|
|
|
export default function refreshTokenMiddleware({ dispatch, getState }: Store): Middleware {
|
|
|
|
return {
|
|
|
|
async before(req) {
|
|
|
|
const activeAccount = getActiveAccount(getState());
|
|
|
|
const disableMiddleware = !!req.options.token || req.options.token === null;
|
2016-11-05 15:41:41 +05:30
|
|
|
|
2020-05-24 04:38:24 +05:30
|
|
|
const isRefreshTokenRequest = req.url.includes('refresh-token');
|
2016-08-08 00:47:58 +05:30
|
|
|
|
2020-05-24 04:38:24 +05:30
|
|
|
if (!activeAccount || disableMiddleware || isRefreshTokenRequest) {
|
|
|
|
return Promise.resolve(req);
|
|
|
|
}
|
2016-08-08 00:47:58 +05:30
|
|
|
|
2020-05-24 04:38:24 +05:30
|
|
|
return dispatch(ensureToken()).then(() => req);
|
|
|
|
},
|
2016-08-08 00:47:58 +05:30
|
|
|
|
2020-05-24 04:38:24 +05:30
|
|
|
async catch(resp: { status: number; message: string }, req, restart): Promise<any> {
|
|
|
|
const disableMiddleware = !!req.options.token || req.options.token === null;
|
2016-11-05 15:41:41 +05:30
|
|
|
|
2020-05-24 04:38:24 +05:30
|
|
|
if (disableMiddleware) {
|
|
|
|
return Promise.reject(resp);
|
|
|
|
}
|
2016-08-08 00:47:58 +05:30
|
|
|
|
2020-05-24 04:38:24 +05:30
|
|
|
return dispatch(recoverFromTokenError(resp)).then(restart);
|
|
|
|
},
|
|
|
|
};
|
2016-08-08 00:47:58 +05:30
|
|
|
}
|