Private
Public Access
80 lines
2.1 KiB
Svelte
80 lines
2.1 KiB
Svelte
<script lang="ts">
|
|
import './layout.css';
|
|
import 'carbon-components-svelte/css/all.css';
|
|
import favicon from '$lib/assets/favicon.svg';
|
|
import { AUTH_CHANGE_EVENT, getToken } from '$lib/hooks/token';
|
|
import { getCurrentUser } from '$lib/hooks/user';
|
|
import { goto } from '$app/navigation';
|
|
import { browser } from '$app/environment';
|
|
import { page } from '$app/state';
|
|
import { TokenRefresher } from '$lib/TokenRefresher.svelte';
|
|
|
|
let { children } = $props();
|
|
let theme = 'g100'; // "white" | "g10" | "g80" | "g90" | "g100"
|
|
let token = $state(getToken());
|
|
|
|
const RUTAS_PUBLICAS = new Set(['/', '/login', '/register']);
|
|
|
|
function esRutaPublica(path: string): boolean {
|
|
return RUTAS_PUBLICAS.has(path) || path.startsWith('/invitaciones/');
|
|
}
|
|
|
|
$effect(() => {
|
|
document.documentElement.setAttribute('theme', theme);
|
|
});
|
|
|
|
$effect(() => {
|
|
const syncToken = () => {
|
|
token = getToken();
|
|
};
|
|
|
|
window.addEventListener(AUTH_CHANGE_EVENT, syncToken);
|
|
window.addEventListener('storage', syncToken);
|
|
|
|
return () => {
|
|
window.removeEventListener(AUTH_CHANGE_EVENT, syncToken);
|
|
window.removeEventListener('storage', syncToken);
|
|
};
|
|
});
|
|
|
|
$effect(() => {
|
|
if (!browser) return;
|
|
|
|
const path = page.url.pathname;
|
|
|
|
if (!token && !esRutaPublica(path)) {
|
|
const destino = path === '/' ? '' : `?next=${encodeURIComponent(path + page.url.search)}`;
|
|
void goto(`/login${destino}`, { replaceState: true });
|
|
return;
|
|
}
|
|
|
|
if (token && (path === '/login' || path === '/register')) {
|
|
void goto('/menu', { replaceState: true });
|
|
return;
|
|
}
|
|
|
|
if (token && path !== '/cambiar-contraseña') {
|
|
const usuario = getCurrentUser();
|
|
if (usuario?.debe_cambiar_password) {
|
|
void goto('/cambiar-contraseña', { replaceState: true });
|
|
}
|
|
}
|
|
});
|
|
|
|
let _refresher: TokenRefresher;
|
|
|
|
$effect(() => {
|
|
if (token) {
|
|
_refresher = new TokenRefresher(() => {
|
|
token = '';
|
|
goto('/login');
|
|
});
|
|
}
|
|
return () => _refresher?.stop();
|
|
});
|
|
</script>
|
|
|
|
<svelte:head><link rel="icon" href={favicon} /></svelte:head>
|
|
<!-- <button onclick={() => _refresher.refresh()} style="margin-top: 8rem;">ghola</button> -->
|
|
{@render children()}
|