from my_modules.app.constens import SECRET_KEY import hmac, hashlib, base64, secrets, time from urllib.parse import quote, unquote def base64url_encode(data: bytes) -> str: return base64.urlsafe_b64encode(data).decode().rstrip("=") def base64url_decode(data: str) -> bytes: padding = '=' * (-len(data) % 4) return base64.urlsafe_b64decode(data + padding) def generate_short_id(length=8): token = base64.urlsafe_b64encode(secrets.token_bytes(length)).decode('utf-8') return token.replace('=', '').replace('-', '').replace('_', '')[:length] def generate_signed_url(file_id: str) -> str: # signature based only on the file_id sig = hmac.new(SECRET_KEY, file_id.encode(), hashlib.sha256).digest() token = base64url_encode(sig) return f"-{file_id}?sig={token}" def verify_signed_url(file_id: str, token: str, file_expiration: int) -> bool: # check both the signature and the file's stored expiration time expected_sig = hmac.new(SECRET_KEY, file_id.encode(), hashlib.sha256).digest() valid_sig = hmac.compare_digest(base64url_encode(expected_sig), token) not_expired = file_expiration >= time.time() return valid_sig and not_expired if __name__ == "__main__": file_id = generate_short_id() url = generate_signed_url(file_id) print(url)