55 lines
1.8 KiB
TypeScript
55 lines
1.8 KiB
TypeScript
import type { APIRoute } from "astro";
|
|
|
|
export const POST: APIRoute = async ({ request, cookies, redirect, locals }) => {
|
|
let username = "";
|
|
let password = "";
|
|
|
|
const contentType = request.headers.get("content-type") ?? "";
|
|
|
|
try {
|
|
if (contentType.includes("application/json")) {
|
|
const body = await request.json();
|
|
username = body.username ?? "";
|
|
password = body.password ?? "";
|
|
} else {
|
|
const formData = await request.formData();
|
|
username = formData.get("username")?.toString() ?? "";
|
|
password = formData.get("password")?.toString() ?? "";
|
|
}
|
|
} catch (err) {
|
|
console.error("Failed to parse login request body:", err);
|
|
return new Response(JSON.stringify({ error: "Invalid request body" }), {
|
|
status: 400,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
}
|
|
|
|
if (!username || !password) {
|
|
return new Response(JSON.stringify({ error: "Username and password are required" }), {
|
|
status: 400,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
}
|
|
|
|
try {
|
|
await locals.pb.collection("users").authWithPassword(username, password);
|
|
|
|
cookies.set("pb_auth", locals.pb.authStore.exportToCookie(), {
|
|
path: "/",
|
|
httpOnly: true,
|
|
sameSite: "lax",
|
|
maxAge: 60 * 60 * 24 * 7, // 1 week
|
|
});
|
|
|
|
return new Response(JSON.stringify({ success: true }), {
|
|
status: 200,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
} catch {
|
|
return new Response(JSON.stringify({ error: "Invalid credentials" }), {
|
|
status: 401,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
}
|
|
};
|