1. import os
  2. import json
  3. def is_allowed_to_diagnose(user_id):
  4. """
  5. Checks if a user is allowed to have their data used for diagnostics.
  6. This is a placeholder - replace with your actual authorization logic.
  7. """
  8. # Example: Allow only specific user IDs or based on a flag in a config file.
  9. allowed_ids = ["user123", "user456"]
  10. if user_id in allowed_ids:
  11. return True
  12. else:
  13. return False
  14. def safeguard_data_for_diagnostics(user_data, user_id, diagnostics_file="diagnostics.json"):
  15. """
  16. Safeguards user data for diagnostics, only if authorized.
  17. """
  18. if is_allowed_to_diagnose(user_id):
  19. try:
  20. with open(diagnostics_file, "r") as f:
  21. diagnostics = json.load(f)
  22. except FileNotFoundError:
  23. diagnostics = {}
  24. if user_id not in diagnostics:
  25. diagnostics[user_id] = {}
  26. # Copy user data to diagnostics, excluding sensitive fields.
  27. data_to_diagnose = {k: v for k, v in user_data.items() if not k.startswith("_")} #example: exclude fields starting with underscore
  28. diagnostics[user_id].update(data_to_diagnose)
  29. with open(diagnostics_file, "w") as f:
  30. json.dump(diagnostics, f, indent=4)
  31. print(f"Data for user {user_id} saved for diagnostics.")
  32. else:
  33. print(f"Diagnostics not enabled for user {user_id}.")
  34. if __name__ == '__main__':
  35. # Example Usage
  36. user_data = {
  37. "name": "Alice",
  38. "email": "alice@example.com",
  39. "age": 30,
  40. "_password": "secret", #sensitive data
  41. "location": "New York"
  42. }
  43. user_id = "user123" # Replace with actual user ID
  44. safeguard_data_for_diagnostics(user_data, user_id)
  45. user_id = "user789"
  46. safeguard_data_for_diagnostics(user_data, user_id)

Add your comment