Files
EME_APP/eme-frontend/lib/services/auth_service.dart
T
2026-07-23 14:39:35 +02:00

123 lines
3.2 KiB
Dart

import "../models/authenticated_profile.dart";
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 AuthenticatedProfile? _currentProfile;
static bool _azureInitialized = false;
static AuthenticatedProfile? get currentProfile => _currentProfile;
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;
_currentProfile = null;
}
static AuthenticatedProfile setProfileFromApi(dynamic reponse) {
final profile = AuthenticatedProfile.fromApi(reponse);
_currentProfile = profile;
return profile;
}
static Future<void> signInWithMicrosoft() async {
await _initializeAzure();
await MsalBridge.signIn();
}
static Future<bool> hasMicrosoftAccount() async {
await _initializeAzure();
return MsalBridge.hasAccount();
}
static Future<void> signOut() async {
if (mode == AuthenticationMode.azure) {
await _initializeAzure();
await MsalBridge.signOut();
_currentProfile = null;
return;
}
clearSession();
}
static Future<Map<String, String>> 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<void> _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.",
);
}
}
}