Passed
Pull Request — master (#312)
by
unknown
03:23 queued 01:23
created

client/kit/src/hooks.server.ts   A

Complexity

Total Complexity 3
Complexity/F 0

Size

Lines of Code 43
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 3
eloc 36
mnd 3
bc 3
fnc 0
dl 0
loc 43
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
import type { Handle } from "@sveltejs/kit";
2
import { get } from "$lib/axios";
3
import { getTokenCookie } from "$lib/stores/auth";
4
import { getThemeCookie } from "$lib/stores/theme";
5
6
const NON_PROTECTED_ROUTES = ["/kit/login"];
7
8
const isNonProtected = (url: URL): boolean => {
9
  return NON_PROTECTED_ROUTES.includes(url.pathname);
10
};
11
12
export const handle: Handle = async ({ event, resolve }) => {
13
  const theme = getThemeCookie(event.cookies) || null;
14
15
  event.locals.theme = theme;
16
17
  if (isNonProtected(event.url)) {
18
    return resolve(event);
19
  }
20
21
  const token = getTokenCookie(event.cookies);
22
23
  if (!token) {
24
    return new Response(null, { status: 302, headers: { Location: "/kit/login" } });
25
  }
26
27
  try {
28
    const { data } = await get("users/me", {}, decodeURIComponent(token));
29
30
    event.locals.user = {
31
      id: data.id,
32
      firstName: data.firstName,
33
      lastName: data.lastName,
34
      email: data.email,
35
      scope: data.role,
36
    };
37
38
    return resolve(event);
39
  } catch {
40
    return new Response(null, { status: 302, headers: { Location: "/kit/login" } });
41
  }
42
};
43