From 2d5640d5304f7218c8ae42faeb97114a1192d036 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EA=A6=8C=EA=A6=AB=EA=A6=B6=EA=A6=8F=EA=A7=80=EA=A6=A6?= =?UTF-8?q?=EA=A6=BF=EA=A6=A7=EA=A6=AE=EA=A6=91=EA=A6=A9=EA=A6=AD=EA=A7=80?= Date: Thu, 15 Sep 2022 21:38:13 +0800 Subject: Preparation for CDN-hosted version --- hooks/useAuthenticatedFetch.js | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 hooks/useAuthenticatedFetch.js (limited to 'hooks/useAuthenticatedFetch.js') diff --git a/hooks/useAuthenticatedFetch.js b/hooks/useAuthenticatedFetch.js new file mode 100644 index 0000000..e5f36a8 --- /dev/null +++ b/hooks/useAuthenticatedFetch.js @@ -0,0 +1,38 @@ +/** + * A hook that returns an auth-aware fetch function. + * @desc The returned fetch function that matches the browser's fetch API + * See: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API + * It will provide the following functionality: + * + * 1. Add a `X-Shopify-Access-Token` header to the request. + * 2. Check response for `X-Shopify-API-Request-Failure-Reauthorize` header. + * 3. Redirect the user to the reauthorization URL if the header is present. + * + * @returns {Function} fetch function + */ +function useAuthenticatedFetch() { + const app = useAppBridge(); + const fetchFunction = authenticatedFetch(app); + + return async (uri, options) => { + const response = await fetchFunction(uri, options); + checkHeadersForReauthorization(response.headers, app); + return response; + }; +} + +function checkHeadersForReauthorization(headers, app) { + if (headers.get("X-Shopify-API-Request-Failure-Reauthorize") === "1") { + const authUrlHeader = + headers.get("X-Shopify-API-Request-Failure-Reauthorize-Url") || + `/api/auth`; + + const redirect = Redirect.create(app); + redirect.dispatch( + Redirect.Action.REMOTE, + authUrlHeader.startsWith("/") + ? `https://${window.location.host}${authUrlHeader}` + : authUrlHeader + ); + } +} -- cgit v1.2.3