-
Notifications
You must be signed in to change notification settings - Fork 38
/
protectedFetch.js
40 lines (34 loc) · 1.2 KB
/
protectedFetch.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import {authenticatedFetch} from '@shopify/app-bridge-utils';
import {AuthCode} from '@shopify/app-bridge/actions';
function getAuthCode(appBridge) {
return new Promise((resolve, reject) => {
const unsubscribe = appBridge.subscribe(AuthCode.ActionType.RESPOND, (payload) => {
if (payload) {
resolve(payload);
} else {
reject("Failed to load");
}
unsubscribe();
});
appBridge.dispatch(AuthCode.request());
});
}
function invalidUserAccessTokenError(responseObject) {
return responseObject.headers.get("X-Shopify-Request-Auth-Code");
}
export default function protectedFetch(appBridge) {
const jwtFetch = authenticatedFetch(appBridge);
return async (uri, options) => {
const response = await jwtFetch(uri, options);
if (invalidUserAccessTokenError(response)) {
const { code, hmac, shop, timestamp } = await getAuthCode(appBridge);
const callback_uri = `auth/shopify/callback?code=${code}&hmac=${hmac}&shop=${shop}×tamp=${timestamp}`
const callback_response = await jwtFetch(callback_uri);
if (callback_response.status == 200) {
return jwtFetch(uri, options);
}
} else {
return response;
}
};
}