setupAuthenticationHandler method

void setupAuthenticationHandler(
  1. InAppWebViewController controller
)

Sets up the onPostAuthentication JavaScript handler

Implementation

void setupAuthenticationHandler(InAppWebViewController controller) {
  controller.addJavaScriptHandler(
    handlerName: 'onPostAuthentication',
    callback: (args) async {
      _log('[DEBUG] Received message from JS channel: $args');
      _log('[DEBUG] Handler name: onPostAuthentication');
      _log('[DEBUG] Arguments received: $args');

      try {
        // Handle both String and Map formats
        Map<String, dynamic> tokenMap;
        if (args.isNotEmpty && args[0] is String) {
          tokenMap = jsonDecode(args[0] as String);
        } else if (args.isNotEmpty && args[0] is Map) {
          tokenMap = Map<String, dynamic>.from(args[0] as Map);
        } else {
          _log('[DEBUG] Args received: $args');
          _log('[DEBUG] Args type: ${args.runtimeType}');
          _log('[DEBUG] Args length: ${args.length}');
          if (args.isNotEmpty) {
            _log(
              '[DEBUG] First arg type: ${args[0].runtimeType}',
            );
          }
          throw Exception(
            'Unexpected data format. Expected Map or JSON String, got: ${args.runtimeType}',
          );
        }

        _log('[DEBUG] Parsed tokens: $tokenMap');
        _log('[DEBUG] Token value: ${tokenMap['token']}');
        _log('[DEBUG] Email value: ${tokenMap['email']}');
        _log('[DEBUG] User ID value: ${tokenMap['user_id']}');
        _log('[DEBUG] Refresh Token value: ${tokenMap['refresh_token']}');
        _log('[DEBUG] Device Key value: ${tokenMap['device_key']}');
        _log(
          '[DEBUG] All keys in tokenMap: ${tokenMap.keys.toList()}',
        );

        // Extract token, email, and user_id from the response with null checks
        final accessToken = tokenMap['token'] as String?;
        final refreshToken = tokenMap['refresh_token'] as String?;
        final deviceKey = tokenMap['device_key'] as String?;
        final email = tokenMap['email'] as String?;
        final userId = tokenMap['user_id'] as String?;

        // Validate that all required fields are present
        if (accessToken == null || accessToken.isEmpty) {
          _log('[DEBUG] access token issue');
          throw Exception('Access token is missing or empty');
        }
        if (email == null || email.isEmpty) {
          _log('[DEBUG] email issue');
          throw Exception('Email is missing or empty');
        }
        if (userId == null || userId.isEmpty) {
          _log('[DEBUG] userId issue');
          throw Exception('User ID is missing or empty');
        }
        if (refreshToken == null || refreshToken.isEmpty) {
          _log('[DEBUG] refreshToken issue');
          throw Exception('Refresh Token is missing or empty');
        }

        await TokenStorage.saveTokens(
          accessToken: accessToken!,
          refreshToken: refreshToken, // Not provided in this format
          deviceKey: deviceKey, // Not provided in this format
          idToken: null, // Not provided in this format
          email: email!,
          userId: userId!,
        );
        _log('[DEBUG] Tokens saved to secure storage.');

        // Use the callback to handle success
        onSuccess(accessToken!, email!, userId!);
      } catch (e) {
        _log('[ERROR] Error parsing or saving tokens: $e');

        // Use the callback to handle error
        onError();
      }
    },
  );
}