refactor: centralize access token handling in cookies and improve related functions
- Introduced utility functions for managing access tokens in cookies, including setting, getting, and clearing tokens. - Updated various components and server routes to utilize the new access token functions for better consistency and maintainability. - Removed redundant cookie handling code across the application, streamlining the authentication process.
This commit is contained in:
@@ -4,9 +4,23 @@
|
||||
import { getToken } from './auth';
|
||||
import { browser } from '$app/environment';
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { clearAccessTokenOnDocument, setAccessTokenOnDocument } from '$lib/access-token-cookie-browser';
|
||||
|
||||
// Normalize API_BASE_URL to remove trailing slash
|
||||
const API_BASE_URL = (import.meta.env.VITE_API_URL || '').replace(/\/+$/, '');
|
||||
/** Base URL absoluta para fetch; corrige `http:host` sin `//` y añade `http://` si no hay esquema. */
|
||||
function normalizeAbsoluteApiBaseUrl(raw: string): string {
|
||||
let s = (raw ?? '').trim().replace(/\/+$/, '');
|
||||
if (!s) return '';
|
||||
if (s.startsWith('http:') && !s.startsWith('http://')) {
|
||||
s = 'http://' + s.slice('http:'.length).replace(/^\/+/, '');
|
||||
}
|
||||
if (s.startsWith('https:') && !s.startsWith('https://')) {
|
||||
s = 'https://' + s.slice('https:'.length).replace(/^\/+/, '');
|
||||
}
|
||||
if (/^https?:\/\//i.test(s)) return s;
|
||||
return `http://${s.replace(/^\/+/, '')}`;
|
||||
}
|
||||
|
||||
const API_BASE_URL = normalizeAbsoluteApiBaseUrl(String(import.meta.env.VITE_API_URL ?? ''));
|
||||
|
||||
export interface ApiResponse<T = any> {
|
||||
data?: T;
|
||||
@@ -164,8 +178,7 @@ async function refreshToken(): Promise<string | null> {
|
||||
|
||||
if (!response.ok) {
|
||||
console.error('❌ [API] Silent refresh falló, status:', response.status);
|
||||
// Limpiar la cookie del access_token (no HttpOnly) para forzar re-login
|
||||
document.cookie = 'access_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 UTC';
|
||||
clearAccessTokenOnDocument();
|
||||
setTimeout(() => { window.location.href = '/login'; }, 1500);
|
||||
return null;
|
||||
}
|
||||
@@ -173,9 +186,7 @@ async function refreshToken(): Promise<string | null> {
|
||||
const data = await response.json() as { access_token?: string };
|
||||
|
||||
if (data.access_token) {
|
||||
// Actualizar cookie no-HttpOnly del access_token
|
||||
const secure = window.location.protocol === 'https:' ? '; Secure' : '';
|
||||
document.cookie = `access_token=${data.access_token}; path=/; max-age=${60 * 60 * 24 * 7}; SameSite=Lax${secure}`;
|
||||
setAccessTokenOnDocument(data.access_token);
|
||||
|
||||
// Actualizar authStore en memoria
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user