import { HandlerContext } from "$fresh/server.ts"; import { setCookie } from "http/cookie.ts"; import { Status } from "http/http_status.ts"; import { connectDB } from "../../src/user/db.ts"; import { getUser, verifyUser } from "../../src/user/user.ts"; import { create as createJWT } from "djwt"; import { prepareSecretKey } from "../../util/secret.ts"; const SECRET_KEY = await prepareSecretKey(); async function POST(req: Request, ctx: HandlerContext): Promise { const url = new URL(req.url); const form = await req.formData(); const username = form.get("username"); const password = form.get("password"); if (username && password){ const DB = connectDB(); const user = await getUser(DB, username.toString()); if (user){ if (await verifyUser(user, password.toString())){ const headers = new Headers(); const jwt = await createJWT({alg:"HS512", typ: "JWT"},{ username: user.name }, SECRET_KEY); setCookie(headers, { name: "auth", value: jwt, httpOnly: true, sameSite: "Strict", maxAge: 60 * 60 * 24 * 7, domain: url.hostname, path: "/", secure: url.protocol === "https:" }); headers.set("Location", "/"); return new Response(null,{ status: Status.SeeOther, // See Other headers: headers }); } } } return new Response(` Login Failed

Login Failed

Back to Home

`, { headers:{ "Content-Type": "text/html" }, status: Status.Forbidden, }); } export const handler = { POST };