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

35 lines
959 B
TypeScript
Raw Normal View History

import { getActiveAccount } from 'app/components/accounts/reducer';
import { Store } from 'app/reducers';
import { Middleware } from 'app/services/request';
/**
* Applies Bearer header for all requests
*
* req.options.token is used to override current token.
* Pass null to disable bearer header at all
*
* @param {object} store - redux store
* @param {Function} store.getState
*
* @returns {object} - request middleware
*/
2019-12-07 16:58:52 +05:30
export default function bearerHeaderMiddleware(store: Store): Middleware {
2020-05-24 04:38:24 +05:30
return {
async before(req) {
const activeAccount = getActiveAccount(store.getState());
2016-11-05 15:41:41 +05:30
2020-05-24 04:38:24 +05:30
let { token = null } = activeAccount || {};
2020-05-24 04:38:24 +05:30
if (req.options.token || req.options.token === null) {
({ token } = req.options);
}
2020-05-24 04:38:24 +05:30
if (token) {
req.options.headers.Authorization = `Bearer ${token}`;
}
2020-05-24 04:38:24 +05:30
return req;
},
};
}