helpers.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import base64
  2. import hashlib
  3. import hmac
  4. import os
  5. import time
  6. from configs import dify_config
  7. def get_signed_file_url(upload_file_id: str) -> str:
  8. url = f"{dify_config.FILES_URL}/files/{upload_file_id}/file-preview"
  9. timestamp = str(int(time.time()))
  10. nonce = os.urandom(16).hex()
  11. key = dify_config.SECRET_KEY.encode()
  12. msg = f"file-preview|{upload_file_id}|{timestamp}|{nonce}"
  13. sign = hmac.new(key, msg.encode(), hashlib.sha256).digest()
  14. encoded_sign = base64.urlsafe_b64encode(sign).decode()
  15. return f"{url}?timestamp={timestamp}&nonce={nonce}&sign={encoded_sign}"
  16. def verify_image_signature(*, upload_file_id: str, timestamp: str, nonce: str, sign: str) -> bool:
  17. data_to_sign = f"image-preview|{upload_file_id}|{timestamp}|{nonce}"
  18. secret_key = dify_config.SECRET_KEY.encode()
  19. recalculated_sign = hmac.new(secret_key, data_to_sign.encode(), hashlib.sha256).digest()
  20. recalculated_encoded_sign = base64.urlsafe_b64encode(recalculated_sign).decode()
  21. # verify signature
  22. if sign != recalculated_encoded_sign:
  23. return False
  24. current_time = int(time.time())
  25. return current_time - int(timestamp) <= dify_config.FILES_ACCESS_TIMEOUT
  26. def verify_file_signature(*, upload_file_id: str, timestamp: str, nonce: str, sign: str) -> bool:
  27. data_to_sign = f"file-preview|{upload_file_id}|{timestamp}|{nonce}"
  28. secret_key = dify_config.SECRET_KEY.encode()
  29. recalculated_sign = hmac.new(secret_key, data_to_sign.encode(), hashlib.sha256).digest()
  30. recalculated_encoded_sign = base64.urlsafe_b64encode(recalculated_sign).decode()
  31. # verify signature
  32. if sign != recalculated_encoded_sign:
  33. return False
  34. current_time = int(time.time())
  35. return current_time - int(timestamp) <= dify_config.FILES_ACCESS_TIMEOUT