1. import time
  2. import hashlib
  3. import base64
  4. def assert_auth_token(token, expected_username, expected_expiry):
  5. """
  6. Asserts the validity of an authentication token.
  7. Args:
  8. token (str): The authentication token to validate.
  9. expected_username (str): The expected username associated with the token.
  10. expected_expiry (float): The expected expiry timestamp (Unix timestamp).
  11. Raises:
  12. AssertionError: If any of the token's attributes do not match the expected values.
  13. """
  14. try:
  15. # Decode the token (assuming it's base64 encoded)
  16. decoded_token = base64.b64decode(token)
  17. token_str = decoded_token.decode('utf-8') #Decode to string
  18. # Split the token into its components (username, expiry, etc.)
  19. parts = token_str.split('|')
  20. if len(parts) != 3:
  21. raise AssertionError("Invalid token format: Expected username|expiry|signature")
  22. username = parts[0].strip()
  23. expiry_str = parts[1].strip()
  24. signature = parts[2].strip()
  25. # Validate username
  26. if username != expected_username:
  27. raise AssertionError(f"Invalid username: Expected '{expected_username}', got '{username}'")
  28. # Validate expiry
  29. try:
  30. expiry = float(expiry_str)
  31. if expiry < time.time():
  32. raise AssertionError("Token has expired")
  33. except ValueError:
  34. raise AssertionError("Invalid expiry format")
  35. # Verify signature (simple example - can be extended with more robust methods)
  36. calculated_signature = calculate_signature(username, expiry, expected_username)
  37. if calculated_signature != signature:
  38. raise AssertionError("Invalid signature")
  39. except Exception as e:
  40. raise AssertionError(f"Token validation failed: {e}")
  41. def calculate_signature(username, expiry, expected_username):
  42. """
  43. Calculates a simple signature for the token. This is a placeholder.
  44. In a real application, a more robust hashing algorithm should be used.
  45. """
  46. data = f"{username}|{expiry}|{expected_username}"
  47. hashed_data = hashlib.sha256(data.encode('utf-8')).hexdigest()
  48. return hashed_data
  49. if __name__ == '__main__':
  50. # Example Usage
  51. valid_token = "user123|1678886400|a1b2c3d4e5f67890" # Example token
  52. invalid_token_username = "wronguser|1678886400|a1b2c3d4e5f67890" #Invalid username
  53. invalid_token_expired = "user123|1678799200|a1b2c3d4e5f67890" #Expired token
  54. try:
  55. assert_auth_token(valid_token, "user123", 1678886400)
  56. print("Valid token passed!")
  57. except AssertionError as e:
  58. print(f"Valid token failed: {e}")
  59. try:
  60. assert_auth_token(invalid_token_username, "user123", 1678886400)
  61. print("Invalid username token passed!")
  62. except AssertionError as e:
  63. print(f"Invalid username token failed: {e}")
  64. try:
  65. assert_auth_token(invalid_token_expired, "user123", 1678886400)
  66. print("Expired token passed!")
  67. except AssertionError as e:
  68. print(f"Expired token failed: {e}")

Add your comment