import { getCookies, setCookie } from "@std/http/cookie"; import { z } from "zod"; import { backendSignIn } from "../backend/sign-in.ts"; import { SignInForm } from "../components/SignInForm.tsx"; import { define } from "../utils.ts"; const loginSchema = z.object({ email: z.string(), password: z.string().min(8), }); export const handler = define.handlers({ GET(ctx) { const cookies = getCookies(ctx.req.headers); const authCookie = cookies["auth"]; if (authCookie === "ok") { const url = new URL(ctx.req.url); url.pathname = "/dashboard"; return Response.redirect(url, 303); } return { data: { email: "", error: undefined, }, }; }, async POST(ctx) { const formData = await ctx.req.formData(); const request = loginSchema.safeParse({ email: formData.get("email"), password: formData.get("password"), }); if (!request.success) { return { data: { email: formData.get("email") as string, error: request.error.issues[0].message, }, }; } const { email, password } = request.data; // Super secure authorization method if (!await backendSignIn(email, password)) { return { data: { email, }, }; } const url = new URL(ctx.req.url); const headers = new Headers(); setCookie(headers, { name: "auth", value: "ok", maxAge: 120, sameSite: "Lax", domain: url.hostname, path: "/", secure: true, }); url.pathname = "/dashboard"; headers.set("location", url.toString()); return new Response(null, { status: 303, headers, }); }, }); export default define.page(function SignInPage(ctx) { const email = ctx.data.email || ""; const error = ctx.data.error; return (

Sign in

); });