import time
import hashlib
import base64
def assert_auth_token(token, expected_username, expected_expiry):
"""
Asserts the validity of an authentication token.
Args:
token (str): The authentication token to validate.
expected_username (str): The expected username associated with the token.
expected_expiry (float): The expected expiry timestamp (Unix timestamp).
Raises:
AssertionError: If any of the token's attributes do not match the expected values.
"""
try:
# Decode the token (assuming it's base64 encoded)
decoded_token = base64.b64decode(token)
token_str = decoded_token.decode('utf-8') #Decode to string
# Split the token into its components (username, expiry, etc.)
parts = token_str.split('|')
if len(parts) != 3:
raise AssertionError("Invalid token format: Expected username|expiry|signature")
username = parts[0].strip()
expiry_str = parts[1].strip()
signature = parts[2].strip()
# Validate username
if username != expected_username:
raise AssertionError(f"Invalid username: Expected '{expected_username}', got '{username}'")
# Validate expiry
try:
expiry = float(expiry_str)
if expiry < time.time():
raise AssertionError("Token has expired")
except ValueError:
raise AssertionError("Invalid expiry format")
# Verify signature (simple example - can be extended with more robust methods)
calculated_signature = calculate_signature(username, expiry, expected_username)
if calculated_signature != signature:
raise AssertionError("Invalid signature")
except Exception as e:
raise AssertionError(f"Token validation failed: {e}")
def calculate_signature(username, expiry, expected_username):
"""
Calculates a simple signature for the token. This is a placeholder.
In a real application, a more robust hashing algorithm should be used.
"""
data = f"{username}|{expiry}|{expected_username}"
hashed_data = hashlib.sha256(data.encode('utf-8')).hexdigest()
return hashed_data
if __name__ == '__main__':
# Example Usage
valid_token = "user123|1678886400|a1b2c3d4e5f67890" # Example token
invalid_token_username = "wronguser|1678886400|a1b2c3d4e5f67890" #Invalid username
invalid_token_expired = "user123|1678799200|a1b2c3d4e5f67890" #Expired token
try:
assert_auth_token(valid_token, "user123", 1678886400)
print("Valid token passed!")
except AssertionError as e:
print(f"Valid token failed: {e}")
try:
assert_auth_token(invalid_token_username, "user123", 1678886400)
print("Invalid username token passed!")
except AssertionError as e:
print(f"Invalid username token failed: {e}")
try:
assert_auth_token(invalid_token_expired, "user123", 1678886400)
print("Expired token passed!")
except AssertionError as e:
print(f"Expired token failed: {e}")
Add your comment