frontend:refactor layout.server

This commit is contained in:
Alex
2025-02-19 12:07:27 +01:00
parent 012a57956a
commit cf037db080

View File

@@ -1,28 +1,28 @@
import { BASE_API_URI } from "$lib/utils/constants";
import { redirect } from "@sveltejs/kit";
import { userDatesFromRFC3339, refreshCookie } from "$lib/utils/helpers";
import { BASE_API_URI } from '$lib/utils/constants';
import { redirect } from '@sveltejs/kit';
import { userDatesFromRFC3339, refreshCookie } from '$lib/utils/helpers';
/** @type {import('./$types').LayoutServerLoad} */
export async function load({ cookies, fetch, locals }) {
const jwt = cookies.get("jwt");
const jwt = cookies.get('jwt');
try {
// Fetch user data, subscriptions, and licence categories in parallel
const response = await fetch(`${BASE_API_URI}/backend/users/all`, {
credentials: "include",
credentials: 'include',
headers: {
Cookie: `jwt=${jwt}`,
},
Cookie: `jwt=${jwt}`
}
});
if (!response.ok) {
// Clear the invalid JWT cookie
cookies.delete("jwt", { path: "/" });
throw redirect(302, "/auth/login?next=/");
cookies.delete('jwt', { path: '/' });
throw redirect(302, '/auth/login?next=/');
}
const data = await response.json();
// Check if the server sent a new token
const newToken = response.headers.get("Set-Cookie");
refreshCookie(newToken, null);
const newToken = response.headers.get('Set-Cookie');
refreshCookie(newToken, cookies);
/** @type {App.Locals['users']}*/
const users = data.users;
@@ -36,13 +36,13 @@ export async function load({ cookies, fetch, locals }) {
subscriptions: locals.subscriptions,
licence_categories: locals.licence_categories,
users: locals.users,
user: locals.user,
user: locals.user
};
} catch (error) {
console.error("Error fetching data:", error);
console.error('Error fetching data:', error);
// In case of any error, clear the JWT cookie
cookies.delete("jwt", { path: "/" });
cookies.delete('jwt', { path: '/' });
throw redirect(302, "/auth/login?next=/");
throw redirect(302, '/auth/login?next=/');
}
}