authenticate method
Implementation
Future<bool> authenticate() async {
final credentials = auth.ClientId(clientId, clientSecret);
// Check if credentials are already stored
if (await File(credentialsFilePath).exists()) {
try {
// Read the credentials from the file
final jsonString = await File(credentialsFilePath).readAsString();
final jsonCredentials =
auth.AccessCredentials.fromJson(json.decode(jsonString));
// Create an authenticated client using the stored credentials
_client = auth.autoRefreshingClient(
credentials,
jsonCredentials,
http.Client(),
);
_driveApi = drive.DriveApi(_client);
print('🔐 Reusing existing credentials. Authentication successful!');
return true;
} catch (e) {
print('Error using stored credentials: $e');
// Fall back to requesting new credentials if there is an error
}
}
try {
// Request new credentials if no valid stored credentials
_client = await auth.clientViaUserConsent(
credentials,
[drive.DriveApi.driveFileScope],
(url) {
Helpers.showHighlight(
firstMessage: 'Please visit the following URL to authenticate:',
highLightmessage: url,
);
},
);
_driveApi = drive.DriveApi(_client);
// Save the credentials for future use
final accessCredentials = _client.credentials;
await File(credentialsFilePath)
.writeAsString(json.encode(accessCredentials.toJson()));
print('🔐 Authentication successful and credentials saved!');
return true;
} catch (e) {
print('Error during authentication: $e');
return false;
}
}