import 'dart:convert'; import 'package:googleapis_auth/auth_io.dart'; class AccessTokenManager { static final AccessTokenManager _instance = AccessTokenManager._internal(); late final String serviceAccountJsonKey; AccessToken? _accessToken; DateTime? _expiryDate; AccessTokenManager._internal(); factory AccessTokenManager(String jsonKey) { if (_instance._isServiceAccountKeyInitialized()) { print('Service account key already initialized.'); return _instance; } print('Initializing service account key.'); _instance.serviceAccountJsonKey = jsonKey; return _instance; } bool _isServiceAccountKeyInitialized() { try { serviceAccountJsonKey; // Access to check if initialized return true; } catch (e) { return false; } } Future getAccessToken() async { print('Attempting to get a new access token...'); try { // Parse service account credentials from JSON print('Parsing service account credentials...'); final serviceAccountCredentials = ServiceAccountCredentials.fromJson( json.decode(serviceAccountJsonKey)); // Log service account email (or other non-sensitive information) print('Service account email: ${serviceAccountCredentials.email}'); // Create an authenticated client via the service account print('Creating authenticated client via service account...'); final client = await clientViaServiceAccount( serviceAccountCredentials, ['https://www.googleapis.com/auth/firebase.messaging'], ); // Log successful client creation print('Authenticated client created successfully.'); // Update the access token and expiry date _accessToken = client.credentials.accessToken; _expiryDate = client.credentials.accessToken.expiry; // Log the obtained token and expiry time print('Access token obtained: ${_accessToken!.data}'); print('Token expiry date: $_expiryDate'); // Close the client to prevent resource leaks print('Closing authenticated client...'); client.close(); // Return the newly fetched access token return _accessToken!.data; } catch (e) { // Log error if token fetch fails print('Failed to obtain a new access token: $e'); throw Exception('Failed to obtain a new access token: $e'); } } }