fix: pass full url to handleSignInCallback

This commit is contained in:
2026-04-20 20:58:29 +00:00
parent 643dbe1b34
commit 7e73398e5b
2 changed files with 18 additions and 43 deletions

2
dist/index.html vendored
View File

@@ -6,7 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="icon" href="/logo.png" type="image/png">
<title>Otimizador de Corte - TSCUT</title>
<script type="module" crossorigin src="/assets/index-B7sXKXk5.js"></script>
<script type="module" crossorigin src="/assets/index-BS71d1C4.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-CpYIvPGq.css">
</head>

View File

@@ -7,65 +7,40 @@ const style = document.createElement('style');
style.innerHTML = 'body { display: none !important; }';
document.head.appendChild(style);
// Implementação de Storage Persistente para evitar perdas em redirecionamentos
const persistentStorage = {
getItem: (key) => localStorage.getItem(key),
setItem: (key, value) => localStorage.setItem(key, value),
removeItem: (key) => localStorage.removeItem(key),
};
const logtoClient = new LogtoClient({
endpoint: import.meta.env.VITE_LOGTO_ENDPOINT,
appId: import.meta.env.VITE_LOGTO_APP_ID,
scopes: ['openid', 'offline_access', 'profile', 'email', 'organizations'],
storage: persistentStorage, // Força o uso de localStorage
});
async function protectPage() {
const urlParams = new URLSearchParams(window.location.search);
const isCallback = urlParams.has('code') && urlParams.has('state');
// Forçar a URI exata registrada no Logto para evitar variações de origin
const exactRedirectUri = 'https://tscut.reifonas.cloud/';
console.log('TSCUT Auth: Inicializando...', {
isCallback,
href: window.location.href,
storageKeys: Object.keys(localStorage).filter(k => k.includes('logto'))
});
// A URI exata para a qual o Logto vai devolver o usuário
const redirectUri = window.location.origin + '/';
if (isCallback) {
try {
console.log('TSCUT Auth: Processando callback com URI:', exactRedirectUri);
// CRÍTICO: handleSignInCallback precisa da URL COMPLETA para extrair o ?code= e &state=
await logtoClient.handleSignInCallback(window.location.href);
// Pequeno delay para garantir que o storage foi persistido pelo navegador
await new Promise(r => setTimeout(r, 100));
console.log('TSCUT Auth: Login bem sucedido!');
// Limpa os parâmetros da URL para evitar erro no reload manual
window.history.replaceState({}, document.title, redirectUri);
await logtoClient.handleSignInCallback(exactRedirectUri);
console.log('TSCUT Auth: Login OK! Redirecionando...');
window.location.assign('/');
style.remove();
} catch (error) {
style.remove();
const logtoState = localStorage.getItem(`logto:${import.meta.env.VITE_LOGTO_APP_ID}:state`);
document.body.innerHTML = `
<div style="padding: 20px; color: #ff5555; background: #1a1a1a; min-height: 100vh; font-family: sans-serif;">
<h1 style="color: white; border-bottom: 2px solid #ff5555; padding-bottom: 10px;">Falha na Identificação Industrial</h1>
<p style="font-size: 1.2em; background: #330000; padding: 15px; border-radius: 5px;">
Erro: ${error.message}
</p>
<div style="background: #222; padding: 15px; border-radius: 5px; margin-top: 20px; font-family: monospace; font-size: 0.9em; color: #aaa;">
<strong>Debug Info:</strong><br>
- AppID: ${import.meta.env.VITE_LOGTO_APP_ID}<br>
- URI Usada: ${exactRedirectUri}<br>
- State na URL: ${urlParams.get('state')?.substring(0, 10)}...<br>
- State no Storage: ${logtoState ? 'Presente' : 'AUSENTE'}<br>
</div>
<h1>Falha na Autenticação</h1>
<p style="font-size: 1.2em;">Erro: ${error.message}</p>
<button onclick="window.location.assign('/')" style="margin-top: 20px; padding: 12px 25px; cursor: pointer; background: #444; color: white; border: none; border-radius: 5px; font-weight: bold;">
🔄 Tentar Novamente (Limpar Sessão)
Tentar Novamente
</button>
</div>`;
console.error('Falha crítica no callback:', error);
console.error('Falha no callback do Logto:', error);
}
return;
}
@@ -73,16 +48,16 @@ async function protectPage() {
try {
const isAuthenticated = await logtoClient.isAuthenticated();
if (!isAuthenticated) {
console.log('TSCUT Auth: Iniciando fluxo de login...');
await logtoClient.signIn(exactRedirectUri);
console.log('TSCUT Auth: Não autenticado. Redirecionando...');
await logtoClient.signIn(redirectUri);
return;
}
// Acesso permitido
style.remove();
console.log('TSCUT: Acesso autorizado.');
} catch (err) {
console.error('Erro na verificação de sessão:', err);
await logtoClient.signIn(exactRedirectUri);
console.error('Erro de autenticação:', err);
await logtoClient.signIn(redirectUri);
}
}