aboutsummaryrefslogtreecommitdiffstats
path: root/src/routes/(static)/register/+page.server.ts
blob: 6986e890e61979a1f413d98db957fd6ac72c5b9c (plain) (blame)
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
import { fd, get, post } from "$lib/utils";
import { fail, redirect } from "@sveltejs/kit";

export const load = async ({ parent }) => {
  const { user } = await parent();
  if (user) redirect(307, `/${user.username}`);

  const index = Math.floor(Math.random() * 64) + 1;
  const { challenge } = await get("/challenge");

  return { index, challenge };
};

export const actions = {
  register: async ({ request }) => {
    const ip = request.headers.get("cf-connecting-ip");
    const form = await fd(request);
    const { picture, username, challenge, recaptcha } = form;

    const user = { picture, username, challenge, recaptcha };
    const headers: Record<string, string> = {};
    if (ip) headers["cf-connecting-ip"] = ip;

    try {
      const { sk, token } = await post("/register", { user }, headers);
      return { token, sk, username };
    } catch (e) {
      const { message } = e as Error;
      return fail(400, { error: message });
    }
  },

  activate: async ({ cookies, request }) => {
    const form = await fd(request);
    const { token, username, sk, pubkey } = form;
    let { loginRedirect } = form;
    if (loginRedirect === "undefined") loginRedirect = undefined;

    const maxAge = 380 * 24 * 60 * 60;
    const expires = new Date();
    expires.setSeconds(expires.getSeconds() + maxAge);
    const opts = { path: "/", expires };

    cookies.set("username", username, opts);
    cookies.set("token", token, opts);

    if (sk) {
      const skExpires = new Date();
      skExpires.setSeconds(skExpires.getSeconds() + 21000000);
      cookies.set("sk", sk, {
        path: "/",
        expires: skExpires,
        httpOnly: false,
        sameSite: "lax",
      });
    }

    if (pubkey) {
      try {
        await post("/user", { pubkey }, { authorization: `Bearer ${token}` });
      } catch (e) {
        console.log("Failed to update pubkey:", e);
      }
    }

    redirect(303, loginRedirect || `/${username}`);
  },
};