connexion avec o365

This commit is contained in:
2025-08-12 16:14:44 +02:00
parent 871f166457
commit e1e4e81420
5 changed files with 119 additions and 7 deletions

View File

@@ -1,4 +1,5 @@
import React, { createContext, useContext, useState, useEffect } from 'react';
import * as msal from '@azure/msal-browser';
const AuthContext = createContext();
@@ -10,11 +11,32 @@ export const useAuth = () => {
return context;
};
const msalConfig = {
auth: {
clientId: '4bb4cc24-bac3-427c-b02c-5d14fc67b561',
authority: 'https://login.microsoftonline.com/9840a2a0-6ae1-4688-b03d-d2ec291be0f9',
redirectUri: window.location.origin,
},
};
const msalInstance = new msal.PublicClientApplication(msalConfig);
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [isLoading, setIsLoading] = useState(true);
// Initialise MSAL au montage
useEffect(() => {
const initializeMsal = async () => {
try {
await msalInstance.initialize();
} catch (error) {
console.error("Erreur d'initialisation MSAL:", error);
}
};
initializeMsal();
const savedUser = localStorage.getItem('user');
if (savedUser) {
try {
@@ -88,12 +110,37 @@ export const AuthProvider = ({ children }) => {
}
};
const loginWithO365 = async () => {
try {
const loginResponse = await msalInstance.loginPopup({
scopes: ["user.read"]
});
const account = loginResponse.account;
if (account) {
const userData = {
id: account.homeAccountId,
name: account.name,
email: account.username,
role: 'Employe',
service: 'Non défini',
};
setUser(userData);
localStorage.setItem('user', JSON.stringify(userData));
return true;
}
return false;
} catch (error) {
console.error('Erreur login Office 365:', error);
return false;
}
};
const logout = () => {
setUser(null);
localStorage.removeItem('user');
};
const value = { user, login, logout, isLoading };
const value = { user, login, loginWithO365, logout, isLoading };
return (
<AuthContext.Provider value={value}>