import re from django.core.cache import cache from django.db import transaction from rest_framework.decorators import api_view, permission_classes, throttle_classes from rest_framework.permissions import AllowAny from rest_framework.response import Response from rest_framework import serializers as drf_serializers from drf_spectacular.utils import extend_schema, inline_serializer from config.exceptions import AppError from apps.user.models import User from apps.user.throttling import ResetPhoneThrottle from apps.user.utils.password import validate_password_strength from apps.user.utils.jwt_redis import invalidate_user_tokens from apps.user.audit import log_password_reset @extend_schema( summary='U5 找回密码', request=inline_serializer('ResetPasswordRequest', fields={ 'phone': drf_serializers.CharField(help_text='手机号'), 'code': drf_serializers.CharField(help_text='6 位短信验证码'), 'new_password': drf_serializers.CharField(help_text='新密码'), }), responses={200: inline_serializer('ResetPasswordResponse', fields={ 'message': drf_serializers.CharField(), })}, tags=['认证'], ) @api_view(['POST']) @permission_classes([AllowAny]) @throttle_classes([ResetPhoneThrottle]) def reset_password(request): """U5 找回密码(手机号 + 验证码 + 新密码)""" data = request.data phone = str(data.get('phone', '')) code = str(data.get('code', '')) new_password = str(data.get('new_password', '')) # ── 入参校验 ────────────────────────────────────────────────────────────── if not re.match(r'^1[3-9]\d{9}$', phone): raise AppError('SMS_INVALID_PHONE', '手机号格式不合法') if not code or len(code) != 6 or not code.isdigit(): raise AppError('AUTH_CODE_INVALID', '验证码必须为 6 位数字') if not new_password: raise AppError('AUTH_PASSWORD_WEAK', '请输入新密码') # ── 查找用户 ────────────────────────────────────────────────────────────── try: user = User.objects.get(phone=phone) except User.DoesNotExist: raise AppError('AUTH_PHONE_NOT_FOUND', '手机号未注册') # ── 验证码校验 ──────────────────────────────────────────────────────────── cache_key = f'sms:reset:{phone}' cached_code = cache.get(cache_key) if not cached_code: raise AppError('AUTH_CODE_EXPIRED', '验证码已过期或未发送') if str(cached_code) != code: raise AppError('AUTH_CODE_MISMATCH', '验证码错误') # ── 新密码校验 ──────────────────────────────────────────────────────────── # 新密码不得与旧密码相同(独立错误码) if user.check_password(new_password): raise AppError('AUTH_PASSWORD_SAME_AS_OLD', '新密码不能与旧密码相同') # 密码强度校验 pwd_errors = validate_password_strength(new_password, phone=user.phone, real_name=user.real_name) if pwd_errors: raise AppError('AUTH_PASSWORD_WEAK', pwd_errors[0], details=pwd_errors) # ── 事务内:重置密码 + 失效旧 token ────────────────────────────────────── with transaction.atomic(): user.set_password(new_password) user.save(update_fields=['password']) invalidate_user_tokens(user.id) # ── 善后 ────────────────────────────────────────────────────────────────── cache.delete(cache_key) cache.delete(f'login_fail:{phone}') log_password_reset(user.id) return Response({'message': '密码已重置,请重新登录'})