1. import json
  2. def load_tokens(filepath):
  3. """Loads authentication tokens from a JSON file.
  4. Args:
  5. filepath (str): The path to the JSON file containing the tokens.
  6. Returns:
  7. dict: A dictionary of tokens, or an empty dictionary if the file
  8. doesn't exist or is invalid. Returns None if there's a JSON decode error.
  9. """
  10. try:
  11. with open(filepath, 'r') as f:
  12. tokens = json.load(f)
  13. return tokens
  14. except FileNotFoundError:
  15. print(f"File not found: {filepath}")
  16. return {}
  17. except json.JSONDecodeError:
  18. print(f"Invalid JSON format in {filepath}")
  19. return None
  20. def validate_token(token):
  21. """Performs basic validation on an authentication token.
  22. Args:
  23. token (str): The token to validate.
  24. Returns:
  25. bool: True if the token is valid, False otherwise.
  26. """
  27. if not isinstance(token, str):
  28. print("Invalid token type: Must be a string.")
  29. return False
  30. if not token:
  31. print("Token cannot be empty.")
  32. return False
  33. if len(token) < 10: #Example length check
  34. print("Token too short.")
  35. return False
  36. return True
  37. if __name__ == '__main__':
  38. # Example Usage:
  39. token_file = 'tokens.json' # Replace with your file path
  40. tokens = load_tokens(token_file)
  41. if tokens is not None:
  42. if tokens:
  43. print("Loaded tokens:", tokens)
  44. else:
  45. print("No tokens loaded.")
  46. #Example token validation
  47. if tokens:
  48. test_token = "valid_token_123"
  49. if validate_token(test_token):
  50. print(f"{test_token} is valid.")
  51. else:
  52. print(f"{test_token} is invalid.")
  53. invalid_token = 123
  54. if validate_token(invalid_token):
  55. print(f"{invalid_token} is valid.")
  56. else:
  57. print(f"{invalid_token} is invalid.")

Add your comment