import "msal_bridge.dart"; enum AuthenticationMode { demo, azure } class AuthService { AuthService._(); static const String _configuredMode = String.fromEnvironment( "AUTH_MODE", defaultValue: "demo", ); static const String azureTenantId = String.fromEnvironment("AZURE_TENANT_ID"); static const String azureSpaClientId = String.fromEnvironment( "AZURE_SPA_CLIENT_ID", ); static const String azureApiScope = String.fromEnvironment("AZURE_API_SCOPE"); static const String demoStudentEmail = "lucas.martin@ensitech.eu"; static const String demoResponsableEmail = "karim.benali@ensup.eu"; static String? _demoEmail; static bool _azureInitialized = false; static AuthenticationMode get mode { return switch (_configuredMode) { "demo" => AuthenticationMode.demo, "azure" => AuthenticationMode.azure, _ => throw StateError("AUTH_MODE doit valoir demo ou azure."), }; } static void selectDemoStudent() { _ensureDemoMode(); _demoEmail = demoStudentEmail; } static void selectDemoResponsable() { _ensureDemoMode(); _demoEmail = demoResponsableEmail; } static void clearSession() { _demoEmail = null; } static Future signInWithMicrosoft() async { await _initializeAzure(); await MsalBridge.signIn(); } static Future hasMicrosoftAccount() async { await _initializeAzure(); return MsalBridge.hasAccount(); } static Future signOut() async { if (mode == AuthenticationMode.azure) { await _initializeAzure(); await MsalBridge.signOut(); return; } clearSession(); } static Future> requestHeaders() async { if (mode == AuthenticationMode.azure) { await _initializeAzure(); final token = await MsalBridge.getAccessToken(); return {"authorization": "Bearer $token"}; } final email = _demoEmail; if (email == null) { throw StateError("Aucun utilisateur de demonstration selectionne."); } return {"x-user-email": email}; } static Future _initializeAzure() async { if (mode != AuthenticationMode.azure) { throw StateError("MSAL est disponible uniquement en mode Azure."); } if (_azureInitialized) { return; } if (azureTenantId.isEmpty || azureSpaClientId.isEmpty || azureApiScope.isEmpty) { throw StateError("La configuration Azure du frontend est incomplete."); } await MsalBridge.initialize( tenantId: azureTenantId, clientId: azureSpaClientId, scope: azureApiScope, redirectUri: Uri.base.origin, ); _azureInitialized = true; } static void _ensureDemoMode() { if (mode != AuthenticationMode.demo) { throw StateError( "Une identite de demonstration est interdite en mode Azure.", ); } } }