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';
|
2017-12-31 00:34:31 +05:30
|
|
|
|
2016-08-08 00:47:58 +05:30
|
|
|
/**
|
|
|
|
* Applies Bearer header for all requests
|
|
|
|
*
|
2016-12-13 01:37:49 +05:30
|
|
|
* req.options.token is used to override current token.
|
|
|
|
* Pass null to disable bearer header at all
|
|
|
|
*
|
2016-08-08 00:47:58 +05:30
|
|
|
* @param {object} store - redux store
|
2019-11-27 14:33:32 +05:30
|
|
|
* @param {Function} store.getState
|
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
|
|
|
*/
|
2019-12-07 16:58:52 +05:30
|
|
|
export default function bearerHeaderMiddleware(store: Store): Middleware {
|
2019-11-27 14:33:32 +05:30
|
|
|
return {
|
2019-12-07 16:58:52 +05:30
|
|
|
async before(req) {
|
2019-11-27 14:33:32 +05:30
|
|
|
const activeAccount = getActiveAccount(store.getState());
|
2016-11-05 15:41:41 +05:30
|
|
|
|
2019-12-07 16:58:52 +05:30
|
|
|
let { token = null } = activeAccount || {};
|
2016-10-30 17:42:49 +05:30
|
|
|
|
2019-11-27 14:33:32 +05:30
|
|
|
if (req.options.token || req.options.token === null) {
|
2019-12-07 16:58:52 +05:30
|
|
|
({ token } = req.options);
|
2019-11-27 14:33:32 +05:30
|
|
|
}
|
2016-08-08 00:47:58 +05:30
|
|
|
|
2019-11-27 14:33:32 +05:30
|
|
|
if (token) {
|
|
|
|
req.options.headers.Authorization = `Bearer ${token}`;
|
|
|
|
}
|
2016-08-08 00:47:58 +05:30
|
|
|
|
2019-11-27 14:33:32 +05:30
|
|
|
return req;
|
|
|
|
},
|
|
|
|
};
|
2016-08-08 00:47:58 +05:30
|
|
|
}
|