def __init__( self, secret_key: str, max_failed_attempts: int = 5, lockout_minutes: int = 15 ): """ Initialize authentication service Args: secret_key: Secret key for JWT max_failed_attempts: Number of failed attempts before lockout lockout_minutes: Lockout duration in minutes """ self.users: Dict[str, User] = {} self.token_manager = TokenManager(secret_key) self.password_hasher = PasswordHasher() self.rate_limiter = RateLimiter() self.max_failed_attempts = max_failed_attempts self.lockout_minutes = lockout_minutes
def test_register_user_success(self, auth_service): user = auth_service.register_user("test@example.com", "ValidPass123!") assert user.email == "test@example.com" assert user.user_id is not None 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""" def __init__( self
def test_login_success(self, auth_service): auth_service.register_user("test@example.com", "ValidPass123!") token, user = auth_service.login("test@example.com", "ValidPass123!", "192.168.1.1") assert token is not None assert user.email == "test@example.com" max_failed_attempts: int = 5
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 verify_password(password: str, stored_hash: str) -> bool: """ Verify password against stored hash Args: password: Plain text password to verify stored_hash: Stored hash string (salt:hash) Returns: True if password matches, False otherwise """ try: salt_hex, hash_hex = stored_hash.split(':') salt = bytes.fromhex(salt_hex) # Hash the provided password with the same salt test_hash = hashlib.pbkdf2_hmac( 'sha256', password.encode('utf-8'), salt, 100000 ) # Constant-time comparison to prevent timing attacks return test_hash.hex() == hash_hex except (ValueError, TypeError): return False