1. import time
  2. import functools
  3. def token_timeout(timeout):
  4. """
  5. Decorator to add a timeout to authentication token validation.
  6. """
  7. def decorator(func):
  8. @functools.wraps(func)
  9. def wrapper(*args, **kwargs):
  10. start_time = time.time()
  11. try:
  12. result = func(*args, **kwargs)
  13. except Exception as e:
  14. if time.time() - start_time > timeout:
  15. raise TimeoutError(f"Authentication token expired after {timeout} seconds.") from e
  16. else:
  17. raise # Re-raise other exceptions
  18. return result
  19. return wrapper
  20. return decorator
  21. if __name__ == '__main__':
  22. @token_timeout(5) # Timeout after 5 seconds
  23. def authenticate(token):
  24. """Simulates authentication with a token."""
  25. time.sleep(2) # Simulate some processing time
  26. if token == "valid_token":
  27. return "Authentication successful!"
  28. else:
  29. raise ValueError("Invalid token")
  30. try:
  31. print(authenticate("valid_token"))
  32. except TimeoutError as e:
  33. print(e)
  34. except ValueError as e:
  35. print(e)
  36. try:
  37. print(authenticate("invalid_token"))
  38. except TimeoutError as e:
  39. print(e)
  40. except ValueError as e:
  41. print(e)

Add your comment