56 lines
1.5 KiB
TypeScript
56 lines
1.5 KiB
TypeScript
'use client';
|
|
|
|
import { useEffect, useState } from 'react';
|
|
import { jwtDecode } from 'jwt-decode';
|
|
import GetSigla from '@/shared/actions/text/GetSigla';
|
|
import GUsuarioAuthenticatedInterface from '@/shared/interfaces/UserAuthenticatedInterface';
|
|
|
|
interface JwtPayload {
|
|
id: string;
|
|
iat: number;
|
|
exp: number;
|
|
data?: GUsuarioAuthenticatedInterface;
|
|
}
|
|
|
|
export default function useGUsuarioGetJWTHook() {
|
|
const [userAuthenticated, setUserAuthenticated] = useState<JwtPayload | null>(null);
|
|
|
|
useEffect(() => {
|
|
async function fetchToken() {
|
|
try {
|
|
// Lê o token diretamente do cookie (lado do cliente)
|
|
const token = document.cookie
|
|
.split('; ')
|
|
.find(row => row.startsWith('access_token='))
|
|
?.split('=')[1];
|
|
|
|
// Se não houver token, apenas sai (sem erro nem redirecionamento)
|
|
if (!token) {
|
|
console.warn('Token ausente ou inválido no cookie.');
|
|
return;
|
|
}
|
|
|
|
// Decodifica o JWT
|
|
const decoded = jwtDecode<JwtPayload>(token);
|
|
|
|
// Se o campo data for string JSON, converte e adiciona sigla
|
|
if (decoded.data && typeof decoded.data === 'string') {
|
|
decoded.data = JSON.parse(decoded.data);
|
|
}
|
|
|
|
if (decoded.data) {
|
|
decoded.data.sigla = GetSigla(decoded.data.nome || '');
|
|
}
|
|
|
|
// Salva no estado global/local
|
|
setUserAuthenticated(decoded);
|
|
} catch (error) {
|
|
console.error('Erro ao buscar token:', error);
|
|
}
|
|
}
|
|
|
|
fetchToken();
|
|
}, []);
|
|
|
|
return { userAuthenticated };
|
|
}
|