import time
import functools
def token_timeout(timeout):
"""
Decorator to add a timeout to authentication token validation.
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
try:
result = func(*args, **kwargs)
except Exception as e:
if time.time() - start_time > timeout:
raise TimeoutError(f"Authentication token expired after {timeout} seconds.") from e
else:
raise # Re-raise other exceptions
return result
return wrapper
return decorator
if __name__ == '__main__':
@token_timeout(5) # Timeout after 5 seconds
def authenticate(token):
"""Simulates authentication with a token."""
time.sleep(2) # Simulate some processing time
if token == "valid_token":
return "Authentication successful!"
else:
raise ValueError("Invalid token")
try:
print(authenticate("valid_token"))
except TimeoutError as e:
print(e)
except ValueError as e:
print(e)
try:
print(authenticate("invalid_token"))
except TimeoutError as e:
print(e)
except ValueError as e:
print(e)
Add your comment