Private
Public Access
feat: refrescador de tokens
This commit is contained in:
1 parent
0ca9e34801
commit
936a401816
4 files changed
+125
-9
No files matched your search
@@ -2,7 +2,6 @@ package auth
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"repuestera_back/config"
|
"repuestera_back/config"
|
||||||
@@ -39,14 +38,13 @@ func Refresh(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
sub, ok := claims["sub"].(string)
|
sub, ok := claims["sub"].(float64)
|
||||||
if !ok {
|
if !ok {
|
||||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token claims"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
userID, _ := strconv.ParseUint(sub, 10, 32)
|
|
||||||
var user models.Usuario
|
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"})
|
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
import favicon from '$lib/assets/favicon.svg';
|
import favicon from '$lib/assets/favicon.svg';
|
||||||
import { getToken } from '$lib/api';
|
import { getToken } from '$lib/api';
|
||||||
import { goto } from '$app/navigation';
|
import { goto } from '$app/navigation';
|
||||||
|
import { TokenRefresher } from '$lib/TokenRefresher.svelte';
|
||||||
|
|
||||||
let { children } = $props();
|
let { children } = $props();
|
||||||
let theme = 'g100'; // "white" | "g10" | "g80" | "g90" | "g100"
|
let theme = 'g100'; // "white" | "g10" | "g80" | "g90" | "g100"
|
||||||
@@ -18,8 +19,20 @@
|
|||||||
$effect(() => {
|
$effect(() => {
|
||||||
document.documentElement.setAttribute('theme', theme);
|
document.documentElement.setAttribute('theme', theme);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
let _refresher: TokenRefresher;
|
||||||
|
|
||||||
|
$effect(() => {
|
||||||
|
if (token) {
|
||||||
|
_refresher = new TokenRefresher(() => {
|
||||||
|
token = '';
|
||||||
|
goto('/login');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return () => _refresher?.stop();
|
||||||
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<svelte:head><link rel="icon" href={favicon} /></svelte:head>
|
<svelte:head><link rel="icon" href={favicon} /></svelte:head>
|
||||||
|
<button onclick={() => _refresher.refresh()} style="margin-top: 8rem;">ghola</button>
|
||||||
{@render children()}
|
{@render children()}
|
||||||
@@ -2,7 +2,14 @@
|
|||||||
import { getCurrentUser, ObtenerGruposDeUsuario } from '$lib/api';
|
import { getCurrentUser, ObtenerGruposDeUsuario } from '$lib/api';
|
||||||
import CardError from '$lib/components/CardError.svelte';
|
import CardError from '$lib/components/CardError.svelte';
|
||||||
import Header from '$lib/components/Header.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();
|
let usuario = getCurrentUser();
|
||||||
|
|
||||||
@@ -28,9 +35,13 @@
|
|||||||
{#if g.permisos?.length == 0}
|
{#if g.permisos?.length == 0}
|
||||||
<p class="text-neutral-500">No hay permisos en este grupo</p>
|
<p class="text-neutral-500">No hay permisos en este grupo</p>
|
||||||
{:else}
|
{:else}
|
||||||
{#each g.permisos as p}
|
<ContainedList>
|
||||||
<a href={p.alias}>{p.nombre}</a>
|
{#each g.permisos as p}
|
||||||
{/each}
|
<ContainedListItem>
|
||||||
|
<a href={p.alias}>{p.nombre}</a>
|
||||||
|
</ContainedListItem>
|
||||||
|
{/each}
|
||||||
|
</ContainedList>
|
||||||
{/if}
|
{/if}
|
||||||
</AccordionItem>
|
</AccordionItem>
|
||||||
{/each}
|
{/each}
|
||||||
|
|||||||
Reference in new issue
Block a user