File size: 1,472 Bytes
815c966
69698fb
815c966
 
 
 
 
bfb06d5
 
 
 
 
 
 
815c966
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bfb06d5
 
815c966
bfb06d5
 
 
815c966
 
bfb06d5
 
69698fb
bfb06d5
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { type NextRequest, NextResponse } from "next/server";
import { setAdminSessionCookie, ADMIN_COOKIE } from "@/lib/admin-session-cookie";
import { backendUrl } from "@/lib/backend-url";

export const dynamic = "force-dynamic";
export const runtime = "nodejs";

function sessionValue(setCookie: string | null) {
  const pair = setCookie?.split(";")[0] ?? "";
  const [name, ...valueParts] = pair.split("=");
  if (name !== ADMIN_COOKIE || valueParts.length === 0) return null;
  return valueParts.join("=");
}

export async function POST(request: NextRequest) {
  let response: Response;
  try {
    response = await fetch(`${backendUrl()}/admin/login`, {
      method: "POST",
      body: await request.text(),
      headers: {
        "content-type": request.headers.get("content-type") ?? "application/json",
      },
    });
  } catch {
    return NextResponse.json(
      { detail: "Could not reach the backend admin login service." },
      { status: 502 }
    );
  }

  const body = response.ok ? JSON.stringify({ ok: true }) : await response.text();
  const nextResponse = new NextResponse(body, {
    status: response.status,
    headers: {
      "content-type": response.headers.get("content-type") ?? "application/json",
    },
  });

  const value = sessionValue(response.headers.get("set-cookie"));
  if (response.ok && value) {
    setAdminSessionCookie(nextResponse.headers, value, request.nextUrl.protocol === "https:");
  }

  return nextResponse;
}