accounts-frontend/src/components/user/middlewares/bearerHeaderMiddleware.js

39 lines
992 B
JavaScript
Raw Normal View History

// @flow
import { getActiveAccount } from 'components/accounts/reducer';
/**
* 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
*
* @return {object} - request middleware
*/
export default function bearerHeaderMiddleware(store: { getState: () => Object }) {
return {
before<T: {
options: {
token?: ?string,
headers: Object,
}
}>(req: T): T {
const activeAccount = getActiveAccount(store.getState());
2016-11-05 15:41:41 +05:30
let {token} = activeAccount || {};
if (req.options.token || req.options.token === null) {
token = req.options.token;
}
if (token) {
req.options.headers.Authorization = `Bearer ${token}`;
}
return req;
}
};
}