dify/api/controllers/web/wraps.py

49 lines
1.5 KiB
Python
Raw Normal View History

2023-05-15 08:51:32 +08:00
# -*- coding:utf-8 -*-
from functools import wraps
from flask import request
2023-05-15 08:51:32 +08:00
from flask_restful import Resource
from werkzeug.exceptions import NotFound, Unauthorized
from extensions.ext_database import db
from models.model import App, EndUser
from libs.passport import PassportService
2023-05-15 08:51:32 +08:00
def validate_jwt_token(view=None):
2023-05-15 08:51:32 +08:00
def decorator(view):
@wraps(view)
def decorated(*args, **kwargs):
app_model, end_user = decode_jwt_token()
2023-05-15 08:51:32 +08:00
return view(app_model, end_user, *args, **kwargs)
return decorated
if view:
return decorator(view)
return decorator
def decode_jwt_token():
2023-05-15 08:51:32 +08:00
auth_header = request.headers.get('Authorization')
if auth_header is None:
2023-05-25 15:54:45 +08:00
raise Unauthorized('Authorization header is missing.')
if ' ' not in auth_header:
raise Unauthorized('Invalid Authorization header format. Expected \'Bearer <api-key>\' format.')
auth_scheme, tk = auth_header.split(None, 1)
2023-05-15 08:51:32 +08:00
auth_scheme = auth_scheme.lower()
if auth_scheme != 'bearer':
2023-05-25 15:54:45 +08:00
raise Unauthorized('Invalid Authorization header format. Expected \'Bearer <api-key>\' format.')
decoded = PassportService().verify(tk)
app_model = db.session.query(App).filter(App.id == decoded['app_id']).first()
if not app_model:
raise NotFound()
end_user = db.session.query(EndUser).filter(EndUser.id == decoded['end_user_id']).first()
if not end_user:
2023-05-15 08:51:32 +08:00
raise NotFound()
return app_model, end_user
2023-05-15 08:51:32 +08:00
class WebApiResource(Resource):
method_decorators = [validate_jwt_token]