UNPKG

@transferwise/approve-api-action-helpers

Version:

An http client that handles SCA protected requests gracefully

58 lines (49 loc) 1.61 kB
import { runFlow } from './authenticationFlow'; import { http } from './http'; export function create(config = {}) { return function request(url, params = {}) { return http(url, params) .then((response) => ({ response, metadata: { scaRequired: false } })) .catch((error) => { if (isSCARequired(error)) { const token = getOTTFromResponse(error.response); callback(config.onSCARequired); return runFlow({ token, flow: config.flow, mode: config.mode, approvalPageUrl: config.approvalPageUrl, }).then(() => { callback(config.onSCACompleted); const originalHeaders = params.headers || {}; const headers = { ...originalHeaders, 'X-2FA-APPROVAL': token, }; return http(url, { ...params, headers, }).then((response) => ({ response, metadata: { scaRequired: true } })); }); } throw error; }) .then((result) => (!params || !params.withMetadata ? result.response : result)); }; } function callback(function_ = () => {}) { function_(); } function isSCARequired(error) { if (!error || !error.response) { return false; } const token = getOTTFromResponse(error.response); const { status } = error.response; return (status === 403 || status === 400) && token; } function getOTTFromResponse(response) { return response && response.headers && response.headers.get ? response.headers.get('X-2FA-APPROVAL') : null; }