Total Complexity | 3 |
Complexity/F | 0 |
Lines of Code | 43 |
Function Count | 0 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 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 |