aboutsummaryrefslogtreecommitdiffstats
path: root/src/routes/(app)/+layout.server.ts
blob: 09d6f841b90e8cabcb11e8bbd7b2e24aa6bcbd9b (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
import { auth, get, isInvalidTokenError, sleep } from "$lib/utils";
import { redirect } from "@sveltejs/kit";

export async function load({ cookies, depends }) {
  depends("app:user");

  const token = cookies.get("token");

  let user;
  let hasArk = false;
  if (token) {
    const authHeaders = auth(cookies);

    // Fetch user and accounts in parallel
    const [userResult, accounts] = await Promise.all([
      get("/me", authHeaders).catch((e) => ({ _error: e })),
      get("/accounts", authHeaders).catch(() => []),
    ]);

    if (userResult?._error) {
      const e = userResult._error;
      const { message } = e as Error;
      if (message.startsWith("Rate")) {
        await sleep(3000);
        try {
          user = await get("/me", authHeaders);
        } catch (retryError) {
          if (isInvalidTokenError(retryError)) {
            redirect(307, "/logout");
          }
          throw retryError;
        }
      } else if (isInvalidTokenError(e)) {
        redirect(307, "/logout");
      } else {
        throw e;
      }
    } else {
      user = userResult;
    }

    hasArk = accounts.some((a: any) => a.type === "ark");
  }

  if (user?.needsMigration) {
    redirect(307, "/migrate");
  }

  const theme = cookies.get("theme") || "light";

  return { user, token, theme, hasArk };
}