From 189511fed7758cfba99c3d0e848eeba63ca16b60 Mon Sep 17 00:00:00 2001 From: Oliver Eyton-Williams Date: Fri, 26 Jan 2024 16:00:06 +0100 Subject: [PATCH] feat: allow staff to revalidate --- src/lib/session-utils.ts | 26 ++++++++++++++++++++++++++ src/pages/api/revalidate.ts | 24 ++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 src/lib/session-utils.ts create mode 100644 src/pages/api/revalidate.ts diff --git a/src/lib/session-utils.ts b/src/lib/session-utils.ts new file mode 100644 index 0000000..7e220eb --- /dev/null +++ b/src/lib/session-utils.ts @@ -0,0 +1,26 @@ +import type { Session } from "next-auth"; + +type ValidationFailure = { + err: Error; + data: null; +}; + +type ValidationSuccess = { + err: null; + data: T; +}; + +type Validated = ValidationFailure | ValidationSuccess; + +export const isStaff = (email?: string): boolean => + !!email && email.endsWith("@freecodecamp.org"); + +export const getEmailFromSession = ( + session: Session | null +): Validated<{ email: string }> => { + if (!session) return { err: Error("No session"), data: null }; + if (!session.user) return { err: Error("No user"), data: null }; + if (!session.user.email) return { err: Error("No email"), data: null }; + + return { err: null, data: { email: session.user.email } }; +}; \ No newline at end of file diff --git a/src/pages/api/revalidate.ts b/src/pages/api/revalidate.ts new file mode 100644 index 0000000..f3824f9 --- /dev/null +++ b/src/pages/api/revalidate.ts @@ -0,0 +1,24 @@ +import { getServerSession } from "next-auth/next"; + +import { getEmailFromSession, isStaff } from "@/lib/session-utils"; +import { authOptions } from "@/pages/api/auth/[...nextauth]"; +import type { NextApiRequest, NextApiResponse } from "next"; + +export default async function handler( + req: NextApiRequest, + res: NextApiResponse +) { + const session = await getServerSession(req, res, authOptions); + const { email } = getEmailFromSession(session).data ?? {}; + + if (isStaff(email)) { + try { + await res.revalidate("/"); + return res.json({ revalidated: true }); + } catch (err) { + return res.status(500).json({ message: "Could not revalidate" }); + } + } else { + res.status(403).end(); + } +}