Skip to article
Documentation

src/app/api/demo/view-as/route.ts

Linked repository file from this build.

import { clerkClient } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
import { z } from "zod";
import { apiRoute } from "@/lib/api-route";
import { getActor } from "@/lib/auth/server";
import { demoRoster } from "@/lib/auth/roster";
import { AccessError } from "@/lib/auth/scope";
const schema = z.object({ staffId: z.string() });
export const POST = apiRoute("Unable to switch demo account.", async (request) => {
  const actor = await getActor(request);
  if (
    !process.env.CLERK_SECRET_KEY?.startsWith("sk_test_") ||
    !demoRoster.some((entry) => entry.staffId === actor.staffId)
  )
    throw new AccessError("View as is available only to the development demo roster.");
  const { staffId } = schema.parse(await request.json());
  if (!demoRoster.some((entry) => entry.staffId === staffId))
    throw new AccessError("Choose a demo staff member.");
  const client = await clerkClient();
  const users = await client.users.getUserList({ externalId: [staffId], limit: 1 });
  const user = users.data[0];
  if (!user || user.publicMetadata.staffId !== staffId)
    throw new AccessError("This demo account is not provisioned.");
  const ticket = await client.signInTokens.createSignInToken({
    userId: user.id,
    expiresInSeconds: 60,
  });
  return NextResponse.json({ ticket: ticket.token }, { headers: { "Cache-Control": "no-store" } });
});