71 lines
2.2 KiB
TypeScript
71 lines
2.2 KiB
TypeScript
import { redirect } from '@sveltejs/kit';
|
|
import type { LayoutServerLoad } from './$types';
|
|
import {
|
|
validateAuth,
|
|
getUserCompanies,
|
|
getAuthTokens,
|
|
clearAuthTokens,
|
|
authenticatedFetch
|
|
} from '$lib/server/api';
|
|
|
|
export const load: LayoutServerLoad = async ({ cookies, url, fetch }) => {
|
|
// Verificar si existe el token en las cookies
|
|
const { accessToken } = getAuthTokens(cookies);
|
|
|
|
// Si no hay token, redirigir al login
|
|
if (!accessToken) {
|
|
const redirectUrl = `/login?redirect=${encodeURIComponent(url.pathname)}`;
|
|
throw redirect(303, redirectUrl);
|
|
}
|
|
|
|
// Validar el token con el backend y obtener datos del usuario
|
|
// La función validateAuth maneja automáticamente el refresh de tokens
|
|
const redirectOnFail = `/login?redirect=${encodeURIComponent(url.pathname)}`;
|
|
|
|
try {
|
|
const userData = await validateAuth(cookies, fetch, redirectOnFail);
|
|
|
|
// Cargar las compañías del usuario en el servidor (SSR)
|
|
const companies = await getUserCompanies(cookies, fetch);
|
|
|
|
// Cargar los tenants del usuario para el selector de organización
|
|
let userTenants: { id: number; name: string; slug: string; is_active: boolean }[] = [];
|
|
try {
|
|
const tenantsRes = await authenticatedFetch(
|
|
`v1/core/user-tenants/${userData.sub}`,
|
|
{},
|
|
cookies,
|
|
fetch
|
|
);
|
|
if (tenantsRes.ok) {
|
|
const tenantsData = await tenantsRes.json();
|
|
userTenants = tenantsData.tenants ?? [];
|
|
}
|
|
} catch {
|
|
// No bloquear el dashboard si falla la carga de tenants
|
|
}
|
|
|
|
// Obtener la compañía activa de la cookie para persistencia
|
|
const activeCompanyId = cookies.get('active_company_id');
|
|
|
|
return {
|
|
authenticated: true,
|
|
user: { ...userData, token: accessToken },
|
|
companies,
|
|
activeCompanyId: activeCompanyId ? parseInt(activeCompanyId) : undefined,
|
|
userTenants,
|
|
error: undefined
|
|
};
|
|
} catch (error) {
|
|
// Si es un redirect, re-lanzarlo sin tocar las cookies
|
|
if (error && typeof error === 'object' && 'status' in error && 'location' in error) {
|
|
throw error;
|
|
}
|
|
|
|
// Para cualquier otro error (conexión, etc), limpiar token y redirigir
|
|
console.error('🔐 [Dashboard] Error validando token:', error);
|
|
clearAuthTokens(cookies);
|
|
throw redirect(303, redirectOnFail);
|
|
}
|
|
};
|