1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
|
"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<number | bigint> {
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<FormState> {
// "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<any> {
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;
// }
|