fix: amélioration de la gestion de l'authentification pour la PWA

This commit is contained in:
Julien Froidefond
2025-02-12 22:12:37 +01:00
parent e95188c32a
commit 99aef49dd9
2 changed files with 48 additions and 9 deletions

View File

@@ -5,6 +5,7 @@ import { cn } from "@/lib/utils";
import { authService } from "@/lib/services/auth.service"; import { authService } from "@/lib/services/auth.service";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { KomgaLibrary } from "@/types/komga"; import { KomgaLibrary } from "@/types/komga";
import { storageService } from "@/lib/services/storage.service";
interface SidebarProps { interface SidebarProps {
isOpen: boolean; isOpen: boolean;
@@ -17,39 +18,60 @@ export function Sidebar({ isOpen }: SidebarProps) {
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const [isAuthenticated, setIsAuthenticated] = useState(false); const [isAuthenticated, setIsAuthenticated] = useState(false);
// Initialiser l'authentification au montage du composant
useEffect(() => { useEffect(() => {
// Vérifier si l'utilisateur est authentifié const initAuth = () => {
const checkAuth = () => { const credentials = storageService.getCredentials();
const isAuth = authService.isAuthenticated(); const user = storageService.getUser();
setIsAuthenticated(isAuth); console.log("Sidebar - Init Auth:", { hasCredentials: !!credentials, hasUser: !!user });
return isAuth; if (credentials && user) {
setIsAuthenticated(true);
return true;
}
return false;
}; };
initAuth();
}, []);
// Effet séparé pour charger les bibliothèques
useEffect(() => {
const fetchLibraries = async () => { const fetchLibraries = async () => {
if (!checkAuth()) { if (!isAuthenticated) {
setIsLoading(false); setIsLoading(false);
return; return;
} }
try { try {
console.log("Sidebar - Fetching libraries...");
const response = await fetch("/api/komga/libraries"); const response = await fetch("/api/komga/libraries");
if (!response.ok) { if (!response.ok) {
throw new Error("Erreur lors de la récupération des bibliothèques"); throw new Error(`Erreur ${response.status} lors de la récupération des bibliothèques`);
} }
const data = await response.json(); const data = await response.json();
console.log("Sidebar - Libraries fetched:", data.length);
setLibraries(data); setLibraries(data);
} catch (error) { } catch (error) {
console.error("Erreur:", error); console.error("Sidebar - Error fetching libraries:", error);
if (
error instanceof Error &&
(error.message.includes("401") || error.message.includes("403"))
) {
console.log("Sidebar - Auth error, logging out");
handleLogout();
}
} finally { } finally {
setIsLoading(false); setIsLoading(false);
} }
}; };
fetchLibraries(); fetchLibraries();
}, [pathname]); // Recharger quand le pathname change pour gérer la déconnexion }, [isAuthenticated, pathname]);
const handleLogout = () => { const handleLogout = () => {
console.log("Sidebar - Logging out");
authService.logout(); authService.logout();
storageService.clearAll(); // Nettoyer tout le stockage
setIsAuthenticated(false); setIsAuthenticated(false);
setLibraries([]); setLibraries([]);
router.push("/login"); router.push("/login");

View File

@@ -142,6 +142,23 @@ class StorageService {
document.cookie = `${CREDENTIALS_KEY}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`; document.cookie = `${CREDENTIALS_KEY}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
document.cookie = `${USER_KEY}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`; document.cookie = `${USER_KEY}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
} }
getUser() {
try {
const userStr = localStorage.getItem("komgaUser");
if (!userStr) return null;
return JSON.parse(atob(userStr));
} catch (error) {
console.error("Erreur lors de la récupération de l'utilisateur:", error);
return null;
}
}
clearAll() {
localStorage.removeItem("komgaUser");
localStorage.removeItem("komgaCredentials");
localStorage.removeItem("ttlConfig");
}
} }
export const storageService = StorageService.getInstance(); export const storageService = StorageService.getInstance();