66 @date:2025/4/14 11:08
77 @desc:
88"""
9+ import base64
910import datetime
1011
12+ from captcha .image import ImageCaptcha
1113from django .core import signing
1214from django .core .cache import cache
1315from django .db .models import QuerySet
1719from common .constants .authentication_type import AuthenticationType
1820from common .constants .cache_version import Cache_Version
1921from common .exception .app_exception import AppApiException
20- from common .utils .common import password_encrypt
22+ from common .utils .common import password_encrypt , get_random_chars
2123from users .models import User
2224
2325
2426class LoginRequest (serializers .Serializer ):
2527 username = serializers .CharField (required = True , max_length = 64 , help_text = _ ("Username" ), label = _ ("Username" ))
2628 password = serializers .CharField (required = True , max_length = 128 , label = _ ("Password" ))
29+ captcha = serializers .CharField (required = True , max_length = 64 , label = _ ('captcha' ))
2730
2831
2932class LoginResponse (serializers .Serializer ):
@@ -40,6 +43,11 @@ def login(instance):
4043 LoginRequest (data = instance ).is_valid (raise_exception = True )
4144 username = instance .get ('username' )
4245 password = instance .get ('password' )
46+ captcha = instance .get ('captcha' )
47+ captcha_cache = cache .get (Cache_Version .CAPTCHA .get_key (captcha = captcha ),
48+ version = Cache_Version .CAPTCHA .get_version ())
49+ if captcha_cache is None :
50+ raise AppApiException (1005 , _ ("Captcha code error or expiration" ))
4351 user = QuerySet (User ).filter (username = username , password = password_encrypt (password )).first ()
4452 if user is None :
4553 raise AppApiException (500 , _ ('The username or password is incorrect' ))
@@ -52,3 +60,22 @@ def login(instance):
5260 version , get_key = Cache_Version .TOKEN .value
5361 cache .set (get_key (token ), user , timeout = datetime .timedelta (seconds = 60 * 60 * 2 ).seconds , version = version )
5462 return {'token' : token }
63+
64+
65+ class CaptchaResponse (serializers .Serializer ):
66+ """
67+ 登录响应对象
68+ """
69+ captcha = serializers .CharField (required = True , label = _ ("captcha" ))
70+
71+
72+ class CaptchaSerializer (serializers .Serializer ):
73+ @staticmethod
74+ def generate ():
75+ chars = get_random_chars ()
76+ image = ImageCaptcha ()
77+ data = image .generate (chars )
78+ captcha = base64 .b64encode (data .getbuffer ())
79+ cache .set (Cache_Version .CAPTCHA .get_key (captcha = chars ), chars ,
80+ timeout = 60 , version = Cache_Version .CAPTCHA .get_version ())
81+ return {'captcha' : 'data:image/png;base64,' + captcha .decode ()}
0 commit comments