Files
pagodera/lib/hooks/use-session.ts
T
Evandro Fonseca Junior 55eebde0ba feat: add user authentication UI to header component
Add login and register dialogs, user dropdown menu with profile link and logout option, and integrate with session management hook. Prevent hydration mismatches by conditionally rendering auth elements after mount. Update package-lock.json with new @esbuild dependencies for build tooling.
2025-11-04 02:33:29 -03:00

106 lines
2.1 KiB
TypeScript

"use client";
import { useState, useEffect, useCallback } from "react";
export interface SessionUser {
userId: number;
username: string;
email: string;
}
interface SessionState {
user: SessionUser | null;
isLoading: boolean;
isAuthenticated: boolean;
}
/**
* Hook para gerenciar sessão do usuário
*/
export function useSession() {
const [session, setSession] = useState<SessionState>({
user: null,
isLoading: true,
isAuthenticated: false,
});
/**
* Verifica a sessão atual
*/
const checkSession = useCallback(async () => {
try {
const response = await fetch("/api/auth/session", {
method: "GET",
credentials: "include",
});
const data = await response.json();
if (data.success && data.authenticated) {
setSession({
user: data.user,
isLoading: false,
isAuthenticated: true,
});
} else {
setSession({
user: null,
isLoading: false,
isAuthenticated: false,
});
}
} catch (error) {
console.error("Erro ao verificar sessão:", error);
setSession({
user: null,
isLoading: false,
isAuthenticated: false,
});
}
}, []);
/**
* Encerra a sessão
*/
const logout = useCallback(async () => {
try {
await fetch("/api/auth/session", {
method: "DELETE",
credentials: "include",
});
setSession({
user: null,
isLoading: false,
isAuthenticated: false,
});
// Recarregar página para limpar estado
window.location.href = "/";
} catch (error) {
console.error("Erro ao fazer logout:", error);
}
}, []);
/**
* Atualiza a sessão após login
*/
const refreshSession = useCallback(async () => {
await checkSession();
}, [checkSession]);
// Verificar sessão ao montar componente
useEffect(() => {
checkSession();
}, [checkSession]);
return {
user: session.user,
isLoading: session.isLoading,
isAuthenticated: session.isAuthenticated,
logout,
refreshSession,
};
}