- Centralized API URL configuration and token management in $lib/server/api.ts. - Replaced direct token access with a centralized method for retrieving tokens. - Updated all dashboard reference data routes to use authenticatedFetch for API calls, improving token refresh handling. - Simplified login route by utilizing centralized token management functions. - Added a new layout file for the dashboard to pass user and company data to the client.
41 lines
1.1 KiB
TypeScript
41 lines
1.1 KiB
TypeScript
import { redirect } from '@sveltejs/kit';
|
|
import type { PageServerLoad } from './$types';
|
|
import { getAuthTokens, authenticatedFetch, clearAuthTokens } from '$lib/server/api';
|
|
|
|
export const load: PageServerLoad = async ({ cookies, fetch }) => {
|
|
const { accessToken } = getAuthTokens(cookies);
|
|
|
|
// Si hay token, validar que sea válido antes de redirigir
|
|
if (accessToken) {
|
|
try {
|
|
// Verificar si el token es válido usando authenticatedFetch
|
|
const response = await authenticatedFetch(
|
|
'v1/auth/me',
|
|
{},
|
|
cookies,
|
|
fetch
|
|
);
|
|
|
|
// Solo redirigir al dashboard si el token es válido
|
|
if (response.ok) {
|
|
throw redirect(303, '/dashboard');
|
|
} else {
|
|
// Token inválido, limpiar cookies y mostrar la página pública
|
|
clearAuthTokens(cookies);
|
|
}
|
|
} catch (error) {
|
|
// Si es un redirect, re-lanzarlo
|
|
if (error && typeof error === 'object' && 'status' in error && 'location' in error) {
|
|
throw error;
|
|
}
|
|
// Para otros errores, limpiar cookies y continuar
|
|
clearAuthTokens(cookies);
|
|
}
|
|
}
|
|
|
|
// Si no está autenticado, mostrar la página principal pública
|
|
return {
|
|
isAuthenticated: false
|
|
};
|
|
};
|