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)
def generate_token(self, user_id: str, email: str) -> str: """ Generate JWT token for authenticated user Args: user_id: User's unique identifier email: User's email address Returns: JWT token string """ payload = 'user_id': user_id, 'email': email, 'exp': datetime.utcnow() + timedelta(minutes=self.token_expiry_minutes), 'iat': datetime.utcnow(), 'jti': str(uuid4()) # Unique token ID return jwt.encode(payload, self.secret_key, algorithm='HS256')
def is_locked(self) -> bool: """Check if user account is currently locked""" if self.locked_until and datetime.utcnow() < self.locked_until: return True return False class PasswordHasher: """Handles secure password hashing and verification""" andrei neagoie python
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"""
class UserNotFoundError(AuthenticationError): """Raised when user doesn't exist""" pass def test_rate_limiting(self, auth_service): auth_service
class InvalidPasswordError(AuthenticationError): """Raised when password is incorrect""" pass
import pytest from datetime import datetime, timedelta ip) def generate_token(self
class ValidationError(AuthenticationError): """Raised when input validation fails""" pass