initialize method
Initialize the API key service with proper validation Delegates to native compiled code for sensitive operations
Implementation
Future<void> initialize({
String? apiKey,
String? environment,
bool autoInitWithAdmin = true,
bool enableLogging = false,
int timeout = 30000,
int retryAttempts = 3,
bool offlineMode = false,
}) async {
try {
if (enableLogging) {
OnairosDebugHelper.log('🔑 Initializing API Key Service with validation');
}
// Initialize native core - handles admin key derivation securely
final coreResult = await _nativeCore.initialize(
apiKey: apiKey,
environment: environment ?? 'production',
autoInitWithAdmin: autoInitWithAdmin,
);
if (!coreResult.success) {
throw Exception('Native core initialization failed: ${coreResult.message}');
}
// Get API base URL from native code (not exposed in Dart source)
_apiBaseUrl = await _nativeCore.getApiBaseUrl();
if (enableLogging && autoInitWithAdmin && apiKey == null) {
OnairosDebugHelper.log('⚠️ Using admin API key for development - apps should provide their own key');
}
// Validate API key using the validation service
if (apiKey != null) {
final validationService = ApiKeyValidationService();
final validationResult = await validationService.initializeApiKey(
apiKey: apiKey,
environment: environment ?? 'production',
enableLogging: enableLogging,
timeout: timeout,
retryAttempts: retryAttempts,
offlineMode: offlineMode,
);
if (!validationResult.isValid) {
final errorMsg = validationResult.error ?? 'Unknown error';
final errorCode = validationResult.code ?? 'UNKNOWN';
throw Exception('API key validation failed: $errorMsg (Code: $errorCode)');
}
if (enableLogging) {
OnairosDebugHelper.log('✅ API key validated successfully');
if (validationResult.message != null) {
OnairosDebugHelper.log(' ${validationResult.message}');
}
if (validationResult.permissions != null) {
OnairosDebugHelper.log('📋 Permissions: ${validationResult.permissions}');
}
}
}
// Store configuration
_currentApiKey = apiKey;
_environment = environment ?? 'production';
if (apiKey != null) {
await _storage.write(key: 'onairos_api_key', value: apiKey);
}
await _storage.write(key: 'onairos_environment', value: _environment!);
_isInitialized = true;
if (enableLogging) {
OnairosDebugHelper.log('✅ API Key Service initialized successfully');
}
} catch (e) {
OnairosDebugHelper.log('❌ Error initializing API Key Service: $e');
rethrow;
}
}