| | import crypto from "crypto"; |
| | import { getClient } from "./api"; |
| | import { CMS_LANG, CMS_CHANNEL } from "./constants"; |
| |
|
| | |
| | export function generatePreviewKey() { |
| | |
| | const str = `-1_${process.env.AGILITY_CMS_SECURITY_KEY}_Preview`; |
| |
|
| | |
| | let data = []; |
| | for (var i = 0; i < str.length; ++i) { |
| | data.push(str.charCodeAt(i)); |
| | data.push(0); |
| | } |
| |
|
| | |
| | const strBuffer = Buffer.from(data); |
| | |
| | const previewKey = crypto |
| | .createHash("sha512") |
| | .update(strBuffer) |
| | .digest("base64"); |
| |
|
| | return previewKey; |
| | } |
| |
|
| | |
| | export async function validateSlugForPreview({ slug, contentID }) { |
| | |
| | if (slug === `/`) { |
| | return { |
| | error: false, |
| | message: null, |
| | slug: `/`, |
| | }; |
| | } |
| |
|
| | const client = getClient(true); |
| | |
| | const sitemapFlat = await client.getSitemapFlat({ |
| | channelName: CMS_CHANNEL, |
| | languageCode: CMS_LANG, |
| | }); |
| |
|
| | let sitemapNode = null; |
| |
|
| | if (!contentID) { |
| | |
| | sitemapNode = sitemapFlat[slug]; |
| | } else { |
| | console.log(contentID); |
| | |
| | slug = Object.keys(sitemapFlat).find((key) => { |
| | const node = sitemapFlat[key]; |
| | if (node.contentID === contentID) { |
| | return node; |
| | } |
| | return false; |
| | }); |
| |
|
| | sitemapNode = sitemapFlat[slug]; |
| | } |
| |
|
| | if (!sitemapNode) { |
| | return { |
| | error: true, |
| | message: `Invalid page. '${slug}' was not found in the sitemap. Are you trying to preview a Dynamic Page Item? If so, ensure you have your List Preview Page, Item Preview Page, and Item Preview Query String Parameter set (contentid) .`, |
| | slug: null, |
| | }; |
| | } |
| |
|
| | return { |
| | error: false, |
| | message: null, |
| | slug: sitemapNode.path, |
| | }; |
| | } |
| |
|
| | |
| | export async function validatePreview({ agilityPreviewKey, slug, contentID }) { |
| | |
| | if (!agilityPreviewKey) { |
| | return { |
| | error: true, |
| | message: `Missing agilitypreviewkey.`, |
| | }; |
| | } |
| |
|
| | |
| | if (agilityPreviewKey.includes(` `)) { |
| | agilityPreviewKey = agilityPreviewKey.split(` `).join(`+`); |
| | } |
| |
|
| | |
| | const correctPreviewKey = generatePreviewKey(); |
| |
|
| | if (agilityPreviewKey !== correctPreviewKey) { |
| | return { |
| | error: true, |
| | message: `Invalid agilitypreviewkey.`, |
| | |
| | }; |
| | } |
| |
|
| | const validateSlugResponse = await validateSlugForPreview({ |
| | slug, |
| | contentID, |
| | }); |
| |
|
| | if (validateSlugResponse.error) { |
| | |
| | return validateSlugResponse; |
| | } |
| |
|
| | |
| | return { |
| | error: false, |
| | message: null, |
| | slug: validateSlugResponse.slug, |
| | }; |
| | } |
| |
|