feat: update medical training case and auth modules
This commit is contained in:
+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)
|
||||
|
||||
Reference in New Issue
Block a user