Skip to content
This repository has been archived by the owner on Oct 24, 2024. It is now read-only.

feat: allow staff to revalidate the homepage #213

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/lib/session-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import type { Session } from "next-auth";

type ValidationFailure = {
err: Error;
data: null;
};

type ValidationSuccess<T> = {
err: null;
data: T;
};

type Validated<T> = ValidationFailure | ValidationSuccess<T>;

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 } };
};
24 changes: 24 additions & 0 deletions src/pages/api/revalidate.ts
Original file line number Diff line number Diff line change
@@ -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();
}
}
Loading