handleRedirect static method

Future<AuthorizationTokenResponse?> handleRedirect(
  1. String url,
  2. OAuthProvider provider
)

Handles the redirect URL after authorization.

Validates the state parameter and exchanges the code for tokens.

Implementation

static Future<AuthorizationTokenResponse?> handleRedirect(
  String url,
  OAuthProvider provider,
) async {
  try {
    final uri = Uri.parse(url);
    final error = uri.queryParameters['error'];

    if (error != null) {
      throw OAuthException.fromOAuthError(
        Map<String, String>.from(uri.queryParameters),
      );
    }

    final code = uri.queryParameters['code'];
    final returnedState = uri.queryParameters['state'];

    if (returnedState != _state) {
      throw const OAuthException(
        message: 'Invalid state parameter',
        code: 'invalid_state',
      );
    }

    if (code == null) {
      throw const OAuthException(
        message: 'No authorization code found in redirect URL',
        code: 'missing_code',
      );
    }

    return await _exchangeCodeForToken(code, provider);
  } catch (e, stackTrace) {
    dev.log(
      'Error handling redirect',
      error: e,
      stackTrace: stackTrace,
    );
    return null;
  }
}