fix: access_token (pas token) dans la réponse login/refresh

Le backend retourne { access_token: "...", user: {...} } pas { token: "..." }.
Le store Alpine lisait data.token → undefined → stockait "undefined" en localStorage
→ toutes les requêtes API échouaient avec 401.

Corrigé dans login() et tryRefresh().
Ajout d'un guard synchrone immédiat (pas de token → redirect login sans attendre fetchMe).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
enzo 2026-03-21 16:50:52 +01:00
parent 562eff8863
commit 65c8bf332f

View file

@ -53,8 +53,9 @@ document.addEventListener('alpine:init', () => {
const res = await fetch('/api/auth/refresh', { method: 'POST', credentials: 'include' }) const res = await fetch('/api/auth/refresh', { method: 'POST', credentials: 'include' })
if (res.ok) { if (res.ok) {
const data = await res.json() const data = await res.json()
this.token = data.token // Le backend retourne "access_token" (pas "token")
localStorage.setItem('pxp_token', data.token) this.token = data.access_token
localStorage.setItem('pxp_token', data.access_token)
await this.fetchMe() await this.fetchMe()
} else { } else {
this.clear() this.clear()
@ -73,9 +74,10 @@ document.addEventListener('alpine:init', () => {
throw new Error(err.error || 'Identifiants invalides') throw new Error(err.error || 'Identifiants invalides')
} }
const data = await res.json() const data = await res.json()
this.token = data.token // Le backend retourne "access_token" (pas "token")
this.token = data.access_token
this.user = data.user this.user = data.user
localStorage.setItem('pxp_token', data.token) localStorage.setItem('pxp_token', data.access_token)
}, },
async logout() { async logout() {
@ -640,15 +642,13 @@ document.addEventListener('DOMContentLoaded', async () => {
await Alpine.store('auth').init() await Alpine.store('auth').init()
Alpine.store('ui').init() Alpine.store('ui').init()
// Guard auth : redirect si non authentifié
const publicPages = ['login', 'install', 'index', ''] const publicPages = ['login', 'install', 'index', '']
const currentPage = window.location.pathname.replace(/^\/|\.html$/g, '') || 'index' const currentPage = window.location.pathname.replace(/^\/|\.html$/g, '') || 'index'
if (!publicPages.includes(currentPage)) { // Guard rapide (synchrone) : si pas de token du tout, redirect immédiat
if (!Alpine.store('auth').isAuthenticated) { if (!publicPages.includes(currentPage) && !localStorage.getItem('pxp_token')) {
window.location.href = '/login.html' window.location.href = '/login.html'
return return
}
} }
// Redirect depuis index // Redirect depuis index