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
|
"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<FormState> {
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<FormState> {
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("/");
}
|