aboutsummaryrefslogtreecommitdiffstats
path: root/apps/kit/src/routes/(main)/+layout.server.ts
blob: ba0cd416cf58a367b214f5a1ea2ef3717a3e0b74 (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
import { api_base, CookieNames, is_development } from "$lib/configuration";
import { logError } from "$lib/logger";
import { error, redirect } from "@sveltejs/kit";
import type { LayoutServerLoad } from "./$types";
import { request, Agent, Pool } from "undici";

export const load: LayoutServerLoad = async ({ routeId, cookies }) => {
    const isPublicRoute = routeId?.startsWith("(main)/(public)") ?? true;
    const sessionCookie = cookies.get(CookieNames.session);
    let sessionIsValid = false;
    if (is_development()) {
        sessionIsValid = (await request(api_base("_/valid-session"), {
            throwOnError: false,
            dispatcher: new Agent({
                factory: (origin, opts) => {
                    return new Pool(origin, opts);
                }
            })
        })).statusCode === 200;
    } else {
        sessionIsValid = (await fetch(api_base("_/valid-session"), {
            headers: {
                Cookie: CookieNames.session + "=" + sessionCookie,
            }
        }).catch((e) => {
            logError(e);
            throw error(503, {
                message: "We are experiencing a service distruption! Have patience while we resolve the issue."
            })
        })).ok;
    }

    if (sessionIsValid && isPublicRoute) {
        throw redirect(302, "/home");
    } else if (!sessionIsValid && !isPublicRoute) {
        throw redirect(302, "/sign-in");
    }
};