import { fail, redirect } from "@sveltejs/kit"; function safeRedirectTo(searchParams) { const to = searchParams.get("redirectTo"); if (!to || typeof to !== "string") return "/items"; if (!to.startsWith("/") || to.startsWith("//")) return "/items"; return to; } const load = ({ url, locals }) => { if (locals.user) { throw redirect(303, safeRedirectTo(url.searchParams)); } }; const actions = { login: async ({ request, locals, url }) => { const data = await request.formData(); const email = data.get("email")?.trim() ?? ""; const password = data.get("password") ?? ""; if (!email || !password) { return fail(400, { error: "Email and password are required.", email }); } try { await locals.pb.collection("users").authWithPassword(email, password); } catch (err) { const message = err && typeof err === "object" && "message" in err ? String(err.message) : "Invalid email or password."; return fail(401, { error: message, email }); } const redirectTo = safeRedirectTo(url.searchParams); throw redirect(303, redirectTo); } }; export { actions, load };