70 lines
2.1 KiB
JavaScript
70 lines
2.1 KiB
JavaScript
import { BASE_API_URI } from '$lib/utils/constants';
|
|
import { redirect } from '@sveltejs/kit';
|
|
import { userDatesFromRFC3339, refreshCookie, carDatesFromRFC3339 } from '$lib/utils/helpers';
|
|
import { base } from '$app/paths';
|
|
|
|
/** @type {import('./$types').LayoutServerLoad} */
|
|
export async function load({ cookies, fetch, locals }) {
|
|
const jwt = cookies.get('jwt');
|
|
try {
|
|
const [usersResponse, carsResponse] = await Promise.all([
|
|
fetch(`${BASE_API_URI}/auth/users`, {
|
|
credentials: 'include',
|
|
headers: { Cookie: `jwt=${jwt}` }
|
|
}),
|
|
fetch(`${BASE_API_URI}/auth/cars`, {
|
|
credentials: 'include',
|
|
headers: { Cookie: `jwt=${jwt}` }
|
|
})
|
|
]);
|
|
if (!usersResponse.ok || !carsResponse.ok) {
|
|
cookies.delete('jwt', { path: '/' });
|
|
throw redirect(302, `${base}/auth/login?next=${base}/auth/admin/users/`);
|
|
}
|
|
const [usersData, carsData] = await Promise.all([usersResponse.json(), carsResponse.json()]);
|
|
// const response = await fetch(`${BASE_API_URI}/auth/users/`, {
|
|
// credentials: 'include',
|
|
// headers: {
|
|
// Cookie: `jwt=${jwt}`
|
|
// }
|
|
// });
|
|
// if (!response.ok) {
|
|
// // Clear the invalid JWT cookie
|
|
// cookies.delete('jwt', { path: '/' });
|
|
// throw redirect(302, `${base}/auth/login?next=${base}/auth/admin/users/`);
|
|
// }
|
|
|
|
// const data = await response.json();
|
|
/** @type {App.Locals['users']}*/
|
|
const users = usersData.users;
|
|
/** @type {App.Types['car'][]} */
|
|
const cars = carsData.cars;
|
|
|
|
users.forEach((user) => {
|
|
userDatesFromRFC3339(user);
|
|
});
|
|
cars.forEach((car) => {
|
|
carDatesFromRFC3339(car);
|
|
});
|
|
|
|
locals.users = users;
|
|
locals.cars = cars;
|
|
// Check if the server sent a new token
|
|
const newToken = usersResponse.headers.get('Set-Cookie');
|
|
refreshCookie(newToken, cookies);
|
|
return {
|
|
subscriptions: locals.subscriptions,
|
|
licence_categories: locals.licence_categories,
|
|
users: locals.users,
|
|
user: locals.user,
|
|
cars: locals.cars
|
|
};
|
|
} catch (error) {
|
|
console.error('Error fetching data:', error);
|
|
// In case of any error, clear the JWT cookie
|
|
cookies.delete('jwt', { path: '/' });
|
|
|
|
throw redirect(302, `${base}/auth/login?next=${base}/auth/admin/users/`);
|
|
}
|
|
}
|