Files
GTA_Prod/GTA_P_V2/project/src/main.jsx
2026-01-12 12:43:50 +01:00

123 lines
5.2 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import App from './App.jsx';
import './index.css';
import { MsalProvider } from "@azure/msal-react";
import { PublicClientApplication, EventType } from "@azure/msal-browser";
import { msalConfig } from "./authConfig";
// ✅ CRITIQUE : Créer l'instance MSAL
const msalInstance = new PublicClientApplication(msalConfig);
// ✅ CRITIQUE : Fonction d'initialisation asynchrone
async function initializeApp() {
console.log('🚀 Initialisation de l\'application...');
console.log('🔗 Hash actuel:', window.location.hash);
console.log('📍 URL complète:', window.location.href);
// ✅ Sauvegarder le hash OAuth s'il existe (avant que quoi que ce soit ne le supprime)
const currentHash = window.location.hash;
if (currentHash && currentHash.includes('code=')) {
console.log('🚨 Hash OAuth détecté - Sauvegarde...');
sessionStorage.setItem('oauth_hash_backup', currentHash);
sessionStorage.setItem('oauth_url_backup', window.location.href);
sessionStorage.setItem('oauth_capture_time', Date.now().toString());
}
try {
// ✅ CRITIQUE : Initialiser MSAL (requis depuis MSAL 3.x)
console.log('⏳ Initialisation MSAL...');
await msalInstance.initialize();
console.log('✅ MSAL initialisé');
// ✅ CRITIQUE : Traiter la redirection OAuth AVANT le rendu React
console.log('⏳ Traitement handleRedirectPromise...');
const response = await msalInstance.handleRedirectPromise();
if (response) {
console.log('✅ Réponse OAuth reçue:', {
account: response.account?.username,
hasAccessToken: !!response.accessToken,
scopes: response.scopes
});
// Nettoyer le hash de l'URL après traitement réussi
window.history.replaceState({}, document.title, window.location.pathname);
// Nettoyer le backup
sessionStorage.removeItem('oauth_hash_backup');
sessionStorage.removeItem('oauth_url_backup');
sessionStorage.removeItem('oauth_capture_time');
} else {
console.log(' Pas de réponse OAuth (normal si pas de redirection en cours)');
// Vérifier s'il y avait un code mais pas de réponse (échec silencieux)
const backupHash = sessionStorage.getItem('oauth_hash_backup');
if (backupHash && backupHash.includes('code=')) {
const captureTime = sessionStorage.getItem('oauth_capture_time');
const elapsed = Date.now() - parseInt(captureTime || '0');
// Si le backup a moins de 30 secondes, c'est un échec récent
if (elapsed < 30000) {
console.warn('⚠️ Code OAuth détecté mais non traité par MSAL');
console.log('🔧 Le hash était:', backupHash.substring(0, 100) + '...');
}
// Nettoyer le backup après vérification
sessionStorage.removeItem('oauth_hash_backup');
sessionStorage.removeItem('oauth_url_backup');
sessionStorage.removeItem('oauth_capture_time');
}
}
// ✅ Configurer les événements MSAL pour le debug
msalInstance.addEventCallback((event) => {
if (event.eventType === EventType.LOGIN_SUCCESS) {
console.log('🎉 LOGIN_SUCCESS event:', event.payload?.account?.username);
}
if (event.eventType === EventType.LOGIN_FAILURE) {
console.error('❌ LOGIN_FAILURE event:', event.error);
}
if (event.eventType === EventType.ACQUIRE_TOKEN_SUCCESS) {
console.log('🔑 Token acquis pour:', event.payload?.account?.username);
}
if (event.eventType === EventType.HANDLE_REDIRECT_END) {
console.log('🏁 HANDLE_REDIRECT_END');
}
});
// ✅ Définir le compte actif si disponible
const accounts = msalInstance.getAllAccounts();
if (accounts.length > 0) {
console.log('📊 Comptes MSAL trouvés:', accounts.length);
msalInstance.setActiveAccount(accounts[0]);
console.log('✅ Compte actif défini:', accounts[0].username);
}
} catch (error) {
console.error('❌ Erreur lors de l\'initialisation MSAL:', error);
// En cas d'erreur, nettoyer et continuer
sessionStorage.removeItem('oauth_hash_backup');
sessionStorage.removeItem('oauth_url_backup');
sessionStorage.removeItem('oauth_capture_time');
// Nettoyer l'URL si elle contient encore le code
if (window.location.hash.includes('code=')) {
window.history.replaceState({}, document.title, window.location.pathname);
}
}
// ✅ Rendre l'application React APRÈS l'initialisation MSAL
console.log('🎨 Rendu de l\'application React...');
createRoot(document.getElementById('root')).render(
<StrictMode>
<MsalProvider instance={msalInstance}>
<App />
</MsalProvider>
</StrictMode>
);
}
// ✅ Lancer l'initialisation
initializeApp();