From c68c67441300446542b2041fa17c1ad22a1da549 Mon Sep 17 00:00:00 2001 From: ytqh Date: Sat, 1 Mar 2025 20:51:31 +0800 Subject: [PATCH] add service auth api in load user from request lib --- .../service_api_with_auth/auth/login.py | 4 ---- api/extensions/ext_login.py | 17 ++++++++++------- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/api/controllers/service_api_with_auth/auth/login.py b/api/controllers/service_api_with_auth/auth/login.py index 229287f380..0ec78add11 100644 --- a/api/controllers/service_api_with_auth/auth/login.py +++ b/api/controllers/service_api_with_auth/auth/login.py @@ -34,8 +34,6 @@ class LogoutApi(Resource): - user/auth summary: Logout User description: Logs out the authenticated user and invalidates the session - security: - - ApiKeyAuth: [] responses: 200: description: Successfully logged out @@ -241,8 +239,6 @@ class RefreshTokenApi(Resource): - user/auth summary: Refresh Token description: Refreshes an access token using a valid refresh token - security: - - ApiKeyAuth: [] parameters: - in: body name: body diff --git a/api/extensions/ext_login.py b/api/extensions/ext_login.py index 10fb89eb73..b0ce868b48 100644 --- a/api/extensions/ext_login.py +++ b/api/extensions/ext_login.py @@ -1,14 +1,13 @@ import json +import contexts import flask_login # type: ignore +from dify_app import DifyApp from flask import Response, request from flask_login import user_loaded_from_request, user_logged_in -from werkzeug.exceptions import Unauthorized - -import contexts -from dify_app import DifyApp from libs.passport import PassportService from services.account_service import AccountService +from werkzeug.exceptions import Unauthorized login_manager = flask_login.LoginManager() @@ -17,7 +16,7 @@ login_manager = flask_login.LoginManager() @login_manager.request_loader def load_user_from_request(request_from_flask_login): """Load user based on the request.""" - if request.blueprint not in {"console", "inner_api"}: + if request.blueprint not in {"console", "inner_api", "service_api_with_auth"}: return None # Check if the user_id contains a dot, indicating the old format auth_header = request.headers.get("Authorization", "") @@ -27,11 +26,15 @@ def load_user_from_request(request_from_flask_login): raise Unauthorized("Invalid Authorization token.") else: if " " not in auth_header: - raise Unauthorized("Invalid Authorization header format. Expected 'Bearer ' format.") + raise Unauthorized( + "Invalid Authorization header format. Expected 'Bearer ' format." + ) auth_scheme, auth_token = auth_header.split(None, 1) auth_scheme = auth_scheme.lower() if auth_scheme != "bearer": - raise Unauthorized("Invalid Authorization header format. Expected 'Bearer ' format.") + raise Unauthorized( + "Invalid Authorization header format. Expected 'Bearer ' format." + ) decoded = PassportService().verify(auth_token) user_id = decoded.get("user_id")