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

export async function load({ cookies, request, url, params }) {
	const { pathname } = url;
	const { id, username } = params;
	const token = cookies.get("token");

	let user;
	if (token) {
		try {
			user = await get("/me", auth(cookies));
		} catch (e) {
			const { message } = e as Error;
			if (message.startsWith("Rate")) {
				await sleep(3000);
				try {
					user = await get("/me", auth(cookies));
				} catch (retryError) {
					if (isInvalidTokenError(retryError) && pathname !== "/logout") {
						redirect(307, "/logout");
					}
					throw retryError;
				}
			} else if (isInvalidTokenError(e) && pathname !== "/logout") {
				redirect(307, "/logout");
			} else {
				throw e;
			}
		}
	}

	let subject;

	if (url.pathname.includes("/invoice") && id) {
		try {
			({ user: subject } = await get(`/invoice/${id}`));
		} catch (e) {
			console.log("unable to fetch invoice", id, e);
		}
	} else if (username) {
		try {
			subject = await get(`/users/${username}`);
		} catch (e) {
			error(500, "Unable to retrieve user account data");
		}
	}

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

	if (
		user &&
		["/login", "/register"].includes(pathname) &&
		request.method === "GET"
	) {
		redirect(307, `/${user.username}`);
	}

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

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