From d56594d3289002566f4653d607f0837befd65109 Mon Sep 17 00:00:00 2001 From: polwex Date: Thu, 15 May 2025 10:13:00 +0700 Subject: wtf man --- src/actions/login.ts | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 src/actions/login.ts (limited to 'src/actions/login.ts') diff --git a/src/actions/login.ts b/src/actions/login.ts new file mode 100644 index 0000000..3d83b55 --- /dev/null +++ b/src/actions/login.ts @@ -0,0 +1,58 @@ +"use server"; +import { AsyncRes } from "@/lib/types"; +import db from "../lib/db"; +import cookie from "cookie"; +import { cookies } from "../lib/server/cookiebridge"; +import { unstable_redirect, unstable_rerenderRoute } from "waku/router/server"; + +export type FormState = { + name?: string; + password?: string; + error?: string; + success?: boolean; +}; +async function call(formData: FormData, register: boolean) { + const nam = formData.get("username"); + const creds = formData.get("password"); + const password = await Bun.password.hash(creds!.toString()); + const name = nam!.toString(); + const res = register + ? db.addUser(name, password) + : await db.loginUser(name, creds!.toString()); + return res; +} + +export async function postRegister( + prevState: FormState, + formData: FormData, +): Promise { + const res = await call(formData, true); + console.log("reg res", res); + if ("error" in res) return { error: "Something went wrong" }; + else { + return { success: true }; + } +} + +export async function postLogin( + prevState: FormState, + formData: FormData, +): Promise { + const res = await call(formData, false); + if ("error" in res) return { error: res.error }; + else { + setCookie(res.ok as number); + return { success: true }; + } +} +async function setCookie(userId: number) { + const COOKIE_EXPIRY = Date.now() + 1000 * 60 * 60 * 24 * 30; + const COOKIE_OPTS = { expires: new Date(COOKIE_EXPIRY) }; + + const { randomBytes } = await import("node:crypto"); + const cokistring = randomBytes(32).toBase64(); + const res = db.setCookie(cokistring, userId, COOKIE_EXPIRY); + const { setCookie } = cookies(); + setCookie("sorlang", cokistring, COOKIE_OPTS); + // unstable_redirect("/"); +} -- cgit v1.2.3