@shopify/shopify-app-remix
Version:
Shopify Remix - to simplify the building of Shopify Apps with Remix
91 lines (87 loc) • 3.38 kB
JavaScript
;
var shopifyApi = require('@shopify/shopify-api');
var factory = require('../../clients/admin/factory.js');
require('@remix-run/server-runtime');
var handleClientError = require('../admin/helpers/handle-client-error.js');
var ensureValidOfflineSession = require('../../helpers/ensure-valid-offline-session.js');
require('../../types.js');
function authenticateWebhookFactory(params) {
const { api, logger } = params;
return async function authenticate(request) {
if (request.method !== 'POST') {
logger.debug('Received a non-POST request for a webhook. Only POST requests are allowed.', { url: request.url, method: request.method });
throw new Response(undefined, {
status: 405,
statusText: 'Method not allowed',
});
}
const rawBody = await request.text();
const check = await api.webhooks.validate({
rawBody,
rawRequest: request,
});
if (!check.valid) {
if (check.reason === shopifyApi.WebhookValidationErrorReason.InvalidHmac) {
logger.debug('Webhook HMAC validation failed', check);
throw new Response(undefined, {
status: 401,
statusText: 'Unauthorized',
});
}
else {
logger.debug('Webhook validation failed', check);
throw new Response(undefined, { status: 400, statusText: 'Bad Request' });
}
}
const session = await ensureValidOfflineSession.ensureValidOfflineSession(params, check.domain);
let webhookContext;
if (check.webhookType === shopifyApi.WebhookType.Webhooks) {
webhookContext = {
apiVersion: check.apiVersion,
shop: check.domain,
topic: check.topic,
webhookId: check.webhookId,
payload: JSON.parse(rawBody),
subTopic: check.subTopic || undefined,
session: undefined,
admin: undefined,
webhookType: check.webhookType,
name: check.name,
triggeredAt: check.triggeredAt,
eventId: check.eventId,
};
}
else {
webhookContext = {
apiVersion: check.apiVersion,
shop: check.domain,
topic: check.topic,
webhookId: check.webhookId,
payload: JSON.parse(rawBody),
session: undefined,
admin: undefined,
webhookType: check.webhookType,
handle: check.handle,
action: check.action,
resourceId: check.resourceId,
triggeredAt: check.triggeredAt,
eventId: check.eventId,
};
}
if (!session) {
return webhookContext;
}
const admin = factory.adminClientFactory({
params,
session,
handleClientError: handleClientError.handleClientErrorFactory({ request }),
});
return {
...webhookContext,
session,
admin,
};
};
}
exports.authenticateWebhookFactory = authenticateWebhookFactory;
//# sourceMappingURL=authenticate.js.map