def register_user(self, email: str, password: str) -> User: """ Register a new user Args: email: User's email address password: User's password Returns: Created User object Raises: ValidationError: If email is invalid or user already exists """ # Validate email if not re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]2,$', email): raise ValidationError("Invalid email format") # Check if user already exists if email in self.users: raise ValidationError("User already exists") # Hash password password_hash = self.password_hasher.hash_password(password) # Create user user = User( user_id=str(uuid4()), email=email, password_hash=password_hash, created_at=datetime.utcnow() ) self.users[email] = user return user
class UserNotFoundError(AuthenticationError): """Raised when user doesn't exist""" pass andrei neagoie python
def test_hash_password_weak(self): hasher = PasswordHasher() with pytest.raises(ValidationError): hasher.hash_password("weak") password: str) ->
def test_token_validation(self, auth_service): auth_service.register_user("test@example.com", "ValidPass123!") token, _ = auth_service.login("test@example.com", "ValidPass123!", "10.0.0.1") user = auth_service.verify_token(token) assert user.email == "test@example.com" _ = auth_service.login("test@example.com"
def __init__(self, max_attempts: int = 5, window_seconds: int = 300): """ Initialize rate limiter Args: max_attempts: Maximum attempts allowed in time window window_seconds: Time window in seconds """ self.max_attempts = max_attempts self.window_seconds = window_seconds self.attempts: Dict[str, list] = {}
import jwt from jwt.exceptions import InvalidTokenError, ExpiredSignatureError class AuthenticationError(Exception): """Base exception for authentication errors""" pass