summaryrefslogtreecommitdiff
path: root/src/actions
diff options
context:
space:
mode:
Diffstat (limited to 'src/actions')
-rw-r--r--src/actions/login.ts58
-rw-r--r--src/actions/test.ts24
2 files changed, 82 insertions, 0 deletions
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<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("/");
+}
diff --git a/src/actions/test.ts b/src/actions/test.ts
new file mode 100644
index 0000000..99d42a0
--- /dev/null
+++ b/src/actions/test.ts
@@ -0,0 +1,24 @@
+"use server";
+import db from "../lib/db";
+
+export async function testFn(lol: any) {
+ console.log({ lol });
+ return "lmao";
+}
+export async function testLogin(state: number, formdata: FormData) {
+ return state + 9;
+}
+// export async function testLogin({
+// name,
+// creds,
+// }: {
+// name: string;
+// creds: string;
+// }) {
+// const res1 = db.loginUser(name, creds);
+// console.log({ res1 });
+// return res1;
+// // const res = db.addUser(name, creds);
+// // console.log({ res });
+// // return res;
+// }