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