"use server"; import type { AsyncRes } from "@/lib/types"; import db from "../lib/db"; import { useCookies } from "../lib/server/cookiebridge"; export type FormState = { name?: string; password?: string; error?: string; success?: boolean; }; async function call( formData: FormData, register: boolean, ): AsyncRes { const nam = formData.get("username"); const creds = formData.get("password"); const password = await Bun.password.hash(creds!.toString()); const name = nam!.toString(); try { const res = register ? db.addUser(name, password) : await db.loginUser(name, creds!.toString()); return res; } catch (e) { console.error(e); return { error: `${e}` }; } } export async function postRegister( prevState: FormState, formData: FormData, ): Promise { // "use server"; 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 { console.log(formData); const res = await call(formData, false); console.log({ res }); if ("error" in res) return { error: res.error }; else { // Set the cookie await setCookie(res.ok as number); // Return success for client-side handling return { success: true, userId: res.ok, redirect: "/" }; } } async function setCookie(userId: number) { // Set cookie expiry for 30 days const COOKIE_EXPIRY = Date.now() + 1000 * 60 * 60 * 24 * 30; // Generate a secure random token for the cookie const { randomBytes } = await import("node:crypto"); const cookieToken = randomBytes(32).toString("base64"); // Store the cookie in the database const res = db.setCookie(cookieToken, userId, COOKIE_EXPIRY); // Set the cookie in the response const { setCookie } = useCookies(); setCookie(cookieToken); console.log("Cookie set for user ID:", userId); // Redirect is managed by client after successful login } // export async function postLogout(prev: number) { // const { delCookie } = cookies(); // const rest = delCookie("sorlang"); // return prev + 9; // }