Revert "V1_Sans_Congé_Anticipéfemini collaboratrice"

This reverts commit 0eb4dbb99b.
This commit is contained in:
2025-11-17 10:34:50 +01:00
parent 0eb4dbb99b
commit 7f15e380e3
41 changed files with 2740 additions and 30354 deletions

View File

@@ -6,7 +6,9 @@ const AuthContext = createContext();
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) throw new Error('useAuth must be used within an AuthProvider');
if (!context) {
throw new Error('useAuth must be used within an AuthProvider');
}
return context;
};
@@ -14,17 +16,25 @@ const msalInstance = new msal.PublicClientApplication(msalConfig);
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [userGroups, setUserGroups] = useState([]);
const [isAuthorized, setIsAuthorized] = useState(false);
const [isLoading, setIsLoading] = useState(true);
const [isMsalInitialized, setIsMsalInitialized] = useState(false);
const getApiUrl = (endpoint) => `http://localhost:3000/${endpoint}`;
// Fonction pour obtenir l'URL de l'API backend
const getApiUrl = (endpoint) => {
const possibleUrls = [
'http://localhost/GTA/project/public/php/',
'http://localhost:80/GTA/project/public/php/',
'http://localhost/GTA/public/php/',
'http://localhost/public/php/'
];
return possibleUrls[0] + endpoint; // Utilisez votre URL préférée
};
// --- Vérifie l'autorisation de l'utilisateur via groupes
// Vérifier les groupes utilisateur via l'API backend
const checkUserAuthorization = async (userPrincipalName, accessToken) => {
try {
const response = await fetch(getApiUrl('check-user-groups'), {
const response = await fetch(getApiUrl('check-user-groups.php'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -46,22 +56,30 @@ export const AuthProvider = ({ children }) => {
}
};
// --- Synchronisation utilisateur connecté
// Synchroniser l'utilisateur avec la base locale
const syncUserToDatabase = async (entraUser, accessToken) => {
try {
const response = await fetch(getApiUrl('initial-sync'), {
const response = await fetch(getApiUrl('check-user-groups.php'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${accessToken}`
},
body: JSON.stringify(entraUser)
body: JSON.stringify({
entraUserId: entraUser.id,
userPrincipalName: entraUser.userPrincipalName,
email: entraUser.mail || entraUser.userPrincipalName,
displayName: entraUser.displayName,
givenName: entraUser.givenName,
surname: entraUser.surname,
jobTitle: entraUser.jobTitle,
department: entraUser.department,
officeLocation: entraUser.officeLocation
})
});
if (response.ok) {
const data = await response.json();
console.log('Utilisateur synchronisé:', entraUser.userPrincipalName);
return data;
return await response.json();
}
} catch (error) {
console.error('Erreur synchronisation utilisateur:', error);
@@ -69,52 +87,22 @@ export const AuthProvider = ({ children }) => {
return null;
};
// --- Full sync admin
const fullSyncDatabase = async (accessToken) => {
try {
const response = await fetch(getApiUrl('initial-sync'), {
method: 'POST',
headers: { 'Authorization': `Bearer ${accessToken}` }
});
if (response.ok) {
const data = await response.json();
console.log('Full sync terminée:', data);
return data;
}
} catch (error) {
console.error('Erreur full sync:', error);
}
return null;
};
// --- S'assurer que MSAL est initialisé avant tout appel
const ensureMsalInitialized = async () => {
if (!isMsalInitialized) {
try {
await msalInstance.initialize();
setIsMsalInitialized(true);
console.log('MSAL initialisé');
} catch (error) {
console.error('Erreur initialisation MSAL:', error);
throw error;
}
}
};
// --- Initialisation au chargement
// Initialisation MSAL
useEffect(() => {
const initializeMsal = async () => {
try {
await ensureMsalInitialized();
await msalInstance.initialize();
// Vérifier si il y a un utilisateur connecté
const accounts = msalInstance.getAllAccounts();
if (accounts.length > 0) {
// Essayer de récupérer un token silencieusement
try {
const response = await msalInstance.acquireTokenSilent({
...loginRequest,
account: accounts[0]
});
await handleSuccessfulAuth(response);
} catch (error) {
console.log('Token silent acquisition failed:', error);
@@ -130,12 +118,18 @@ export const AuthProvider = ({ children }) => {
initializeMsal();
}, []);
// --- Gestion login réussi
// Gérer l'authentification réussie
// Gérer l'authentification réussie
const handleSuccessfulAuth = async (authResponse) => {
try {
const account = authResponse.account;
const accessToken = authResponse.accessToken;
// 🔹 Récupérer profil Microsoft Graph
const graphResponse = await fetch('https://graph.microsoft.com/v1.0/me', {
headers: { 'Authorization': `Bearer ${accessToken}` }
});
let entraUser = {
id: account.homeAccountId,
displayName: account.name,
@@ -143,31 +137,35 @@ export const AuthProvider = ({ children }) => {
mail: account.username
};
const graphResponse = await fetch('https://graph.microsoft.com/v1.0/me', {
headers: { 'Authorization': `Bearer ${accessToken}` }
});
if (graphResponse.ok) {
const graphData = await graphResponse.json();
entraUser = { ...entraUser, ...graphData };
}
// 1 Synchroniser lutilisateur connecté
// 🔹 Synchroniser lutilisateur dans la DB
const syncResult = await syncUserToDatabase(entraUser, accessToken);
console.log("Résultat syncUserToDatabase:", syncResult);
// 2⃣ Full sync si admin
if (syncResult?.role === 'Admin') {
console.log('Admin détecté → lancement full sync...');
await fullSyncDatabase(accessToken);
// 🚀 Si admin → lancer full-sync.php
if (syncResult?.role === "Admin") {
try {
const syncResp = await fetch(getApiUrl('full-sync.php'), {
method: "POST",
headers: { "Authorization": `Bearer ${accessToken}` }
});
const syncData = await syncResp.json();
console.log("Résultat Full Sync:", syncData);
} catch (err) {
console.error("Erreur synchronisation groupes:", err);
}
}
// 3 Vérifier groupes
// 🔹 Vérifier autorisation via groupes DB
const authResult = await checkUserAuthorization(entraUser.userPrincipalName, accessToken);
if (authResult.authorized) {
setUser({
const userData = {
id: syncResult?.localUserId || entraUser.id,
CollaborateurADId: syncResult?.localUserId, // ⭐ AJOUT
entraUserId: entraUser.id,
name: entraUser.displayName,
prenom: entraUser.givenName || entraUser.displayName?.split(' ')[0] || '',
@@ -175,15 +173,22 @@ export const AuthProvider = ({ children }) => {
email: entraUser.mail || entraUser.userPrincipalName,
userPrincipalName: entraUser.userPrincipalName,
role: syncResult?.role || 'Employe',
service: syncResult?.service || entraUser.department || 'Non défini',
// ✅ Correction ici
service: syncResult?.service
|| syncResult?.user?.service
|| entraUser.department
|| 'Non défini',
jobTitle: entraUser.jobTitle,
department: entraUser.department,
officeLocation: entraUser.officeLocation,
typeContrat: syncResult?.typeContrat || '37h', // ⭐ AJOUT
dateEntree: syncResult?.dateEntree || null, // ⭐ AJOUT
groups: authResult.groups
});
};
setUser(userData);
setIsAuthorized(true);
return true;
} else {
throw new Error('Utilisateur non autorisé - pas membre des groupes requis');
}
@@ -193,20 +198,32 @@ export const AuthProvider = ({ children }) => {
}
};
// --- Connexion classique
// Connexion classique (email/mot de passe)
const login = async (email, password) => {
try {
const response = await fetch(getApiUrl('login'), {
const response = await fetch(getApiUrl('login.php'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, mot_de_passe: password })
body: JSON.stringify({ email, mot_de_passe: password }),
});
if (!response.ok) throw new Error('Erreur de connexion');
if (!response.ok) {
throw new Error('Erreur de connexion');
}
const text = await response.text();
let data;
try {
data = JSON.parse(text);
} catch {
console.error("Réponse non-JSON:", text.substring(0, 200));
throw new Error("Le serveur PHP ne répond pas correctement.");
}
const data = await response.json();
if (data.success) {
setUser({
const userData = {
id: data.user.id,
name: `${data.user.prenom} ${data.user.nom}`,
prenom: data.user.prenom,
@@ -214,7 +231,9 @@ export const AuthProvider = ({ children }) => {
email: data.user.email,
role: data.user.role || 'Employe',
service: data.user.service || 'Non défini'
});
};
setUser(userData);
setIsAuthorized(true);
return true;
}
@@ -225,10 +244,9 @@ export const AuthProvider = ({ children }) => {
}
};
// --- Connexion Office 365
// Connexion Office 365
const loginWithO365 = async () => {
try {
await ensureMsalInitialized();
const authResponse = await msalInstance.loginPopup(loginRequest);
await handleSuccessfulAuth(authResponse);
return true;
@@ -241,12 +259,14 @@ export const AuthProvider = ({ children }) => {
}
};
// --- Déconnexion
// Déconnexion
const logout = async () => {
try {
const accounts = msalInstance.getAllAccounts();
if (accounts.length > 0) {
await msalInstance.logoutPopup({ account: accounts[0] });
await msalInstance.logoutPopup({
account: accounts[0]
});
}
} catch (error) {
console.error('Erreur lors de la déconnexion:', error);
@@ -257,12 +277,13 @@ export const AuthProvider = ({ children }) => {
}
};
// --- Obtenir token API
// Obtenir un token pour l'API
const getAccessToken = async () => {
try {
await ensureMsalInitialized();
const accounts = msalInstance.getAllAccounts();
if (accounts.length === 0) throw new Error('Aucun compte connecté');
if (accounts.length === 0) {
throw new Error('Aucun compte connecté');
}
const response = await msalInstance.acquireTokenSilent({
...loginRequest,
@@ -287,7 +308,11 @@ export const AuthProvider = ({ children }) => {
getAccessToken
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
return (
<AuthContext.Provider value={value}>
{children}
</AuthContext.Provider>
);
};
export default AuthContext;
export default AuthContext;