Files
medical_training/apps/user/auth/register.py
T

142 lines
6.5 KiB
Python
Raw Normal View History

2026-05-29 15:58:00 +08:00
import re
from django.core.cache import cache
from django.conf import settings
from django.db import transaction, IntegrityError
from rest_framework import status
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, Institution, Department
from apps.user.throttling import RegisterIpThrottle
from apps.user.utils.password import validate_password_strength
from apps.user.audit import log_register
from apps.user.auth import get_tokens_for_user, build_user_response, ALLOWED_ROLE_TYPES
@extend_schema(
summary='U2 用户注册',
request=inline_serializer('RegisterRequest', fields={
'phone': drf_serializers.CharField(help_text='手机号'),
'code': drf_serializers.CharField(help_text='6 位短信验证码'),
'password': drf_serializers.CharField(help_text='密码(>=6 位,含字母+数字)'),
'real_name': drf_serializers.CharField(help_text='真实姓名'),
'role_type': drf_serializers.ChoiceField(
choices=['student', 'doctor', 'teacher'],
required=False, default='student', help_text='角色类型'),
'institution_name': drf_serializers.CharField(required=False, help_text='机构名称'),
'department_name': drf_serializers.CharField(required=False, help_text='科室名称'),
}),
responses={201: inline_serializer('RegisterResponse', fields={
'message': drf_serializers.CharField(),
'user': drf_serializers.DictField(help_text='用户基本信息'),
'tokens': drf_serializers.DictField(help_text='access + refresh'),
})},
tags=['认证'],
)
@api_view(['POST'])
@permission_classes([AllowAny])
@throttle_classes([RegisterIpThrottle])
def register(request):
"""U2 用户注册(手机号 + 验证码 + 密码)"""
data = request.data
phone = str(data.get('phone', ''))
code = str(data.get('code', ''))
password = str(data.get('password', ''))
real_name = str(data.get('real_name', ''))
role_type = str(data.get('role_type', 'student'))
institution_name = data.get('institution_name') or ''
department_name = data.get('department_name') or ''
# ── 入参校验 ──────────────────────────────────────────────────────────────
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 real_name or len(real_name) < 2 or len(real_name) > 20:
raise AppError('USER_INVALID_NAME', '姓名长度应在 2-20 字符之间')
if role_type not in ALLOWED_ROLE_TYPES:
raise AppError('AUTH_INVALID_ROLE', '角色类型无效,仅允许 student / doctor / teacher')
# ── 密码强度 ──────────────────────────────────────────────────────────────
pwd_errors = validate_password_strength(password, phone=phone, real_name=real_name)
if pwd_errors:
raise AppError('AUTH_PASSWORD_WEAK', pwd_errors[0], details=pwd_errors)
# ── 验证码校验 ────────────────────────────────────────────────────────────
cache_key = f'sms:register:{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', '验证码错误')
# ── 机构 / 科室解析 ──────────────────────────────────────────────────────
institution = None
if institution_name:
try:
institution = Institution.objects.get(name=institution_name)
except Institution.DoesNotExist:
raise AppError('USER_INSTITUTION_NOT_FOUND', f'机构"{institution_name}"不存在')
except Institution.MultipleObjectsReturned:
raise AppError('USER_INSTITUTION_AMBIGUOUS', f'存在多个同名机构"{institution_name}"')
department = None
if department_name:
qs = Department.objects.filter(name=department_name)
if institution:
qs = qs.filter(institution=institution)
cnt = qs.count()
if cnt == 0:
raise AppError('USER_DEPARTMENT_NOT_FOUND', f'科室"{department_name}"不存在')
if cnt > 1:
raise AppError('USER_DEPARTMENT_AMBIGUOUS',
f'科室"{department_name}"不唯一,请同时指定 institution_name')
department = qs.first()
# ── 事务内创建用户 ────────────────────────────────────────────────────────
try:
with transaction.atomic():
if User.objects.filter(phone=phone).exists():
raise AppError('AUTH_PHONE_REGISTERED', '该手机号已注册')
user = User.objects.create_user(
username=phone,
password=password,
phone=phone,
real_name=real_name,
role_type=role_type,
institution=institution,
department=department,
status=1,
)
except AppError:
raise
except IntegrityError:
raise AppError('AUTH_PHONE_REGISTERED', '该手机号已注册')
# ── 善后 ──────────────────────────────────────────────────────────────────
cache.delete(cache_key)
tokens = get_tokens_for_user(user)
log_register(user.id, phone)
return Response({
'message': '注册成功',
'user': build_user_response(user),
'tokens': tokens,
}, status=status.HTTP_201_CREATED)