helpers.py 1.8 KB

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