import json
def load_tokens(filepath):
"""Loads authentication tokens from a JSON file.
Args:
filepath (str): The path to the JSON file containing the tokens.
Returns:
dict: A dictionary of tokens, or an empty dictionary if the file
doesn't exist or is invalid. Returns None if there's a JSON decode error.
"""
try:
with open(filepath, 'r') as f:
tokens = json.load(f)
return tokens
except FileNotFoundError:
print(f"File not found: {filepath}")
return {}
except json.JSONDecodeError:
print(f"Invalid JSON format in {filepath}")
return None
def validate_token(token):
"""Performs basic validation on an authentication token.
Args:
token (str): The token to validate.
Returns:
bool: True if the token is valid, False otherwise.
"""
if not isinstance(token, str):
print("Invalid token type: Must be a string.")
return False
if not token:
print("Token cannot be empty.")
return False
if len(token) < 10: #Example length check
print("Token too short.")
return False
return True
if __name__ == '__main__':
# Example Usage:
token_file = 'tokens.json' # Replace with your file path
tokens = load_tokens(token_file)
if tokens is not None:
if tokens:
print("Loaded tokens:", tokens)
else:
print("No tokens loaded.")
#Example token validation
if tokens:
test_token = "valid_token_123"
if validate_token(test_token):
print(f"{test_token} is valid.")
else:
print(f"{test_token} is invalid.")
invalid_token = 123
if validate_token(invalid_token):
print(f"{invalid_token} is valid.")
else:
print(f"{invalid_token} is invalid.")
Add your comment