From 61530416074f23f4abc595e3435495ceb14d39c2 Mon Sep 17 00:00:00 2001 From: Canmi <9997200@qq.com> Date: Mon, 14 Apr 2025 23:22:56 +0800 Subject: [PATCH] fix: handle --- oauth_auth.py | 291 ++++++++++++++++++++++---------------------------- 1 file changed, 126 insertions(+), 165 deletions(-) diff --git a/oauth_auth.py b/oauth_auth.py index 0c518a3..b15c71a 100644 --- a/oauth_auth.py +++ b/oauth_auth.py @@ -6,7 +6,7 @@ import random import webbrowser import sys import json -import logging # Added for detailed logging +import logging from DrissionPage import ChromiumPage, ChromiumOptions from cursor_auth import CursorAuth from utils import get_random_wait_time, get_default_browser_path @@ -72,14 +72,13 @@ class OAuthHandler: profiles.append((item, profile_names.get(item, item))) return sorted(profiles) except Exception as e: - logger.error(f"Error loading Chrome profiles: {str(e)}") # Enhanced logging + logger.error(f"Error loading Chrome profiles: {str(e)}") print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('chrome_profile.error_loading', error=str(e)) if self.translator else f'Error loading Chrome profiles: {e}'}{Style.RESET_ALL}") return [] def _select_profile(self): """Allow user to select a browser profile to use""" try: - # 从配置中获取浏览器类型 config = get_config(self.translator) browser_type = config.get('Browser', 'default_browser', fallback='chrome') browser_type_display = browser_type.capitalize() @@ -91,10 +90,8 @@ class OAuthHandler: print(f"{Fore.CYAN}{EMOJI['INFO']} Select {browser_type_display} profile to use:{Style.RESET_ALL}") print(f"Available {browser_type_display} profiles:") - # Get the user data directory for the browser type user_data_dir = self._get_user_data_directory() - # Load available profiles from the selected browser type try: local_state_file = os.path.join(user_data_dir, "Local State") if os.path.exists(local_state_file): @@ -153,13 +150,13 @@ class OAuthHandler: return True except Exception as e: - logger.error(f"Error loading profiles: {str(e)}") # Enhanced logging + logger.error(f"Error loading profiles: {str(e)}") print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('browser_profile.error_loading', error=str(e), browser=browser_type_display) if self.translator else f'Error loading {browser_type_display} profiles: {str(e)}'}{Style.RESET_ALL}") self.selected_profile = "Default" return True except Exception as e: - logger.error(f"Profile selection error: {str(e)}") # Enhanced logging + logger.error(f"Profile selection error: {str(e)}") print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.profile_selection_error', error=str(e)) if self.translator else f'Error during profile selection: {str(e)}'}{Style.RESET_ALL}") self.selected_profile = "Default" return True @@ -167,11 +164,11 @@ class OAuthHandler: def setup_browser(self): """Setup browser for OAuth flow using selected profile""" try: - logger.info("Initializing browser setup") # Enhanced logging + logger.info("Initializing browser setup") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.initializing_browser_setup') if self.translator else 'Initializing browser setup...'}{Style.RESET_ALL}") platform_name = platform.system().lower() - logger.info(f"Detected platform: {platform_name}") # Enhanced logging + logger.info(f"Detected platform: {platform_name}") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.detected_platform', platform=platform_name) if self.translator else f'Detected platform: {platform_name}'}{Style.RESET_ALL}") config = get_config(self.translator) @@ -189,10 +186,10 @@ class OAuthHandler: "- macOS: Google Chrome, Chromium\n" + "- Linux: Google Chrome, Chromium, google-chrome-stable" ) - logger.error("No compatible browser found") # Enhanced logging + logger.error("No compatible browser found") raise Exception(error_msg) - logger.info(f"Found browser data directory: {user_data_dir}") # Enhanced logging + logger.info(f"Found browser data directory: {user_data_dir}") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.found_browser_data_directory', path=user_data_dir) if self.translator else f'Found browser data directory: {user_data_dir}'}{Style.RESET_ALL}") if self.translator: @@ -204,33 +201,33 @@ class OAuthHandler: choice = input(f"{Fore.YELLOW} {self.translator.get('menu.continue_prompt', choices='y/N')} {Style.RESET_ALL}").lower() if choice != 'y': - logger.info("Operation cancelled by user") # Enhanced logging + logger.info("Operation cancelled by user") print(f"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('menu.operation_cancelled_by_user') if self.translator else 'Operation cancelled by user'}{Style.RESET_ALL}") return False self._kill_browser_processes() if not self._select_profile(): - logger.info("Operation cancelled by user during profile selection") # Enhanced logging + logger.info("Operation cancelled by user during profile selection") print(f"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('menu.operation_cancelled_by_user') if self.translator else 'Operation cancelled by user'}{Style.RESET_ALL}") return False co = self._configure_browser_options(browser_path, user_data_dir, self.selected_profile) - logger.info(f"Starting browser at: {browser_path}") # Enhanced logging + logger.info(f"Starting browser at: {browser_path}") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.starting_browser', path=browser_path) if self.translator else f'Starting browser at: {browser_path}'}{Style.RESET_ALL}") self.browser = ChromiumPage(co) if not self.browser: - logger.error("Failed to initialize browser instance") # Enhanced logging + logger.error("Failed to initialize browser instance") raise Exception(f"{self.translator.get('oauth.browser_failed_to_start') if self.translator else 'Failed to initialize browser instance'}") - logger.info("Browser setup completed successfully") # Enhanced logging + logger.info("Browser setup completed successfully") print(f"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.browser_setup_completed') if self.translator else 'Browser setup completed successfully'}{Style.RESET_ALL}") return True except Exception as e: - logger.error(f"Browser setup failed: {str(e)}", exc_info=True) # Enhanced logging with stack trace + logger.error(f"Browser setup failed: {str(e)}", exc_info=True) print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.browser_setup_failed', error=str(e)) if self.translator else f'Browser setup failed: {str(e)}'}{Style.RESET_ALL}") if "DevToolsActivePort file doesn't exist" in str(e): print(f"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.try_running_without_sudo_admin') if self.translator else 'Try running without sudo/administrator privileges'}{Style.RESET_ALL}") @@ -284,7 +281,7 @@ class OAuthHandler: processes = browser_processes.get(browser_type, browser_processes['chrome']).get(platform_type, []) - logger.info(f"Killing {browser_type} processes: {processes}") # Enhanced logging + logger.info(f"Killing {browser_type} processes: {processes}") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.killing_browser_processes', browser=browser_type) if self.translator else f'Killing {browser_type} processes...'}{Style.RESET_ALL}") if os.name == 'nt': @@ -296,7 +293,7 @@ class OAuthHandler: time.sleep(1) except Exception as e: - logger.warning(f"Could not kill browser processes: {str(e)}") # Enhanced logging + logger.warning(f"Could not kill browser processes: {str(e)}") print(f"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.warning_could_not_kill_existing_browser_processes', error=str(e)) if self.translator else f'Warning: Could not kill existing browser processes: {e}'}{Style.RESET_ALL}") def _get_user_data_directory(self): @@ -337,16 +334,16 @@ class OAuthHandler: user_data_dir = user_data_dirs.get(browser_type) if user_data_dir and os.path.exists(user_data_dir): - logger.info(f"Found {browser_type} user data directory: {user_data_dir}") # Enhanced logging + logger.info(f"Found {browser_type} user data directory: {user_data_dir}") print(f"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.found_browser_user_data_dir', browser=browser_type, path=user_data_dir) if self.translator else f'Found {browser_type} user data directory: {user_data_dir}'}{Style.RESET_ALL}") return user_data_dir else: - logger.warning(f"{browser_type} user data directory not found at {user_data_dir}, trying Chrome") # Enhanced logging + logger.warning(f"{browser_type} user data directory not found at {user_data_dir}, trying Chrome") print(f"{Fore.YELLOW}{EMOJI['WARNING']} {self.translator.get('oauth.user_data_dir_not_found', browser=browser_type, path=user_data_dir) if self.translator else f'{browser_type} user data directory not found at {user_data_dir}, will try Chrome instead'}{Style.RESET_ALL}") return user_data_dirs['chrome'] except Exception as e: - logger.error(f"Error getting user data directory: {str(e)}") # Enhanced logging + logger.error(f"Error getting user data directory: {str(e)}") print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.error_getting_user_data_directory', error=str(e)) if self.translator else f'Error getting user data directory: {e}'}{Style.RESET_ALL}") if os.name == 'nt': return os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Google', 'Chrome', 'User Data') @@ -364,7 +361,7 @@ class OAuthHandler: browser_path = config.get('Browser', f'{browser_type}_path', fallback=None) if browser_path and os.path.exists(browser_path): - logger.info(f"Using configured {browser_type} path: {browser_path}") # Enhanced logging + logger.info(f"Using configured {browser_type} path: {browser_path}") print(f"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.using_configured_browser_path', browser=browser_type, path=browser_path) if self.translator else f'Using configured {browser_type} path: {browser_path}'}{Style.RESET_ALL}") return browser_path @@ -372,7 +369,7 @@ class OAuthHandler: if browser_path and os.path.exists(browser_path): return browser_path - logger.info("Searching for alternative browser installations") # Enhanced logging + logger.info("Searching for alternative browser installations") print(f"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.searching_for_alternative_browser_installations') if self.translator else 'Searching for alternative browser installations...'}{Style.RESET_ALL}") if os.name == 'nt': @@ -400,8 +397,7 @@ class OAuthHandler: os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Programs', 'Opera', 'launcher.exe'), os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Programs', 'Opera', 'opera.exe'), os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Programs', 'Opera GX', 'launcher.exe'), - os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Programs', 'Oper -a GX', 'opera.exe') + os.path.join(os.environ.get('LOCALAPPDATA', ''), 'Programs', 'Opera GX', 'opera.exe') ] else: possible_paths = [ @@ -439,19 +435,19 @@ a GX', 'opera.exe') for path in possible_paths: if os.path.exists(path): - logger.info(f"Found browser at: {path}") # Enhanced logging + logger.info(f"Found browser at: {path}") print(f"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.found_browser_at', path=path) if self.translator else f'Found browser at: {path}'}{Style.RESET_ALL}") return path if browser_type != 'chrome': - logger.warning(f"Could not find {browser_type}, trying Chrome") # Enhanced logging + logger.warning(f"Could not find {browser_type}, trying Chrome") print(f"{Fore.YELLOW}{EMOJI['WARNING']} {self.translator.get('oauth.browser_not_found_trying_chrome', browser=browser_type) if self.translator else f'Could not find {browser_type}, trying Chrome instead'}{Style.RESET_ALL}") return self._get_chrome_path() return None except Exception as e: - logger.error(f"Error finding browser path: {str(e)}", exc_info=True) # Enhanced logging + logger.error(f"Error finding browser path: {str(e)}", exc_info=True) print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.error_finding_browser_path', error=str(e)) if self.translator else f'Error finding browser path: {e}'}{Style.RESET_ALL}") return None @@ -477,31 +473,31 @@ a GX', 'opera.exe') co.set_argument('--disable-features=TranslateUI') co.set_argument('--disable-features=RendererCodeIntegrity') - logger.info("Browser options configured successfully") # Enhanced logging + logger.info("Browser options configured successfully") return co except Exception as e: - logger.error(f"Error configuring browser options: {str(e)}", exc_info=True) # Enhanced logging + logger.error(f"Error configuring browser options: {str(e)}", exc_info=True) print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.error_configuring_browser_options', error=str(e)) if self.translator else f'Error configuring browser options: {e}'}{Style.RESET_ALL}") raise def handle_google_auth(self): """Handle Google OAuth authentication""" try: - logger.info("Starting Google OAuth authentication") # Enhanced logging + logger.info("Starting Google OAuth authentication") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.google_start') if self.translator else 'Starting Google OAuth authentication...'}{Style.RESET_ALL}") if not self.setup_browser(): - logger.error("Browser failed to initialize") # Enhanced logging + logger.error("Browser failed to initialize") print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.browser_failed') if self.translator else 'Browser failed to initialize'}{Style.RESET_ALL}") return False, None try: - logger.info("Navigating to authentication page") # Enhanced logging + logger.info("Navigating to authentication page") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.navigating_to_authentication_page') if self.translator else 'Navigating to authentication page...'}{Style.RESET_ALL}") self.browser.get("https://authenticator.cursor.sh/sign-up") time.sleep(get_random_wait_time(self.config, 'page_load_wait')) - logger.info(f"Current URL after navigation: {self.browser.url}") # Enhanced logging + logger.info(f"Current URL after navigation: {self.browser.url}") selectors = [ "//a[contains(@href,'GoogleOAuth')]", @@ -511,31 +507,31 @@ a GX', 'opera.exe') auth_btn = None for selector in selectors: - logger.debug(f"Trying selector: {selector}") # Enhanced logging + logger.debug(f"Trying selector: {selector}") try: - auth_btn = self.browser.ele(f"xpath:{selector}", timeout=5) # Increased timeout + auth_btn = self.browser.ele(f"xpath:{selector}", timeout=5) if auth_btn and auth_btn.is_displayed(): - logger.info(f"Found Google auth button with selector: {selector}") # Enhanced logging + logger.info(f"Found Google auth button with selector: {selector}") break except Exception as e: - logger.warning(f"Selector {selector} failed: {str(e)}") # Enhanced logging + logger.warning(f"Selector {selector} failed: {str(e)}") continue if not auth_btn: - logger.error("Could not find Google authentication button") # Enhanced logging + logger.error("Could not find Google authentication button") raise Exception("Could not find Google authentication button") - logger.debug(f"Button state - displayed: {auth_btn.is_displayed()}, enabled: {auth_btn.is_enabled()}") # Enhanced logging + logger.debug(f"Button state - displayed: {auth_btn.is_displayed()}, enabled: {auth_btn.is_enabled()}") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.starting_google_authentication') if self.translator else 'Starting Google authentication...'}{Style.RESET_ALL}") try: auth_btn.click() except Exception as e: - logger.warning(f"Standard click failed: {str(e)}, attempting JavaScript click") # Enhanced logging + logger.warning(f"Standard click failed: {str(e)}, attempting JavaScript click") self.browser.run_js("arguments[0].click();", auth_btn) time.sleep(get_random_wait_time(self.config, 'page_load_wait')) if "accounts.google.com" in self.browser.url: - logger.info("On Google account selection page") # Enhanced logging + logger.info("On Google account selection page") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.please_select_your_google_account_to_continue') if self.translator else 'Please select your Google account to continue...'}{Style.RESET_ALL}") config = get_config(self.translator) @@ -548,34 +544,34 @@ a GX', 'opera.exe') alert('{alert_message}'); """) except: - logger.warning("Failed to display alert") # Enhanced logging + logger.warning("Failed to display alert") pass auth_info = self._wait_for_auth() if not auth_info: - logger.error("Authentication timeout") # Enhanced logging + logger.error("Authentication timeout") print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.timeout') if self.translator else 'Timeout'}{Style.RESET_ALL}") return False, None - logger.info("Google authentication successful") # Enhanced logging + logger.info("Google authentication successful") print(f"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.success') if self.translator else 'Success'}{Style.RESET_ALL}") return True, auth_info except Exception as e: - logger.error(f"Authentication error: {str(e)}", exc_info=True) # Enhanced logging + logger.error(f"Authentication error: {str(e)}", exc_info=True) print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.authentication_error', error=str(e)) if self.translator else f'Authentication error: {str(e)}'}{Style.RESET_ALL}") return False, None finally: try: if self.browser: self.browser.quit() - logger.info("Browser closed") # Enhanced logging + logger.info("Browser closed") except: - logger.warning("Failed to close browser") # Enhanced logging + logger.warning("Failed to close browser") pass except Exception as e: - logger.error(f"Google OAuth failed: {str(e)}", exc_info=True) # Enhanced logging + logger.error(f"Google OAuth failed: {str(e)}", exc_info=True) print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.failed', error=str(e))}{Style.RESET_ALL}") return False, None @@ -586,7 +582,7 @@ a GX', 'opera.exe') start_time = time.time() check_interval = 2 - logger.info("Waiting for authentication (timeout: 5 minutes)") # Enhanced logging + logger.info("Waiting for authentication (timeout: 5 minutes)") print(f"{Fore.CYAN}{EMOJI['WAIT']} {self.translator.get('oauth.waiting_for_authentication', timeout='5 minutes') if self.translator else 'Waiting for authentication (timeout: 5 minutes)'}{Style.RESET_ALL}") while time.time() - start_time < max_wait: @@ -598,7 +594,7 @@ a GX', 'opera.exe') value = cookie.get("value", "") token = get_token_from_cookie(value, self.translator) if token: - logger.info("Authentication successful, getting account info") # Enhanced logging + logger.info("Authentication successful, getting account info") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.authentication_successful_getting_account_info') if self.translator else 'Authentication successful, getting account info...'}{Style.RESET_ALL}") self.browser.get("https://www.cursor.com/settings") time.sleep(3) @@ -608,17 +604,17 @@ a GX', 'opera.exe') email_element = self.browser.ele("css:div[class='flex w-full flex-col gap-2'] div:nth-child(2) p:nth-child(2)") if email_element: email = email_element.text - logger.info(f"Found email: {email}") # Enhanced logging + logger.info(f"Found email: {email}") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.found_email', email=email) if self.translator else f'Found email: {email}'}{Style.RESET_ALL}") except: - logger.warning("Could not find email, using fallback") # Enhanced logging + logger.warning("Could not find email, using fallback") email = "user@cursor.sh" try: usage_element = self.browser.ele("css:div[class='flex flex-col gap-4 lg:flex-row'] div:nth-child(1) div:nth-child(1) span:nth-child(2)") if usage_element: usage_text = usage_element.text - logger.info(f"Usage count: {usage_text}") # Enhanced logging + logger.info(f"Usage count: {usage_text}") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.usage_count', usage=usage_text) if self.translator else f'Usage count: {usage_text}'}{Style.RESET_ALL}") def check_usage_limits(usage_str): @@ -633,117 +629,115 @@ a GX', 'opera.exe') return False if check_usage_limits(usage_text): - logger.info("Account has reached maximum usage, deleting") # Enhanced logging + logger.info("Account has reached maximum usage, deleting") print(f"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.account_has_reached_maximum_usage', deleting='deleting') if self.translator else 'Account has reached maximum usage, deleting...'}{Style.RESET_ALL}") if self._delete_current_account(): - logger.info("Starting new authentication process") # Enhanced logging + logger.info("Starting new authentication process") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.starting_new_authentication_process') if self.translator else 'Starting new authentication process...'}{Style.RESET_ALL}") if self.auth_type == "google": return self.handle_google_auth() else: return self.handle_github_auth() else: - logger.error("Failed to delete expired account") # Enhanced logging + logger.error("Failed to delete expired account") print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.failed_to_delete_expired_account') if self.translator else 'Failed to delete expired account'}{Style.RESET_ALL}") else: - logger.info(f"Account is still valid (Usage: {usage_text})") # Enhanced logging + logger.info(f"Account is still valid (Usage: {usage_text})") print(f"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.account_is_still_valid', usage=usage_text) if self.translator else f'Account is still valid (Usage: {usage_text})'}{Style.RESET_ALL}") except Exception as e: - logger.warning(f"Could not check usage count: {str(e)}") # Enhanced logging + logger.warning(f"Could not check usage count: {str(e)}") print(f"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.could_not_check_usage_count', error=str(e)) if self.translator else f'Could not check usage count: {str(e)}'}{Style.RESET_ALL}") return {"email": email, "token": token} if "cursor.com/settings" in self.browser.url: - logger.info("Detected successful login via URL") # Enhanced logging + logger.info("Detected successful login via URL") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.detected_successful_login') if self.translator else 'Detected successful login'}{Style.RESET_ALL}") except Exception as e: - logger.warning(f"Error during auth wait: {str(e)}") # Enhanced logging + logger.warning(f"Error during auth wait: {str(e)}") print(f"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.waiting_for_authentication', error=str(e)) if self.translator else f'Waiting for authentication... ({str(e)})'}{Style.RESET_ALL}") time.sleep(check_interval) - logger.error("Authentication timeout") # Enhanced logging + logger.error("Authentication timeout") print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.authentication_timeout') if self.translator else 'Authentication timeout'}{Style.RESET_ALL}") return None except Exception as e: - logger.error(f"Error waiting for authentication: {str(e)}", exc_info=True) # Enhanced logging + logger.error(f"Error waiting for authentication: {str(e)}", exc_info=True) print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.error_waiting_for_authentication', error=str(e)) if self.translator else f'Error while waiting for authentication: {str(e)}'}{Style.RESET_ALL}") return None def handle_github_auth(self): """Handle GitHub OAuth authentication""" try: - logger.info("Starting GitHub OAuth authentication") # Enhanced logging + logger.info("Starting GitHub OAuth authentication") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.github_start')}{Style.RESET_ALL}") if not self.setup_browser(): - logger.error("Browser failed to initialize") # Enhanced logging + logger.error("Browser failed to initialize") print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.browser_failed') if self.translator else 'Browser failed to initialize'}{Style.RESET_ALL}") return False, None - # Retry navigation up to 3 times max_retries = 3 for attempt in range(max_retries): try: - logger.info(f"Attempt {attempt + 1}/{max_retries}: Navigating to authentication page") # Enhanced logging + logger.info(f"Attempt {attempt + 1}/{max_retries}: Navigating to authentication page") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.navigating_to_authentication_page') if self.translator else 'Navigating to authentication page...'}{Style.RESET_ALL}") self.browser.get("https://authenticator.cursor.sh/sign-up") time.sleep(get_random_wait_time(self.config, 'page_load_wait')) - logger.info(f"Current URL after navigation: {self.browser.url}") # Enhanced logging + logger.info(f"Current URL after navigation: {self.browser.url}") - # Updated selectors for GitHub button selectors = [ - "//a[contains(@href,'GitHubOAuth')]", # Primary selector - "//a[contains(@class,'auth-method-button') and contains(@href,'GitHubOAuth')]", # Class-based - "(//a[contains(@class,'auth-method-button')])[2]", # Second button fallback - "//a[contains(text(),'GitHub')]", # Text-based fallback - "//a[@href='/auth/github']" # Additional fallback + "//a[contains(@href,'GitHubOAuth')]", + "//a[contains(@class,'auth-method-button') and contains(@href,'GitHubOAuth')]", + "(//a[contains(@class,'auth-method-button')])[2]", + "//a[contains(text(),'GitHub')]", + "//a[@href='/auth/github']" ] auth_btn = None for selector in selectors: - logger.debug(f"Trying selector: {selector}") # Enhanced logging + logger.debug(f"Trying selector: {selector}") try: - auth_btn = self.browser.ele(f"xpath:{selector}", timeout=5) # Increased timeout + auth_btn = self.browser.ele(f"xpath:{selector}", timeout=5) if auth_btn and auth_btn.is_displayed(): - logger.info(f"Found GitHub auth button with selector: {selector}") # Enhanced logging + logger.info(f"Found GitHub auth button with selector: {selector}") break except Exception as e: - logger.warning(f"Selector {selector} failed: {str(e)}") # Enhanced logging + logger.warning(f"Selector {selector} failed: {str(e)}") continue if not auth_btn: - logger.error("Could not find GitHub authentication button") # Enhanced logging + logger.error("Could not find GitHub authentication button") raise Exception("Could not find GitHub authentication button") - logger.debug(f"Button state - displayed: {auth_btn.is_displayed()}, enabled: {auth_btn.is_enabled()}") # Enhanced logging + logger.debug(f"Button state - displayed: {auth_btn.is_displayed()}, enabled: {auth_btn.is_enabled()}") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.starting_github_authentication') if self.translator else 'Starting GitHub authentication...'}{Style.RESET_ALL}") try: auth_btn.click() except Exception as e: - logger.warning(f"Standard click failed: {str(e)}, attempting JavaScript click") # Enhanced logging + logger.warning(f"Standard click failed: {str(e)}, attempting JavaScript click") self.browser.run_js("arguments[0].click();", auth_btn) time.sleep(get_random_wait_time(self.config, 'page_load_wait')) - logger.info(f"Current URL after clicking GitHub button: {self.browser.url}") # Enhanced logging + logger.info(f"Current URL after clicking GitHub button: {self.browser.url}") auth_info = self._wait_for_auth() if not auth_info: - logger.error("Authentication timeout") # Enhanced logging + logger.error("Authentication timeout") print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.timeout') if self.translator else 'Timeout'}{Style.RESET_ALL}") return False, None - logger.info("GitHub authentication successful") # Enhanced logging + logger.info("GitHub authentication successful") print(f"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.success')}{Style.RESET_ALL}") return True, auth_info except Exception as e: - logger.error(f"Attempt {attempt + 1} failed: {str(e)}", exc_info=True) # Enhanced logging + logger.error(f"Attempt {attempt + 1} failed: {str(e)}", exc_info=True) print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.authentication_error', error=str(e)) if self.translator else f'Authentication error: {str(e)}'}{Style.RESET_ALL}") if attempt < max_retries - 1: - logger.info("Retrying navigation") # Enhanced logging + logger.info("Retrying navigation") time.sleep(2) continue return False, None @@ -751,13 +745,13 @@ a GX', 'opera.exe') try: if self.browser and attempt == max_retries - 1: self.browser.quit() - logger.info("Browser closed") # Enhanced logging + logger.info("Browser closed") except: - logger.warning("Failed to close browser") # Enhanced logging + logger.warning("Failed to close browser") pass except Exception as e: - logger.error(f"GitHub OAuth failed: {str(e)}", exc_info=True) # Enhanced logging + logger.error(f"GitHub OAuth failed: {str(e)}", exc_info=True) print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.failed', error=str(e))}{Style.RESET_ALL}") return False, None @@ -769,7 +763,7 @@ a GX', 'opera.exe') self.browser.get("https://authenticator.cursor.sh/sign-up") time.sleep(get_random_wait_time(self.config, 'page_load_wait')) - logger.info(f"Current URL in _handle_oauth: {self.browser.url}") # Enhanced logging + logger.info(f"Current URL in _handle_oauth: {self.browser.url}") if auth_type == "google": selectors = [ @@ -787,11 +781,11 @@ a GX', 'opera.exe') while time.time() - button_start_time < max_button_wait: for selector in selectors: - logger.debug(f"Trying selector in _handle_oauth: {selector}") # Enhanced logging + logger.debug(f"Trying selector in _handle_oauth: {selector}") try: auth_btn = self.browser.ele(f"xpath:{selector}", timeout=1) if auth_btn and auth_btn.is_displayed(): - logger.info(f"Found auth button in _handle_oauth: {selector}") # Enhanced logging + logger.info(f"Found auth button in _handle_oauth: {selector}") break except: continue @@ -800,7 +794,7 @@ a GX', 'opera.exe') time.sleep(1) if auth_btn: - logger.debug(f"Button state in _handle_oauth - displayed: {auth_btn.is_displayed()}, enabled: {auth_btn.is_enabled()}") # Enhanced logging + logger.debug(f"Button state in _handle_oauth - displayed: {auth_btn.is_displayed()}, enabled: {auth_btn.is_enabled()}") auth_btn.click() time.sleep(get_random_wait_time(self.config, 'page_load_wait')) @@ -811,7 +805,7 @@ a GX', 'opera.exe') alert('{alert_message}'); """) except Exception as e: - logger.warning(f"Alert display failed: {str(e)}") # Enhanced logging + logger.warning(f"Alert display failed: {str(e)}") print(f"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.alert_display_failed', error=str(e)) if self.translator else f'Alert display failed: {str(e)}'}{Style.RESET_ALL}") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.please_select_your_google_account_manually_to_continue_with_cursor_authentication') if self.translator else 'Please select your Google account manually to continue with Cursor authentication...'}{Style.RESET_ALL}") @@ -832,7 +826,7 @@ a GX', 'opera.exe') value = cookie.get("value", "") token = get_token_from_cookie(value, self.translator) if token: - logger.info("Authentication successful in _handle_oauth") # Enhanced logging + logger.info("Authentication successful in _handle_oauth") print(f"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.authentication_successful') if self.translator else 'Authentication successful!'}{Style.RESET_ALL}") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.navigating_to_settings_page') if self.translator else 'Navigating to settings page...'}{Style.RESET_ALL}") self.browser.get("https://www.cursor.com/settings") @@ -842,10 +836,10 @@ a GX', 'opera.exe') email_element = self.browser.ele("css:div[class='flex w-full flex-col gap-2'] div:nth-child(2) p:nth-child(2)") if email_element: actual_email = email_element.text - logger.info(f"Found email: {actual_email}") # Enhanced logging + logger.info(f"Found email: {actual_email}") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.found_email', email=actual_email) if self.translator else f'Found email: {actual_email}'}{Style.RESET_ALL}") except Exception as e: - logger.warning(f"Could not find email: {str(e)}") # Enhanced logging + logger.warning(f"Could not find email: {str(e)}") print(f"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.could_not_find_email', error=str(e)) if self.translator else f'Could not find email: {str(e)}'}{Style.RESET_ALL}") actual_email = "user@cursor.sh" @@ -853,7 +847,7 @@ a GX', 'opera.exe') usage_element = self.browser.ele("css:div[class='flex flex-col gap-4 lg:flex-row'] div:nth-child(1) div:nth-child(1) span:nth-child(2)") if usage_element: usage_text = usage_element.text - logger.info(f"Usage count: {usage_text}") # Enhanced logging + logger.info(f"Usage count: {usage_text}") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.usage_count', usage=usage_text) if self.translator else f'Usage count: {usage_text}'}{Style.RESET_ALL}") def check_usage_limits(usage_str): @@ -868,30 +862,30 @@ a GX', 'opera.exe') return False if check_usage_limits(usage_text): - logger.info("Account has reached maximum usage, deleting") # Enhanced logging + logger.info("Account has reached maximum usage, deleting") print(f"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.account_has_reached_maximum_usage', deleting='deleting') if self.translator else 'Account has reached maximum usage, deleting...'}{Style.RESET_ALL}") if self._delete_current_account(): - logger.info("Starting new authentication process") # Enhanced logging + logger.info("Starting new authentication process") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.starting_new_authentication_process') if self.translator else 'Starting new authentication process...'}{Style.RESET_ALL}") if self.auth_type == "google": return self.handle_google_auth() else: return self.handle_github_auth() else: - logger.error("Failed to delete expired account") # Enhanced logging + logger.error("Failed to delete expired account") print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.failed_to_delete_expired_account') if self.translator else 'Failed to delete expired account'}{Style.RESET_ALL}") else: - logger.info(f"Account is still valid (Usage: {usage_text})") # Enhanced logging + logger.info(f"Account is still valid (Usage: {usage_text})") print(f"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.account_is_still_valid', usage=usage_text) if self.translator else f'Account is still valid (Usage: {usage_text})'}{Style.RESET_ALL}") except Exception as e: - logger.warning(f"Could not check usage count: {str(e)}") # Enhanced logging + logger.warning(f"Could not check usage count: {str(e)}") print(f"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.could_not_check_usage_count', error=str(e)) if self.translator else f'Could not check usage count: {str(e)}'}{Style.RESET_ALL}") return True, {"email": actual_email, "token": token} current_url = self.browser.url if "cursor.com/settings" in current_url: - logger.info("Already on settings page") # Enhanced logging + logger.info("Already on settings page") print(f"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.already_on_settings_page') if self.translator else 'Already on settings page!'}{Style.RESET_ALL}") time.sleep(1) cookies = self.browser.cookies() @@ -904,10 +898,10 @@ a GX', 'opera.exe') email_element = self.browser.ele("css:div[class='flex w-full flex-col gap-2'] div:nth-child(2) p:nth-child(2)") if email_element: actual_email = email_element.text - logger.info(f"Found email: {actual_email}") # Enhanced logging + logger.info(f"Found email: {actual_email}") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.found_email', email=actual_email) if self.translator else f'Found email: {actual_email}'}{Style.RESET_ALL}") except Exception as e: - logger.warning(f"Could not find email: {str(e)}") # Enhanced logging + logger.warning(f"Could not find email: {str(e)}") print(f"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.could_not_find_email', error=str(e)) if self.translator else f'Could not find email: {str(e)}'}{Style.RESET_ALL}") actual_email = "user@cursor.sh" @@ -915,7 +909,7 @@ a GX', 'opera.exe') usage_element = self.browser.ele("css:div[class='flex flex-col gap-4 lg:flex-row'] div:nth-child(1) div:nth-child(1) span:nth-child(2)") if usage_element: usage_text = usage_element.text - logger.info(f"Usage count: {usage_text}") # Enhanced logging + logger.info(f"Usage count: {usage_text}") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.usage_count', usage=usage_text) if self.translator else f'Usage count: {usage_text}'}{Style.RESET_ALL}") def check_usage_limits(usage_str): @@ -930,54 +924,54 @@ a GX', 'opera.exe') return False if check_usage_limits(usage_text): - logger.info("Account has reached maximum usage, deleting") # Enhanced logging + logger.info("Account has reached maximum usage, deleting") print(f"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.account_has_reached_maximum_usage', deleting='deleting') if self.translator else 'Account has reached maximum usage, deleting...'}{Style.RESET_ALL}") if self._delete_current_account(): - logger.info("Starting new authentication process") # Enhanced logging + logger.info("Starting new authentication process") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.starting_new_authentication_process') if self.translator else 'Starting new authentication process...'}{Style.RESET_ALL}") if self.auth_type == "google": return self.handle_google_auth() else: return self.handle_github_auth() else: - logger.error("Failed to delete expired account") # Enhanced logging + logger.error("Failed to delete expired account") print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.failed_to_delete_expired_account') if self.translator else 'Failed to delete expired account'}{Style.RESET_ALL}") else: - logger.info(f"Account is still valid (Usage: {usage_text})") # Enhanced logging + logger.info(f"Account is still valid (Usage: {usage_text})") print(f"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.account_is_still_valid', usage=usage_text) if self.translator else f'Account is still valid (Usage: {usage_text})'}{Style.RESET_ALL}") except Exception as e: - logger.warning(f"Could not check usage count: {str(e)}") # Enhanced logging + logger.warning(f"Could not check usage count: {str(e)}") print(f"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.could_not_check_usage_count', error=str(e)) if self.translator else f'Could not check usage count: {str(e)}'}{Style.RESET_ALL}") return True, {"email": actual_email, "token": token} elif current_url != last_url: - logger.info(f"Page changed to {current_url}") # Enhanced logging + logger.info(f"Page changed to {current_url}") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.page_changed_checking_auth') if self.translator else 'Page changed, checking auth...'}{Style.RESET_ALL}") last_url = current_url time.sleep(get_random_wait_time(self.config, 'page_load_wait')) except Exception as e: - logger.warning(f"Status check error: {str(e)}") # Enhanced logging + logger.warning(f"Status check error: {str(e)}") print(f"{Fore.YELLOW}{EMOJI['INFO']} {self.translator.get('oauth.status_check_error', error=str(e)) if self.translator else f'Status check error: {str(e)}'}{Style.RESET_ALL}") time.sleep(1) continue time.sleep(1) - logger.error("Authentication timeout") # Enhanced logging + logger.error("Authentication timeout") print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.authentication_timeout') if self.translator else 'Authentication timeout'}{Style.RESET_ALL}") return False, None - logger.error("Authentication button not found") # Enhanced logging + logger.error("Authentication button not found") print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.authentication_button_not_found') if self.translator else 'Authentication button not found'}{Style.RESET_ALL}") return False, None except Exception as e: - logger.error(f"Authentication failed: {str(e)}", exc_info=True) # Enhanced logging + logger.error(f"Authentication failed: {str(e)}", exc_info=True) print(f"{Fore.RED}{EMOJI['ERROR']} {self.translator.get('oauth.authentication_failed', error=str(e)) if self.translator else f'Authentication failed: {str(e)}'}{Style.RESET_ALL}") return False, None finally: if self.browser: self.browser.quit() - logger.info("Browser closed in _handle_oauth") # Enhanced logging + logger.info("Browser closed in _handle_oauth") def _extract_auth_info(self): """Extract authentication information after successful OAuth""" @@ -994,7 +988,7 @@ a GX', 'opera.exe') raise time.sleep(1) - logger.info(f"Found {len(cookies)} cookies") # Enhanced logging + logger.info(f"Found {len(cookies)} cookies") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.found_cookies', count=len(cookies)) if self.translator else f'Found {len(cookies)} cookies'}{Style.RESET_ALL}") email = None @@ -1007,14 +1001,14 @@ a GX', 'opera.exe') value = cookie.get("value", "") token = get_token_from_cookie(value, self.translator) except Exception as e: - logger.error(f"Failed to extract token: {str(e)}") # Enhanced logging + logger.error(f"Failed to extract token: {str(e)}") error_message = f'Failed to extract auth info: {str(e)}' if not self.translator else self.translator.get('oauth.failed_to_extract_auth_info', error=str(e)) print(f"{Fore.RED}{EMOJI['ERROR']} {error_message}{Style.RESET_ALL}") elif name == "cursor_email": email = cookie.get("value") if email and token: - logger.info(f"Authentication successful - Email: {email}") # Enhanced logging + logger.info(f"Authentication successful - Email: {email}") print(f"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.authentication_successful', email=email) if self.translator else f'Authentication successful - Email: {email}'}{Style.RESET_ALL}") return True, {"email": email, "token": token} else: @@ -1023,13 +1017,13 @@ a GX', 'opera.exe') missing.append("email") if not token: missing.append("token") - logger.error(f"Missing authentication data: {', '.join(missing)}") # Enhanced logging + logger.error(f"Missing authentication data: {', '.join(missing)}") error_message = f"Missing authentication data: {', '.join(missing)}" if not self.translator else self.translator.get('oauth.missing_authentication_data', data=', '.join(missing)) print(f"{Fore.RED}{EMOJI['ERROR']} {error_message}{Style.RESET_ALL}") return False, None except Exception as e: - logger.error(f"Failed to extract auth info: {str(e)}", exc_info=True) # Enhanced logging + logger.error(f"Failed to extract auth info: {str(e)}", exc_info=True) error_message = f'Failed to extract auth info: {str(e)}' if not self.translator else self.translator.get('oauth.failed_to_extract_auth_info', error=str(e)) print(f"{Fore.RED}{EMOJI['ERROR']} {error_message}{Style.RESET_ALL}") return False, None @@ -1062,54 +1056,21 @@ a GX', 'opera.exe') return deleteAccount(); """ + logger.info("Attempting to delete account via API") result = self.browser.run_js(delete_js) - logger.info(f"Delete account result: {result}") # Enhanced logging - print(f"{Fore.GREEN}{EMOJI['SUCCESS']} Delete account result: {result}{Style.RESET_ALL}") + logger.info(f"Delete account result: {result}") + print(f"{Fore.GREEN}{EMOJI['SUCCESS']} {self.translator.get('oauth.delete_account_success', result=result) if self.translator else f'Delete account result: {result}'}{Style.RESET_ALL}") + logger.info("Redirecting to authenticator.cursor.sh") print(f"{Fore.CYAN}{EMOJI['INFO']} {self.translator.get('oauth.redirecting_to_authenticator_cursor_sh') if self.translator else 'Redirecting to authenticator.cursor.sh...'}{Style.RESET_ALL}") self.browser.get("https://authenticator.cursor.sh/sign-up") time.sleep(get_random_wait_time(self.config, 'page_load_wait')) + logger.info(f"Navigated to sign-up page: {self.browser.url}") return True except Exception as e: - logger.error(f"Failed to delete account: {str(e)}", exc_info=True) # Enhanced logging - error_message = f'Failed to delete account: {str(e)}' if not self.translator else self.translator.get('oauth.failed_to_delete_account', error=str(e)) + logger.error(f"Failed to delete account: {str(e)}", exc_info=True) + error_message = self.translator.get('oauth.failed_to_delete_account', error=str(e)) if self.translator else f'Failed to delete account: {str(e)}' print(f"{Fore.RED}{EMOJI['ERROR']} {error_message}{Style.RESET_ALL}") - return False - -def main(auth_type, translator=None): - """Main function to handle OAuth authentication""" - logger.info(f"Starting OAuth main with auth_type: {auth_type}") # Enhanced logging - handler = OAuthHandler(translator, auth_type) - - if auth_type.lower() == 'google': - print(f"{Fore.CYAN}{EMOJI['INFO']} {translator.get('oauth.google_start') if translator else 'Google start'}{Style.RESET_ALL}") - success, auth_info = handler.handle_google_auth() - elif auth_type.lower() == 'github': - print(f"{Fore.CYAN}{EMOJI['INFO']} {translator.get('oauth.github_start') if translator else 'Github start'}{Style.RESET_ALL}") - success, auth_info = handler.handle_github_auth() - else: - logger.error("Invalid authentication type") # Enhanced logging - print(f"{Fore.RED}{EMOJI['ERROR']} {translator.get('oauth.invalid_authentication_type') if translator else 'Invalid authentication type'}{Style.RESET_ALL}") - return False - - if success and auth_info: - auth_manager = CursorAuth(translator) - if auth_manager.update_auth( - email=auth_info["email"], - access_token=auth_info["token"], - refresh_token=auth_info["token"] - ): - logger.info("Auth update success") # Enhanced logging - print(f"{Fore.GREEN}{EMOJI['SUCCESS']} {translator.get('oauth.auth_update_success') if translator else 'Auth update success'}{Style.RESET_ALL}") - if handler.browser: - handler.browser.quit() - logger.info("Browser closed") # Enhanced logging - print(f"{Fore.CYAN}{EMOJI['INFO']} {translator.get('oauth.browser_closed') if translator else 'Browser closed'}{Style.RESET_ALL}") - return True - else: - logger.error("Auth update failed") # Enhanced logging - print(f"{Fore.RED}{EMOJI['ERROR']} {translator.get('oauth.auth_update_failed') if translator else 'Auth update failed'}{Style.RESET_ALL}") - - return False \ No newline at end of file + return False \ No newline at end of file