2024-04-18 17:33:32 +08:00
|
|
|
from base64 import b64encode
|
|
|
|
from functools import wraps
|
|
|
|
from hashlib import sha1
|
|
|
|
from hmac import new as hmac_new
|
|
|
|
|
2024-07-12 16:51:43 +08:00
|
|
|
from flask import abort, request
|
2024-04-18 17:33:32 +08:00
|
|
|
|
2024-07-12 16:51:43 +08:00
|
|
|
from configs import dify_config
|
2024-04-18 17:33:32 +08:00
|
|
|
from extensions.ext_database import db
|
|
|
|
from models.model import EndUser
|
|
|
|
|
|
|
|
|
|
|
|
def inner_api_only(view):
|
|
|
|
@wraps(view)
|
|
|
|
def decorated(*args, **kwargs):
|
2024-07-12 16:51:43 +08:00
|
|
|
if not dify_config.INNER_API:
|
2024-04-18 17:33:32 +08:00
|
|
|
abort(404)
|
|
|
|
|
|
|
|
# get header 'X-Inner-Api-Key'
|
2024-08-26 15:29:10 +08:00
|
|
|
inner_api_key = request.headers.get("X-Inner-Api-Key")
|
2024-07-12 16:51:43 +08:00
|
|
|
if not inner_api_key or inner_api_key != dify_config.INNER_API_KEY:
|
2024-08-01 17:41:35 +08:00
|
|
|
abort(401)
|
2024-04-18 17:33:32 +08:00
|
|
|
|
|
|
|
return view(*args, **kwargs)
|
|
|
|
|
|
|
|
return decorated
|
|
|
|
|
|
|
|
|
|
|
|
def inner_api_user_auth(view):
|
|
|
|
@wraps(view)
|
|
|
|
def decorated(*args, **kwargs):
|
2024-07-12 16:51:43 +08:00
|
|
|
if not dify_config.INNER_API:
|
2024-04-18 17:33:32 +08:00
|
|
|
return view(*args, **kwargs)
|
|
|
|
|
|
|
|
# get header 'X-Inner-Api-Key'
|
2024-08-26 15:29:10 +08:00
|
|
|
authorization = request.headers.get("Authorization")
|
2024-04-18 17:33:32 +08:00
|
|
|
if not authorization:
|
|
|
|
return view(*args, **kwargs)
|
|
|
|
|
2024-08-26 15:29:10 +08:00
|
|
|
parts = authorization.split(":")
|
2024-04-18 17:33:32 +08:00
|
|
|
if len(parts) != 2:
|
|
|
|
return view(*args, **kwargs)
|
|
|
|
|
|
|
|
user_id, token = parts
|
2024-08-26 15:29:10 +08:00
|
|
|
if " " in user_id:
|
|
|
|
user_id = user_id.split(" ")[1]
|
2024-04-18 17:33:32 +08:00
|
|
|
|
2024-08-26 15:29:10 +08:00
|
|
|
inner_api_key = request.headers.get("X-Inner-Api-Key")
|
2024-04-18 17:33:32 +08:00
|
|
|
|
2024-08-26 15:29:10 +08:00
|
|
|
data_to_sign = f"DIFY {user_id}"
|
2024-04-18 17:33:32 +08:00
|
|
|
|
2024-08-26 15:29:10 +08:00
|
|
|
signature = hmac_new(inner_api_key.encode("utf-8"), data_to_sign.encode("utf-8"), sha1)
|
|
|
|
signature = b64encode(signature.digest()).decode("utf-8")
|
2024-04-18 17:33:32 +08:00
|
|
|
|
|
|
|
if signature != token:
|
|
|
|
return view(*args, **kwargs)
|
|
|
|
|
2024-08-26 15:29:10 +08:00
|
|
|
kwargs["user"] = db.session.query(EndUser).filter(EndUser.id == user_id).first()
|
2024-04-18 17:33:32 +08:00
|
|
|
|
|
|
|
return view(*args, **kwargs)
|
|
|
|
|
|
|
|
return decorated
|