63 lines
2.2 KiB
TypeScript
63 lines
2.2 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 email = String(body?.email || "").trim();
|
|
const password = String(body?.password || "");
|
|
const passwordConfirm = String(body?.passwordConfirm || "");
|
|
|
|
if (!email || !password || !passwordConfirm) {
|
|
return NextResponse.json(
|
|
{ ok: false, error: "Missing email/password/passwordConfirm" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const pb = getPocketBaseConfig();
|
|
const createRes = await fetch(`${pb.url}/api/collections/${pb.usersCollection}/records`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ email, password, passwordConfirm }),
|
|
});
|
|
|
|
const createData = await createRes.json().catch(() => ({}));
|
|
if (!createRes.ok) {
|
|
return NextResponse.json(
|
|
{ ok: false, error: createData?.message || "Register failed" },
|
|
{ status: createRes.status || 400 }
|
|
);
|
|
}
|
|
|
|
const loginRes = await fetch(`${pb.url}/api/collections/${pb.usersCollection}/auth-with-password`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ identity: email, password }),
|
|
});
|
|
const loginData = await loginRes.json().catch(() => ({}));
|
|
if (!loginRes.ok || !loginData?.token || !loginData?.record?.id) {
|
|
return NextResponse.json(
|
|
{ ok: false, error: loginData?.message || "Auto login failed after register" },
|
|
{ status: loginRes.status || 401 }
|
|
);
|
|
}
|
|
|
|
const payload = JSON.stringify({
|
|
token: loginData.token,
|
|
userId: loginData.record.id,
|
|
email: loginData.record.email ?? email,
|
|
});
|
|
const encoded = Buffer.from(payload, "utf-8").toString("base64url");
|
|
|
|
const res = NextResponse.json({
|
|
ok: true,
|
|
token: loginData.token,
|
|
record: loginData.record,
|
|
user: { id: loginData.record.id, email: loginData.record.email ?? email },
|
|
});
|
|
res.cookies.set(COOKIE_NAME, encoded, getCookieOptions(false, getHostFromRequest(request)) as Record<string, string | number | boolean>);
|
|
return res;
|
|
}
|
|
|