Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

helpers.py 2.3KB

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