Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 8 additions & 21 deletions apps/chat/serializers/chat_user_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand All @@ -60,16 +48,15 @@ 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:
if not captcha:
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"))
Expand All @@ -78,22 +65,22 @@ 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


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)
Expand Down
28 changes: 19 additions & 9 deletions apps/chat/views/v3/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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):
Expand Down
Loading