Refactor authentication handling and API calls in dashboard routes

- 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.
This commit is contained in:
2025-11-12 09:46:59 -06:00
parent 70f7d1f868
commit a5c1bab201
27 changed files with 549 additions and 573 deletions

View File

@@ -1,12 +1,13 @@
import type { PageServerLoad } from './$types';
import { getAuthTokens, authenticatedFetch } from '$lib/server/api';
export const load: PageServerLoad = async ({ cookies, fetch, url, parent }) => {
// Esperar a que el layout padre valide/refresque el token
await parent();
const token = cookies.get('access_token');
const { accessToken } = getAuthTokens(cookies);
if (!token) {
if (!accessToken) {
return {
error: 'No authenticated',
items: [],
@@ -21,25 +22,12 @@ export const load: PageServerLoad = async ({ cookies, fetch, url, parent }) => {
const page = parseInt(url.searchParams.get('page') || '1');
const pageSize = parseInt(url.searchParams.get('page_size') || '50');
// Configurar la URL de la API para SSR
let apiUrl = process.env.INTERNAL_API_URL;
if (!apiUrl) {
apiUrl = import.meta.env.VITE_API_URL;
// Reemplazar 'localhost' con 'backend' para llamadas desde el servidor (SSR)
apiUrl = apiUrl?.replace('localhost', 'backend').replace('127.0.0.1', 'backend');
}
// Normalizar la URL
const baseUrl = apiUrl?.endsWith('/') ? apiUrl : `${apiUrl}/`;
const response = await fetch(
`${baseUrl}v1/public/refrence_data/payment-methods?page=${page}&page_size=${pageSize}`,
{
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
}
// Usar authenticatedFetch para manejar automáticamente el refresh de tokens
const response = await authenticatedFetch(
`v1/public/refrence_data/payment-methods?page=${page}&page_size=${pageSize}`,
{},
cookies,
fetch
);
if (!response.ok) {