feat: update medical training case and auth modules
This commit is contained in:
+24
-42
@@ -1,7 +1,5 @@
|
||||
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
|
||||
@@ -11,24 +9,29 @@ 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.models import User, 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
|
||||
from apps.user.auth import (
|
||||
get_tokens_for_user, build_user_response, ALLOWED_ROLE_TYPES,
|
||||
resolve_or_create_institution,
|
||||
)
|
||||
|
||||
DEFAULT_PASSWORD_PREFIX = 'Pass'
|
||||
|
||||
|
||||
@extend_schema(
|
||||
summary='U2 用户注册',
|
||||
summary='U2 管理员代注册',
|
||||
description='CMS 管理员为他人注册账号,无需验证码。默认密码为 Pass+手机号(如 Pass13800001001),用户可自行修改。'
|
||||
'机构不存在会自动创建。',
|
||||
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='机构名称'),
|
||||
'institution_code': drf_serializers.CharField(help_text='机构编码(必填,唯一标识)'),
|
||||
'institution_name': drf_serializers.CharField(help_text='机构名称(必填)'),
|
||||
'department_name': drf_serializers.CharField(required=False, help_text='科室名称'),
|
||||
}),
|
||||
responses={201: inline_serializer('RegisterResponse', fields={
|
||||
@@ -39,18 +42,17 @@ from apps.user.auth import get_tokens_for_user, build_user_response, ALLOWED_ROL
|
||||
tags=['认证'],
|
||||
)
|
||||
@api_view(['POST'])
|
||||
@permission_classes([AllowAny])
|
||||
@permission_classes([AllowAny]) # TODO: 上线前改为管理员权限
|
||||
@throttle_classes([RegisterIpThrottle])
|
||||
def register(request):
|
||||
"""U2 用户注册(手机号 + 验证码 + 密码)"""
|
||||
"""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 ''
|
||||
institution_code = str(data.get('institution_code', '')).strip()
|
||||
institution_name = str(data.get('institution_name', '')).strip()
|
||||
department_name = data.get('department_name') or ''
|
||||
|
||||
# ── 入参校验 ──────────────────────────────────────────────────────────────
|
||||
@@ -58,52 +60,33 @@ def register(request):
|
||||
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')
|
||||
|
||||
# ── 密码强度 ──────────────────────────────────────────────────────────────
|
||||
if not institution_code:
|
||||
raise AppError('USER_INSTITUTION_CODE_REQUIRED', '机构编码不能为空')
|
||||
|
||||
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)
|
||||
if not institution_name:
|
||||
raise AppError('USER_INSTITUTION_REQUIRED', '机构名称不能为空')
|
||||
|
||||
# ── 验证码校验 ────────────────────────────────────────────────────────────
|
||||
|
||||
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', '验证码错误')
|
||||
password = f'{DEFAULT_PASSWORD_PREFIX}{phone}'
|
||||
|
||||
# ── 机构 / 科室解析 ──────────────────────────────────────────────────────
|
||||
|
||||
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}"')
|
||||
institution = resolve_or_create_institution(institution_code, institution_name)
|
||||
|
||||
department = None
|
||||
if department_name:
|
||||
qs = Department.objects.filter(name=department_name)
|
||||
if institution:
|
||||
qs = qs.filter(institution=institution)
|
||||
qs = Department.objects.filter(name=department_name, 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')
|
||||
f'科室"{department_name}"不唯一')
|
||||
department = qs.first()
|
||||
|
||||
# ── 事务内创建用户 ────────────────────────────────────────────────────────
|
||||
@@ -130,7 +113,6 @@ def register(request):
|
||||
|
||||
# ── 善后 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
cache.delete(cache_key)
|
||||
tokens = get_tokens_for_user(user)
|
||||
log_register(user.id, phone)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user