accounts-frontend/packages/app/components/user/middlewares/refreshTokenMiddleware.ts

53 lines
1.3 KiB
TypeScript
Raw Normal View History

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