perf: 🐛 修复用户登录后,每次都会变化密码加密值bug

pull/98/head
李强 2023-05-28 12:14:39 +08:00
parent 815b8e956b
commit c9db799304
2 changed files with 18 additions and 12 deletions

View File

@ -1,6 +1,6 @@
import hashlib import hashlib
from django.contrib.auth.hashers import make_password from django.contrib.auth.hashers import make_password, check_password
from django_restql.fields import DynamicSerializerMethodField from django_restql.fields import DynamicSerializerMethodField
from rest_framework import serializers from rest_framework import serializers
from rest_framework.decorators import action, permission_classes from rest_framework.decorators import action, permission_classes
@ -347,10 +347,10 @@ class UserViewSet(CustomModelViewSet):
return ErrorResponse(msg="参数不能为空") return ErrorResponse(msg="参数不能为空")
if new_pwd != new_pwd2: if new_pwd != new_pwd2:
return ErrorResponse(msg="两次密码不匹配") return ErrorResponse(msg="两次密码不匹配")
check_password = request.user.check_password(old_pwd) verify_password = check_password(old_pwd, self.request.user.password)
if not check_password: if not verify_password:
check_password = request.user.check_password(hashlib.md5(old_pwd.encode(encoding='UTF-8')).hexdigest()) verify_password = check_password(hashlib.md5(old_pwd.encode(encoding='UTF-8')).hexdigest(), self.request.user.password)
if check_password: if verify_password:
request.user.password = make_password(new_pwd) request.user.password = make_password(new_pwd)
request.user.save() request.user.save()
return DetailResponse(data=None, msg="修改成功") return DetailResponse(data=None, msg="修改成功")

View File

@ -3,8 +3,11 @@ import logging
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.hashers import check_password
from django.utils import timezone from django.utils import timezone
from dvadmin.utils.validator import CustomValidationError
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
UserModel = get_user_model() UserModel = get_user_model()
@ -24,10 +27,13 @@ class CustomBackend(ModelBackend):
except UserModel.DoesNotExist: except UserModel.DoesNotExist:
UserModel().set_password(password) UserModel().set_password(password)
else: else:
check_password = user.check_password(password) verify_password = check_password(password, user.password)
if not check_password: if not verify_password:
check_password = user.check_password(hashlib.md5(password.encode(encoding='UTF-8')).hexdigest()) password = hashlib.md5(password.encode(encoding='UTF-8')).hexdigest()
if check_password and self.user_can_authenticate(user): verify_password = check_password(password, user.password)
user.last_login = timezone.now() if verify_password:
user.save() if self.user_can_authenticate(user):
return user user.last_login = timezone.now()
user.save()
return user
raise CustomValidationError("当前用户已被禁用,请联系管理员!")