-
Notifications
You must be signed in to change notification settings - Fork 81
/
authenticate.ts
63 lines (51 loc) · 1.64 KB
/
authenticate.ts
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import {ShopifyRestResources} from '@shopify/shopify-api';
import {adminClientFactory} from '../../../clients/admin';
import {BasicParams} from '../../../types';
import {
AppProxyContext,
AppProxyContextWithSession,
AuthenticateAppProxy,
} from './types';
export function authenticateAppProxyFactory<
Resources extends ShopifyRestResources,
>(params: BasicParams): AuthenticateAppProxy {
const {api, config, logger} = params;
return async function authenticate(
request,
): Promise<AppProxyContext | AppProxyContextWithSession<Resources>> {
logger.info('Authenticating app proxy request');
const {searchParams} = new URL(request.url);
const query = Object.fromEntries(searchParams.entries());
let isValid = false;
try {
isValid = await api.utils.validateHmac(query, {
signator: 'appProxy',
});
} catch (error) {
logger.info(error.message);
throw new Response(undefined, {status: 400, statusText: 'Bad Request'});
}
if (!isValid) {
logger.info('App proxy request has invalid signature');
throw new Response(undefined, {
status: 400,
statusText: 'Bad Request',
});
}
const shop = searchParams.get('shop')!;
const sessionId = api.session.getOfflineId(shop);
const session = await config.sessionStorage.loadSession(sessionId);
if (!session) {
const context: AppProxyContext = {
session: undefined,
admin: undefined,
};
return context;
}
const context: AppProxyContextWithSession<Resources> = {
session,
admin: adminClientFactory({params, session}),
};
return context;
};
}