feat: refrescador de tokens

This commit is contained in:
fede committed 2026-05-12 01:06:11 -03:00
1 parent 0ca9e34801
commit 936a401816
4 files changed
+125 -9

No files matched your search

+2 -4
View File
@@ -2,7 +2,6 @@ package auth
import (
"net/http"
"strconv"
"time"
"repuestera_back/config"
@@ -39,14 +38,13 @@ func Refresh(c *gin.Context) {
return
}
sub, ok := claims["sub"].(string)
sub, ok := claims["sub"].(float64)
if !ok {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
return
}
userID, _ := strconv.ParseUint(sub, 10, 32)
var user models.Usuario
if err := config.DB.First(&user, userID).Error; err != nil {
if err := config.DB.First(&user, sub).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
return
}
+94
View File
@@ -0,0 +1,94 @@
import { API_URL } from '$lib/env';
import {
getAuthTokens,
setAuthTokens,
setToken,
removeAuthTokens,
removeToken
} from '$lib/hooks/token';
function getTokenExpiry(): number | null {
try {
const token = getAuthTokens()?.access_token;
if (!token) return null;
const payload = JSON.parse(atob(token.split('.')[1]));
return payload.exp ? payload.exp * 1000 : null;
} catch {
return null;
}
}
export class TokenRefresher {
private timer: ReturnType<typeof setInterval> | null = null;
private onExpired: () => void;
active = $state(false);
constructor(onExpired?: () => void) {
this.onExpired = onExpired ?? (() => {});
if (getAuthTokens()) {
this.start();
}
}
start() {
this.schedule();
}
stop() {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
this.active = false;
}
private schedule() {
this.stop();
if (!getAuthTokens()) return;
const exp = getTokenExpiry();
if (!exp) return;
const delay = Math.max(exp - Date.now() - 120_000, 30_000);
this.active = true;
this.timer = setInterval(() => {
this.refresh();
}, delay);
}
private async refresh() {
const tokens = getAuthTokens();
if (!tokens?.refresh_token) {
this.stop();
return;
}
try {
const res = await fetch(`${API_URL}/auth/refresh`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ refresh_token: tokens.refresh_token })
});
if (!res.ok) throw new Error('Refresh failed');
const data = await res.json();
setAuthTokens({
access_token: data.access_token,
refresh_token: data.refresh_token,
expires_in: data.expires_in,
token_type: data.token_type
});
setToken(data.access_token);
this.schedule();
} catch {
removeAuthTokens();
removeToken();
this.stop();
this.onExpired();
}
}
}
+14 -1
View File
@@ -4,6 +4,7 @@
import favicon from '$lib/assets/favicon.svg';
import { getToken } from '$lib/api';
import { goto } from '$app/navigation';
import { TokenRefresher } from '$lib/TokenRefresher.svelte';
let { children } = $props();
let theme = 'g100'; // "white" | "g10" | "g80" | "g90" | "g100"
@@ -18,8 +19,20 @@
$effect(() => {
document.documentElement.setAttribute('theme', theme);
});
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()}
+15 -4
View File
@@ -2,7 +2,14 @@
import { getCurrentUser, ObtenerGruposDeUsuario } from '$lib/api';
import CardError from '$lib/components/CardError.svelte';
import Header from '$lib/components/Header.svelte';
import { Accordion, AccordionItem, Loading, Tile } from 'carbon-components-svelte';
import {
Accordion,
AccordionItem,
ContainedList,
ContainedListItem,
Loading,
Tile
} from 'carbon-components-svelte';
let usuario = getCurrentUser();
@@ -28,9 +35,13 @@
{#if g.permisos?.length == 0}
<p class="text-neutral-500">No hay permisos en este grupo</p>
{:else}
{#each g.permisos as p}
<a href={p.alias}>{p.nombre}</a>
{/each}
<ContainedList>
{#each g.permisos as p}
<ContainedListItem>
<a href={p.alias}>{p.nombre}</a>
</ContainedListItem>
{/each}
</ContainedList>
{/if}
</AccordionItem>
{/each}