46 lines
1.6 KiB
TypeScript
46 lines
1.6 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { getPocketBaseConfig } from "@/config/services.config";
|
|
import { COOKIE_NAME, getCookieOptions, getHostFromRequest } from "@/app/lib/auth-cookie";
|
|
|
|
export async function POST(request: NextRequest) {
|
|
const body = await request.json().catch(() => ({}));
|
|
const identity = String(body?.identity || body?.email || "").trim();
|
|
const password = String(body?.password || "");
|
|
|
|
if (!identity || !password) {
|
|
return NextResponse.json({ ok: false, error: "Missing identity or password" }, { status: 400 });
|
|
}
|
|
|
|
const pb = getPocketBaseConfig();
|
|
const pbRes = await fetch(`${pb.url}/api/collections/${pb.usersCollection}/auth-with-password`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ identity, password }),
|
|
});
|
|
|
|
const pbData = await pbRes.json().catch(() => ({}));
|
|
if (!pbRes.ok || !pbData?.token || !pbData?.record?.id) {
|
|
return NextResponse.json(
|
|
{ ok: false, error: pbData?.message || "Login failed" },
|
|
{ status: pbRes.status || 401 }
|
|
);
|
|
}
|
|
|
|
const payload = JSON.stringify({
|
|
token: pbData.token,
|
|
userId: pbData.record.id,
|
|
email: pbData.record.email ?? identity,
|
|
});
|
|
const encoded = Buffer.from(payload, "utf-8").toString("base64url");
|
|
|
|
const res = NextResponse.json({
|
|
ok: true,
|
|
token: pbData.token,
|
|
record: pbData.record,
|
|
user: { id: pbData.record.id, email: pbData.record.email ?? identity },
|
|
});
|
|
res.cookies.set(COOKIE_NAME, encoded, getCookieOptions(false, getHostFromRequest(request)) as Record<string, string | number | boolean>);
|
|
return res;
|
|
}
|
|
|