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

41 lines
1.4 KiB
TypeScript
Raw Normal View History

2020-05-24 04:38:24 +05:30
import { ensureToken, recoverFromTokenError } from 'app/components/accounts/actions';
import { getActiveAccount } from 'app/components/accounts/reducer';
import { Store } from 'app/types';
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
*/
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');
2020-05-24 04:38:24 +05:30
if (!activeAccount || disableMiddleware || isRefreshTokenRequest) {
return Promise.resolve(req);
}
2020-05-24 04:38:24 +05:30
return dispatch(ensureToken()).then(() => req);
},
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);
}
2020-05-24 04:38:24 +05:30
return dispatch(recoverFromTokenError(resp)).then(restart);
},
};
}