summaryrefslogtreecommitdiff
path: root/src/actions/login.ts
blob: ee15fe653e72ff897211a338be34981ba4ca6413 (plain)
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
"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 {
    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 } = useCookies();
  setCookie(cokistring);
  // unstable_redirect("/");
}

// export async function postLogout(prev: number) {
//   const { delCookie } = cookies();
//   const rest = delCookie("sorlang");
//   return prev + 9;
// }