Underground-Digital/Workflow-Engine
0
1import base642import hashlib3import hmac4import os5import time6 7from configs import dify_config8 9 10def get_signed_file_url(upload_file_id: str) -> str:11 url = f"{dify_config.FILES_URL}/files/{upload_file_id}/file-preview"12 13 timestamp = str(int(time.time()))14 nonce = os.urandom(16).hex()15 key = dify_config.SECRET_KEY.encode()16 msg = f"file-preview|{upload_file_id}|{timestamp}|{nonce}"17 sign = hmac.new(key, msg.encode(), hashlib.sha256).digest()18 encoded_sign = base64.urlsafe_b64encode(sign).decode()19 20 return f"{url}?timestamp={timestamp}&nonce={nonce}&sign={encoded_sign}"21 22 23def verify_image_signature(*, upload_file_id: str, timestamp: str, nonce: str, sign: str) -> bool:24 data_to_sign = f"image-preview|{upload_file_id}|{timestamp}|{nonce}"25 secret_key = dify_config.SECRET_KEY.encode()26 recalculated_sign = hmac.new(secret_key, data_to_sign.encode(), hashlib.sha256).digest()27 recalculated_encoded_sign = base64.urlsafe_b64encode(recalculated_sign).decode()28 29 # verify signature30 if sign != recalculated_encoded_sign:31 return False32 33 current_time = int(time.time())34 return current_time - int(timestamp) <= dify_config.FILES_ACCESS_TIMEOUT35 36 37def verify_file_signature(*, upload_file_id: str, timestamp: str, nonce: str, sign: str) -> bool:38 data_to_sign = f"file-preview|{upload_file_id}|{timestamp}|{nonce}"39 secret_key = dify_config.SECRET_KEY.encode()40 recalculated_sign = hmac.new(secret_key, data_to_sign.encode(), hashlib.sha256).digest()41 recalculated_encoded_sign = base64.urlsafe_b64encode(recalculated_sign).decode()42 43 # verify signature44 if sign != recalculated_encoded_sign:45 return False46 47 current_time = int(time.time())48 return current_time - int(timestamp) <= dify_config.FILES_ACCESS_TIMEOUT49 