From bc994f4159bb9dcaedccec572bd0671403e0c988 Mon Sep 17 00:00:00 2001 From: wxg0103 <727495428@qq.com> Date: Fri, 14 Aug 2026 16:45:47 +0800 Subject: [PATCH] refactor: update user instance serialization in user_group.py for improved clarity --- apps/chat/serializers/chat_user_serializer.py | 29 +++++-------------- apps/chat/views/v3/chat.py | 28 ++++++++++++------ 2 files changed, 27 insertions(+), 30 deletions(-) diff --git a/apps/chat/serializers/chat_user_serializer.py b/apps/chat/serializers/chat_user_serializer.py index a0162f863e8..634029f3b7b 100644 --- a/apps/chat/serializers/chat_user_serializer.py +++ b/apps/chat/serializers/chat_user_serializer.py @@ -5,9 +5,6 @@ from rest_framework import serializers from application.models import ApplicationAccessToken -from common.auth.common import ChatToken, FileToken -from common.auth.constants.operate_constants import Operate -from common.constants.authentication_type import AuthenticationType from common.constants.cache_version import Cache_Version from common.exception.app_exception import AppApiException from common.utils.common import password_encrypt @@ -20,21 +17,12 @@ class ChatUserAccessTokenV3Serializer(serializers.Serializer): - - @staticmethod - def create_token_and_cache(user, request): - _type = AuthenticationType.CHAT_USER - token = ChatToken(str(user.id),_type, str(Operate.LOCAL)).to_token() - return token, FileToken(str(user.id),_type).to_token() - @staticmethod def get_auth_setting(): - application_access_token = ApplicationAccessToken.objects.filter( - is_active=True - ).first() + application_access_token = ApplicationAccessToken.objects.filter(is_active=True).first() if not application_access_token: - raise AppApiException(1005, _('Invalid access token')) + raise AppApiException(1005, _("Invalid access token")) return application_access_token.authentication_value @@ -60,7 +48,7 @@ def local_login(instance): if max_attempts == -1: need_captcha = False elif max_attempts > 0: - fail_count = cache.get(system_get_key(f'chat_{username}'), version=system_version) or 0 + fail_count = cache.get(system_get_key(f"chat_{username}"), version=system_version) or 0 need_captcha = fail_count >= max_attempts if need_captcha: @@ -68,8 +56,7 @@ def local_login(instance): raise AppApiException(1005, _("Captcha is required")) captcha_cache = cache.get( - Cache_Version.CAPTCHA.get_key(captcha=f"chat_{username}"), - version=Cache_Version.CAPTCHA.get_version() + Cache_Version.CAPTCHA.get_key(captcha=f"chat_{username}"), version=Cache_Version.CAPTCHA.get_version() ) if captcha_cache is None or captcha.lower() != captcha_cache: raise AppApiException(1005, _("Captcha code error or expiration")) @@ -78,14 +65,14 @@ def local_login(instance): if not user or not password_verify(password, user.password): record_login_fail(username) - raise AppApiException(500, _('The username or password is incorrect')) + raise AppApiException(500, _("The username or password is incorrect")) if needs_password_upgrade(user.password): user.password = password_encrypt(password) - user.save(update_fields=['password']) + user.save(update_fields=["password"]) if not user.is_active: raise AppApiException(1005, _("The user has been disabled, please contact the administrator!")) - cache.delete(system_get_key(f'chat_{username}'), version=system_version) + cache.delete(system_get_key(f"chat_{username}"), version=system_version) return user @@ -93,7 +80,7 @@ def record_login_fail(username: str, expire: int = 600): """记录登录失败次数""" if not username: return - fail_key = system_get_key(f'chat_{username}') + fail_key = system_get_key(f"chat_{username}") fail_count = cache.get(fail_key, version=system_version) if fail_count is None: cache.set(fail_key, 1, timeout=expire, version=system_version) diff --git a/apps/chat/views/v3/chat.py b/apps/chat/views/v3/chat.py index 66dc23aa2e0..8fd53a8baf1 100644 --- a/apps/chat/views/v3/chat.py +++ b/apps/chat/views/v3/chat.py @@ -21,7 +21,7 @@ from rest_framework.views import APIView from application.api.application_api import SpeechToTextAPI, TextToSpeechAPI -from application.models import ChatUserType, ChatSourceChoices +from application.models import ChatUserType, ChatSourceChoices, ApplicationAccessToken from chat.api.chat_api import ChatAPI from chat.api.chat_authentication_api import ChatAuthenticationAPI, ChatAuthenticationProfileAPI, ChatOpenAPI, OpenAIAPI from chat.serializers.chat import ( @@ -38,12 +38,12 @@ ) from common.auth import ChatTokenAuth from common.auth.authentication import has_permissions -from common.auth.common import FileToken +from common.auth.common import FileToken, ChatToken from common.auth.constants.chat_permission_constants import ChatPermissionConstants +from common.auth.constants.operate_constants import Operate from common.constants.authentication_type import AuthenticationType from common.constants.cache_version import Cache_Version -from common.auth.common import ChatAuthentication -from common.exception.app_exception import AppAuthenticationFailed, AppApiException +from common.exception.app_exception import AppApiException from common.log.log import _get_ip_address, log from common.result import result from common.utils.rsa_util import decrypt @@ -409,7 +409,7 @@ def post(self, request: Request): decrypted_data = json.loads(decrypted_raw) if decrypted_raw else {} if isinstance(decrypted_data, dict): request_data = decrypted_data - except Exception as e: + except Exception: raise AppApiException(500, _("Invalid encrypted data")) serializer_obj = RePasswordSerializer(data=request_data) if serializer_obj.reset_password(request.user.id): @@ -437,8 +437,17 @@ def get(self, request: Request): class BaseAuthView(APIView): @staticmethod - def create_token_and_cache(user, request): - token, f_token = ChatUserAccessTokenV3Serializer.create_token_and_cache(user, request) + def create_token_and_cache(user, access_token, operate): + application_id = None + if access_token: + application_id = ( + ApplicationAccessToken.objects.filter(access_token=access_token, is_active=True) + .values_list("application_id", flat=True) + .first() + ) + token = ChatToken( + str(user.id), AuthenticationType.CHAT_USER, str(operate), application_id=application_id + ).to_token() version, get_key = Cache_Version.CHAT_USER_TOKEN.value cache.set(get_key(token), user, timeout=60 * 60 * 2, version=version) return token, FileToken(str(user.id), AuthenticationType.CHAT_USER.value).to_token() @@ -472,9 +481,10 @@ class LocalLoginView(BaseAuthView): def post(self, request: Request): user = ChatUserAccessTokenV3Serializer.local_login(request.data) user.source = "LOCAL" - token, f_token = self.create_token_and_cache(user, request) + access_token = request.query_params.get("accessToken") + token, f_token = self.create_token_and_cache(user, access_token, Operate.LOCAL) response = result.success({"token": token}) - return self.generate(request, f_token, response, path=f"/chat/") + return self.generate(request, f_token, response, path=f"/chat/{access_token + '/' if access_token else ''}") class Logout(APIView):