import { SESSION_COOKIE_NAME } from "../auth/token"; import { tokenLifetimes } from "../auth/types"; import { request } from "../request"; import { html, redirect, render } from "../request/util"; import type { Call, Result, Route } from "../types"; const loginHandler = async (call: Call): Promise => { if (call.method === "GET") { const c = await render("basic/login", {}); return html(c); } // POST - handle login const { email, password } = call.request.body; if (!email || !password) { const c = await render("basic/login", { error: "Email and password are required", email, }); return html(c); } const result = await request.auth.login(email, password, "cookie", { userAgent: call.request.get("User-Agent"), ipAddress: call.request.ip, }); if (!result.success) { const c = await render("basic/login", { error: result.error, email, }); return html(c); } // Success - set cookie and redirect to home const redirectResult = redirect("/"); redirectResult.cookies = [ { name: SESSION_COOKIE_NAME, value: result.token, options: { httpOnly: true, secure: false, // Set to true in production with HTTPS sameSite: "lax", maxAge: tokenLifetimes.session, path: "/", }, }, ]; return redirectResult; }; const loginRoute: Route = { path: "/login", methods: ["GET", "POST"], handler: loginHandler, }; export { loginRoute };