Files
medical_training/apps/user/auth/login.py
T
2026-06-05 15:36:31 +08:00

230 lines
9.9 KiB
Python

import re
from django.core.cache import cache
from django.db.models import Q
from django.utils import timezone
from rest_framework.decorators import api_view, permission_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
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,
CMS_ROLE_TYPES, TRIAL_INSTITUTION_NAME,
)
LOGIN_FAIL_MAX = 5
LOGIN_FAIL_LOCK_SECONDS = 15 * 60 # 15 分钟
_LOGIN_RESPONSE = inline_serializer('LoginResponse', fields={
'message': drf_serializers.CharField(),
'user': drf_serializers.DictField(help_text='用户基本信息'),
'tokens': drf_serializers.DictField(help_text='access + refresh'),
})
# ── U3 密码登录 ──────────────────────────────────────────────────────────────
@extend_schema(
summary='U3 密码登录(CMS 端)',
description='CMS 端登录:用户名或手机号 + 密码 + 角色,三者必填。角色须为 '
'super_admin / hospital_admin / content_admin / doctor 之一,且与账号实际角色一致。',
request=inline_serializer('LoginPasswordRequest', fields={
'account': drf_serializers.CharField(help_text='用户名或手机号'),
'password': drf_serializers.CharField(help_text='密码'),
'role': drf_serializers.ChoiceField(
choices=list(CMS_ROLE_TYPES),
help_text='角色:super_admin/hospital_admin/content_admin/doctor'),
}),
responses={200: _LOGIN_RESPONSE},
tags=['认证'],
)
@api_view(['POST'])
@permission_classes([AllowAny])
def login_password(request):
"""U3 密码登录(CMS 端:用户名/手机号 + 密码 + 角色)"""
data = request.data
account = str(data.get('account', '')).strip()
password = str(data.get('password', ''))
role = str(data.get('role', '')).strip()
if not account or not password or not role:
raise AppError('AUTH_BAD_CREDENTIALS', '用户名、密码、角色不能为空')
if role not in CMS_ROLE_TYPES:
raise AppError('AUTH_INVALID_ROLE',
'角色无效,仅允许 super_admin / hospital_admin / content_admin / doctor')
ip = get_client_ip(request)
ua = get_user_agent(request)
# 检查账号锁定
fail_key = f'login_fail:{account}'
fail_count = cache.get(fail_key)
if fail_count is not None and int(fail_count) >= LOGIN_FAIL_MAX:
raise AppError('AUTH_ACCOUNT_LOCKED', '登录失败次数过多,请 15 分钟后再试', status_code=423)
# 查找用户(用户名或手机号;不区分"未注册"和"密码错",防用户名枚举)
try:
user = User.objects.select_related('institution', 'department').get(
Q(username=account) | Q(phone=account)
)
except User.DoesNotExist:
log_login_fail(account, ip=ip, reason='account_not_found')
raise AppError('AUTH_BAD_CREDENTIALS', '账号、密码或角色错误')
# 账号禁用检查
if user.status == 0:
log_login_fail(account, ip=ip, reason='account_disabled')
raise AppError('AUTH_ACCOUNT_DISABLED', '账号已被禁用,请联系管理员', status_code=403)
# 校验密码 + 角色(角色不一致同样返回通用错误,避免暴露真实角色)
if not user.check_password(password) or user.role_type != role:
current = cache.get(fail_key)
new_count = (int(current) + 1) if current is not None else 1
cache.set(fail_key, new_count, timeout=LOGIN_FAIL_LOCK_SECONDS)
reason = 'wrong_password' if user.role_type == role else 'role_mismatch'
log_login_fail(account, ip=ip, reason=reason)
raise AppError('AUTH_BAD_CREDENTIALS', '账号、密码或角色错误')
# 登录成功
cache.delete(fail_key)
user.last_login_time = timezone.now()
user.save(update_fields=['last_login_time'])
tokens = get_tokens_for_user(user)
log_login_success(user.id, user.phone, ip=ip, ua=ua)
return Response({
'message': '登录成功',
'user': build_user_response(user),
'tokens': tokens,
})
# ── 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 验证码登录(移动端)',
description='移动端学生登录:手机号 + 验证码 + 所选机构编码。'
f'仅当所选机构为试用机构({TRIAL_INSTITUTION_NAME})时,未注册手机号首次即自动注册(角色=student);'
'其它机构必须由 CMS 先录入学生,且所选机构需与录入机构一致,否则拒绝登录。机构不会自动创建。',
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='机构编码(来自机构列表接口,必填)'),
}),
responses={200: _LOGIN_CODE_RESPONSE, 201: _LOGIN_CODE_RESPONSE},
tags=['认证'],
)
@api_view(['POST'])
@permission_classes([AllowAny])
def login_code(request):
"""U4 验证码登录(移动端:仅试用机构可自动注册)"""
data = request.data
phone = str(data.get('phone', ''))
code = str(data.get('code', ''))
institution_code = str(data.get('institution_code', '')).strip()
# ── 入参校验 ──────────────────────────────────────────────────────────────
if not re.match(r'^1[3-9]\d{9}$', phone):
raise AppError('SMS_INVALID_PHONE', '手机号格式不合法')
if not code:
raise AppError('AUTH_CODE_INVALID', '请输入验证码')
if not institution_code:
raise AppError('USER_INSTITUTION_CODE_REQUIRED', '机构编码不能为空')
# ── 校验验证码(先校验再查用户,避免未注册用户也暴露手机号状态)───────────
cache_key = f'sms:login:{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', '验证码错误')
# 验证码一次性使用
cache.delete(cache_key)
cache.delete(f'login_fail:{phone}')
# ── 解析机构(仅按编码查询,不创建)──────────────────────────────────────
try:
institution = Institution.objects.get(code=institution_code)
except Institution.DoesNotExist:
raise AppError('USER_INSTITUTION_NOT_FOUND', '机构不存在,请重新选择')
is_trial = institution.name == TRIAL_INSTITUTION_NAME
# ── 查找用户 ──────────────────────────────────────────────────────────────
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:
user = None
is_new = False
if user is None:
# 仅试用机构允许首次自动注册;其它机构必须先由 CMS 录入
if not is_trial:
raise AppError('AUTH_NOT_REGISTERED', '账号未录入,请联系管理员', status_code=403)
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 not is_trial:
# 移动端只有学生;非试用机构需校验角色与所选机构一致(不暴露 CMS 账号是否存在)
if user.role_type != 'student':
raise AppError('AUTH_NOT_REGISTERED', '账号未录入,请联系管理员', status_code=403)
if user.institution_id != institution.id:
raise AppError('AUTH_INSTITUTION_MISMATCH', '所选机构与账号不匹配', status_code=403)
user.last_login_time = timezone.now()
user.save(update_fields=['last_login_time'])
tokens = get_tokens_for_user(user)
log_login_success(user.id, phone, ip=ip, ua=ua)
return Response({
'message': '注册并登录成功' if is_new else '登录成功',
'user': build_user_response(user),
'tokens': tokens,
'is_new_user': is_new,
}, status=201 if is_new else 200)