"""Auth0 user search functionality.""" import argparse from typing import List, Dict, Any # from auth0.authentication import GetToken from auth0.management import Auth0 import config class Auth0UserSearcher: """Search Auth0 for users.""" def __init__(self, domain: str, token: str): """Initialize the searcher. Args: domain: Auth0 domain (e.g., 'myaccount.auth0.com') token: Auth0 management API token """ self.domain = domain # Initialize Auth0 management client self.auth0 = Auth0(domain, token) def search_users(self, email: str) -> List[Dict[str, Any]]: """Search for users in Auth0 by email. Args: email: Email address to search for Returns: List of user objects matching the email """ try: # Use the search_users_by_email method users = self.auth0.users_by_email.search_users_by_email( email=email, fields=None, include_fields=True ) return users if users else [] except Exception as e: print(f"Error searching Auth0 users: {e}") return [] def delete_user(self, user_id: str) -> bool: """Delete a user from Auth0. Args: user_id: The Auth0 user ID to delete Returns: True if deletion was successful, False otherwise """ try: self.auth0.users.delete(user_id) return True except Exception as e: print(f"Error deleting user {user_id}: {e}") return False def search_all_domains(email: str) -> Dict[str, List[Dict[str, Any]]]: """Search for users across all Auth0 domains. Args: email: Email address to search for Returns: Dictionary mapping domain names to lists of users found """ users_by_domain = {} if email: print(f"\nSearching for '{email}' in Auth0...") for domain, token in config.AUTH0_DOMAINS.items(): try: full_domain = f"{domain}.auth0.com" print(f" Searching {domain}...") auth0_searcher = Auth0UserSearcher(full_domain, token) users = auth0_searcher.search_users(email) if users: users_by_domain[domain] = users except Exception as e: print(f" Warning: {domain} search failed: {e}") else: print("\nNote: Auth0 search skipped. Provide --email_search_term to search Auth0 users") return users_by_domain def delete_and_log_users(users_by_domain: Dict[str, List[Dict[str, Any]]]) -> None: """Delete Auth0 users and log details. Args: users_by_domain: Dictionary mapping domain names to lists of users """ if users_by_domain: total_auth0_users = sum(len(users) for users in users_by_domain.values()) print(f"\n{'='*80}") print(f"AUTH0 USERS ({total_auth0_users} found across {len(users_by_domain)} domains)") print(f"{'='*80}\n") for domain, users in users_by_domain.items(): print(f"\n{domain} ({len(users)} users):") print("-" * 40) # Get token for this domain token = config.AUTH0_DOMAINS[domain] full_domain = f"{domain}.auth0.com" auth0_searcher = Auth0UserSearcher(full_domain, token) for user in users: user_id = user.get('user_id', 'N/A') email = user.get('email', 'N/A') name = user.get('name', 'N/A') created_at = user.get('created_at', 'N/A') print(f" Deleting user:") print(f" User ID: {user_id}") print(f" Email: {email}") print(f" Name: {name}") print(f" Created: {created_at}") # Delete the user if user_id != 'N/A': success = auth0_searcher.delete_user(user_id) if success: print(f" Status: ✓ DELETED (ID: {user_id})") else: print(f" Status: ✗ FAILED TO DELETE") else: print(f" Status: ✗ SKIPPED (no user ID)") print() def main(): """Run the Auth0 user search.""" parser = argparse.ArgumentParser( description="Search Auth0 domains for users by email" ) parser.add_argument( "--email", help="Email address to search for" ) args = parser.parse_args() # Search all domains users_by_domain = search_all_domains(args.email) # Delete users and log details delete_and_log_users(users_by_domain) return 0 if __name__ == "__main__": exit(main())