authenticate method
Performs OAuth2 authentication using the system browser
Returns the authorization code from the callback URL. Throws FrappeAuthException for various error scenarios.
Implementation
Future<String> authenticate({
required String authorizationUrl,
required String callbackUrlScheme,
}) async {
try {
// Perform web authentication with timeout options
// The timeout ensures the Chrome Custom Tab closes automatically
// and prevents indefinite waiting for user authentication
final result = await FlutterWebAuth2.authenticate(
url: authorizationUrl,
callbackUrlScheme: callbackUrlScheme,
options: const FlutterWebAuth2Options(
timeout: 120, // 2 minutes - gives users time to enter credentials
),
);
// Extract authorization code from callback URL
final code = _extractAuthorizationCode(result);
if (code == null) {
throw FrappeNetworkException(
'No authorization code found in callback URL',
);
}
return code;
} catch (e) {
if (e is FrappeAuthException) {
rethrow;
}
// Handle flutter_web_auth_2 specific errors
if (e.toString().contains('User cancelled')) {
throw FrappeUserCancelledException(
'User cancelled the authentication process',
);
}
if (e.toString().contains('RESULT_CANCELED')) {
throw FrappeUserCancelledException('Authentication was cancelled');
}
// Generic authentication error
throw FrappeNetworkException(
'Authentication failed: ${e.toString()}',
originalError: e,
);
}
}