feat: update medical training case and auth modules
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
from rest_framework_simplejwt.tokens import RefreshToken
|
||||
|
||||
from config.exceptions import AppError
|
||||
|
||||
ALLOWED_ROLE_TYPES = ('student', 'doctor', 'teacher')
|
||||
|
||||
|
||||
@@ -9,17 +11,42 @@ def get_tokens_for_user(user):
|
||||
|
||||
|
||||
def build_user_response(user):
|
||||
inst = user.institution if user.institution_id else None
|
||||
return {
|
||||
'id': user.id,
|
||||
'username': user.username,
|
||||
'phone': user.phone,
|
||||
'real_name': user.real_name,
|
||||
'role_type': user.role_type,
|
||||
'institution': user.institution.name if user.institution_id else None,
|
||||
'institution_code': inst.code if inst else None,
|
||||
'institution_name': inst.name if inst else None,
|
||||
'department': user.department.name if user.department_id else None,
|
||||
}
|
||||
|
||||
|
||||
def resolve_or_create_institution(code, name):
|
||||
"""按机构编码查找,不存在则自动创建。
|
||||
|
||||
Args:
|
||||
code: 机构编码(必填,唯一标识)
|
||||
name: 机构名称(必填,创建时使用)
|
||||
Returns:
|
||||
Institution 实例
|
||||
"""
|
||||
from apps.user.models import Institution
|
||||
|
||||
if not code:
|
||||
raise AppError('USER_INSTITUTION_CODE_REQUIRED', '机构编码不能为空')
|
||||
if not name:
|
||||
raise AppError('USER_INSTITUTION_REQUIRED', '机构名称不能为空')
|
||||
|
||||
institution, _ = Institution.objects.get_or_create(
|
||||
code=code,
|
||||
defaults={'name': name, 'type': 'hospital'},
|
||||
)
|
||||
return institution
|
||||
|
||||
|
||||
def get_client_ip(request):
|
||||
xff = request.META.get('HTTP_X_FORWARDED_FOR')
|
||||
if xff:
|
||||
|
||||
+73
-20
@@ -10,8 +10,11 @@ from drf_spectacular.utils import extend_schema, inline_serializer
|
||||
|
||||
from config.exceptions import AppError
|
||||
from apps.user.models import User
|
||||
from apps.user.audit import log_login_success, log_login_fail
|
||||
from apps.user.auth import get_tokens_for_user, build_user_response, get_client_ip, get_user_agent
|
||||
from apps.user.audit import log_login_success, log_login_fail, log_register
|
||||
from apps.user.auth import (
|
||||
get_tokens_for_user, build_user_response, get_client_ip, get_user_agent,
|
||||
resolve_or_create_institution,
|
||||
)
|
||||
|
||||
LOGIN_FAIL_MAX = 5
|
||||
LOGIN_FAIL_LOCK_SECONDS = 15 * 60 # 15 分钟
|
||||
@@ -89,24 +92,40 @@ def login_password(request):
|
||||
})
|
||||
|
||||
|
||||
# ── U4 验证码登录 ────────────────────────────────────────────────────────────
|
||||
# ── U4 验证码登录(自动注册)────────────────────────────────────────────────
|
||||
|
||||
_LOGIN_CODE_RESPONSE = inline_serializer('LoginCodeResponse', fields={
|
||||
'message': drf_serializers.CharField(),
|
||||
'user': drf_serializers.DictField(help_text='用户基本信息'),
|
||||
'tokens': drf_serializers.DictField(help_text='access + refresh'),
|
||||
'is_new_user': drf_serializers.BooleanField(help_text='是否为新注册用户'),
|
||||
})
|
||||
|
||||
|
||||
@extend_schema(
|
||||
summary='U4 验证码登录',
|
||||
summary='U4 验证码登录(未注册自动注册)',
|
||||
description='前端一键登录/注册:验证码校验通过后,若手机号未注册则自动创建账号(角色=student,无密码)。'
|
||||
'机构不存在会自动创建。',
|
||||
request=inline_serializer('LoginCodeRequest', fields={
|
||||
'phone': drf_serializers.CharField(help_text='手机号'),
|
||||
'code': drf_serializers.CharField(help_text='6 位短信验证码'),
|
||||
'institution_code': drf_serializers.CharField(help_text='机构编码(必填,唯一标识)'),
|
||||
'institution_name': drf_serializers.CharField(help_text='机构名称(必填)'),
|
||||
}),
|
||||
responses={200: _LOGIN_RESPONSE},
|
||||
responses={200: _LOGIN_CODE_RESPONSE, 201: _LOGIN_CODE_RESPONSE},
|
||||
tags=['认证'],
|
||||
)
|
||||
@api_view(['POST'])
|
||||
@permission_classes([AllowAny])
|
||||
def login_code(request):
|
||||
"""U4 验证码登录"""
|
||||
"""U4 验证码登录 — 未注册用户自动注册"""
|
||||
data = request.data
|
||||
phone = str(data.get('phone', ''))
|
||||
code = str(data.get('code', ''))
|
||||
institution_code = str(data.get('institution_code', '')).strip()
|
||||
institution_name = str(data.get('institution_name', '')).strip()
|
||||
|
||||
# ── 入参校验 ──────────────────────────────────────────────────────────────
|
||||
|
||||
if not re.match(r'^1[3-9]\d{9}$', phone):
|
||||
raise AppError('SMS_INVALID_PHONE', '手机号格式不合法')
|
||||
@@ -114,16 +133,14 @@ def login_code(request):
|
||||
if not code:
|
||||
raise AppError('AUTH_CODE_INVALID', '请输入验证码')
|
||||
|
||||
# 查找用户
|
||||
try:
|
||||
user = User.objects.select_related('institution', 'department').get(phone=phone)
|
||||
except User.DoesNotExist:
|
||||
raise AppError('AUTH_PHONE_NOT_FOUND', '手机号未注册')
|
||||
if not institution_code:
|
||||
raise AppError('USER_INSTITUTION_CODE_REQUIRED', '机构编码不能为空')
|
||||
|
||||
if user.status == 0:
|
||||
raise AppError('AUTH_ACCOUNT_DISABLED', '账号已被禁用,请联系管理员', status_code=403)
|
||||
if not institution_name:
|
||||
raise AppError('USER_INSTITUTION_REQUIRED', '机构名称不能为空')
|
||||
|
||||
# ── 校验验证码(先校验再查用户,避免未注册用户也暴露手机号状态)───────────
|
||||
|
||||
# 校验验证码
|
||||
cache_key = f'sms:login:{phone}'
|
||||
cached_code = cache.get(cache_key)
|
||||
if not cached_code:
|
||||
@@ -131,20 +148,56 @@ def login_code(request):
|
||||
if str(cached_code) != code:
|
||||
raise AppError('AUTH_CODE_MISMATCH', '验证码错误')
|
||||
|
||||
# 成功:清理验证码 + 清理密码失败计数
|
||||
# 验证码一次性使用
|
||||
cache.delete(cache_key)
|
||||
cache.delete(f'login_fail:{phone}')
|
||||
|
||||
user.last_login_time = timezone.now()
|
||||
user.save(update_fields=['last_login_time'])
|
||||
# ── 解析 / 创建机构 ──────────────────────────────────────────────────────
|
||||
|
||||
institution = resolve_or_create_institution(institution_code, institution_name)
|
||||
|
||||
# ── 查找用户 or 自动注册 ────────────────────────────────────────────────
|
||||
|
||||
tokens = get_tokens_for_user(user)
|
||||
ip = get_client_ip(request)
|
||||
ua = get_user_agent(request)
|
||||
|
||||
from django.db import IntegrityError
|
||||
|
||||
try:
|
||||
user = User.objects.select_related('institution', 'department').get(phone=phone)
|
||||
is_new = False
|
||||
except User.DoesNotExist:
|
||||
try:
|
||||
user = User.objects.create_user(
|
||||
username=phone,
|
||||
password=None,
|
||||
phone=phone,
|
||||
role_type='student',
|
||||
institution=institution,
|
||||
status=1,
|
||||
)
|
||||
is_new = True
|
||||
except IntegrityError:
|
||||
user = User.objects.select_related('institution', 'department').get(phone=phone)
|
||||
is_new = False
|
||||
|
||||
if is_new:
|
||||
log_register(user.id, phone)
|
||||
else:
|
||||
if user.status == 0:
|
||||
raise AppError('AUTH_ACCOUNT_DISABLED', '账号已被禁用,请联系管理员', status_code=403)
|
||||
if user.institution_id != institution.id:
|
||||
user.institution = institution
|
||||
|
||||
user.last_login_time = timezone.now()
|
||||
user.save(update_fields=['institution', 'last_login_time'])
|
||||
|
||||
tokens = get_tokens_for_user(user)
|
||||
log_login_success(user.id, phone, ip=ip, ua=ua)
|
||||
|
||||
return Response({
|
||||
'message': '登录成功',
|
||||
'message': '注册并登录成功' if is_new else '登录成功',
|
||||
'user': build_user_response(user),
|
||||
'tokens': tokens,
|
||||
})
|
||||
'is_new_user': is_new,
|
||||
}, status=201 if is_new else 200)
|
||||
|
||||
+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)
|
||||
|
||||
|
||||
@@ -44,7 +44,8 @@ def send_code(request):
|
||||
user_exists = User.objects.filter(phone=phone).exists()
|
||||
if scene == 'register' and user_exists:
|
||||
raise AppError('AUTH_PHONE_REGISTERED', '该手机号已注册')
|
||||
if scene in ('login', 'reset') and not user_exists:
|
||||
# scene='login':不检查是否已注册(未注册用户通过 login-code 自动注册)
|
||||
if scene == 'reset' and not user_exists:
|
||||
raise AppError('AUTH_PHONE_NOT_FOUND', '手机号未注册')
|
||||
|
||||
code = generate_sms_code()
|
||||
|
||||
Reference in New Issue
Block a user