@medusajs/medusa
Version:
Building blocks for digital commerce
39 lines • 1.91 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.ensurePublishableKeyAndSalesChannelMatch = ensurePublishableKeyAndSalesChannelMatch;
/**
* If a publishable key (PK) is passed in the header of the request AND
* the request carries a sales channel id param in the url or body,
* we check if the sales channel is valid for the key.
*
* If the request does not carry a sales channel id, we attempt to assign
* a sales channel associated with the PK.
*
* @throws If sales channel id is passed as a url or body param
* but that id is not in the scope defined by the PK from the header.
* If the PK is associated with multiple sales channels but no
* sales channel id is passed in the request.
*/
async function ensurePublishableKeyAndSalesChannelMatch(req, res, next) {
const pubKey = req.get("x-publishable-api-key");
if (pubKey) {
const pubKeySalesChannels = req.publishableApiKeyScopes?.sales_channel_ids ?? [];
const channelId = req.validatedBody?.sales_channel_id;
req.errors = req.errors ?? [];
if (pubKeySalesChannels.length) {
if (channelId && !pubKeySalesChannels.includes(channelId)) {
req.errors.push(`Sales channel ID in payload ${channelId} is not associated with the Publishable API Key in the header.`);
}
if (!channelId) {
if (pubKeySalesChannels.length > 1) {
req.errors.push(`Cannot assign sales channel to cart. The Publishable API Key in the header has multiple associated sales channels. Please provide a sales channel ID in the request body.`);
}
else {
req.validatedBody.sales_channel_id = pubKeySalesChannels[0];
}
}
}
}
next();
}
//# sourceMappingURL=ensure-pub-key-sales-channel-match.js.map
;