Andrei Neagoie Python Upd ❲2024❳

def check_rate_limit(self, key: str) -> bool: """ Check if rate limit is exceeded for given key Args: key: Identifier for rate limiting (e.g., email or IP) Returns: True if under limit, False if exceeded Raises: RateLimitExceededError: If rate limit is exceeded """ now = time.time() # Clean up old attempts if key in self.attempts: self.attempts[key] = [ attempt_time for attempt_time in self.attempts[key] if now - attempt_time < self.window_seconds ] # Check if limit exceeded if len(self.attempts.get(key, [])) >= self.max_attempts: wait_time = self.window_seconds - (now - self.attempts[key][0]) raise RateLimitExceededError( f"Too many attempts. Please try again in int(wait_time) seconds" ) return True

def validate_token(self, token: str) -> Dict: """ Validate and decode JWT token Args: token: JWT token string Returns: Decoded token payload Raises: AuthenticationError: If token is invalid or expired """ try: payload = jwt.decode( token, self.secret_key, algorithms=['HS256'] ) return payload except ExpiredSignatureError: raise AuthenticationError("Token has expired") except InvalidTokenError as e: raise AuthenticationError(f"Invalid token: str(e)") class RateLimiter: """Simple in-memory rate limiter for authentication attempts"""

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] = {} andrei neagoie python

class InvalidPasswordError(AuthenticationError): """Raised when password is incorrect""" pass

# Register user try: user = auth_service.register_user("user@example.com", "MySecurePass123!") print(f"✅ User registered: user.email") except ValidationError as e: print(f"❌ Registration failed: e") def check_rate_limit(self, key: str) -&gt; bool: """ Check

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"

@staticmethod def _validate_password_strength(password: str) -> None: """ Validate password meets security requirements Requirements: - Minimum 8 characters - At least 1 uppercase letter - At least 1 lowercase letter - At least 1 digit - At least 1 special character Raises: ValidationError: If password doesn't meet requirements """ if len(password) < 8: raise ValidationError("Password must be at least 8 characters long") if not re.search(r'[A-Z]', password): raise ValidationError("Password must contain at least one uppercase letter") if not re.search(r'[a-z]', password): raise ValidationError("Password must contain at least one lowercase letter") if not re.search(r'\d', password): raise ValidationError("Password must contain at least one digit") if not re.search(r'[!@#$%^&*(),.?":{}|<>]', password): raise ValidationError("Password must contain at least one special character") class TokenManager: """Handles JWT token creation and validation""" key: str) -&gt

def test_rate_limiting(self, auth_service): auth_service.register_user("test@example.com", "ValidPass123!") ip = "192.168.1.100" # Try wrong password 5 times for _ in range(5): with pytest.raises(InvalidPasswordError): auth_service.login("test@example.com", "wrong", ip) # 6th attempt should trigger rate limit with pytest.raises(RateLimitExceededError): auth_service.login("test@example.com", "wrong", ip)

Vous avez un projet en tête?

Contactez-nous
arrow black
800, Square Victoria Suite 2624
Montréal (QC)
H3C 0B4 Canada
Av. de la Catedral, 6 
Ciutat Vella, 08002 Barcelona
Espagne
linkcrossmenu