feat: update login api
This commit is contained in:
+61
-35
@@ -1,6 +1,7 @@
|
||||
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
|
||||
@@ -9,11 +10,11 @@ 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
|
||||
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,
|
||||
resolve_or_create_institution,
|
||||
CMS_ROLE_TYPES, TRIAL_INSTITUTION_NAME,
|
||||
)
|
||||
|
||||
LOGIN_FAIL_MAX = 5
|
||||
@@ -29,10 +30,15 @@ _LOGIN_RESPONSE = inline_serializer('LoginResponse', fields={
|
||||
# ── U3 密码登录 ──────────────────────────────────────────────────────────────
|
||||
|
||||
@extend_schema(
|
||||
summary='U3 密码登录',
|
||||
summary='U3 密码登录(CMS 端)',
|
||||
description='CMS 端登录:用户名或手机号 + 密码 + 角色,三者必填。角色须为 '
|
||||
'super_admin / hospital_admin / content_admin / doctor 之一,且与账号实际角色一致。',
|
||||
request=inline_serializer('LoginPasswordRequest', fields={
|
||||
'phone': drf_serializers.CharField(help_text='手机号'),
|
||||
'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=['认证'],
|
||||
@@ -40,42 +46,50 @@ _LOGIN_RESPONSE = inline_serializer('LoginResponse', fields={
|
||||
@api_view(['POST'])
|
||||
@permission_classes([AllowAny])
|
||||
def login_password(request):
|
||||
"""U3 密码登录"""
|
||||
"""U3 密码登录(CMS 端:用户名/手机号 + 密码 + 角色)"""
|
||||
data = request.data
|
||||
phone = str(data.get('phone', ''))
|
||||
account = str(data.get('account', '')).strip()
|
||||
password = str(data.get('password', ''))
|
||||
role = str(data.get('role', '')).strip()
|
||||
|
||||
if not phone or not password:
|
||||
raise AppError('AUTH_BAD_CREDENTIALS', '手机号和密码不能为空')
|
||||
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:{phone}'
|
||||
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(phone=phone)
|
||||
user = User.objects.select_related('institution', 'department').get(
|
||||
Q(username=account) | Q(phone=account)
|
||||
)
|
||||
except User.DoesNotExist:
|
||||
log_login_fail(phone, ip=ip, reason='phone_not_found')
|
||||
raise AppError('AUTH_BAD_CREDENTIALS', '手机号或密码错误')
|
||||
log_login_fail(account, ip=ip, reason='account_not_found')
|
||||
raise AppError('AUTH_BAD_CREDENTIALS', '账号、密码或角色错误')
|
||||
|
||||
# 账号禁用检查
|
||||
if user.status == 0:
|
||||
log_login_fail(phone, ip=ip, reason='account_disabled')
|
||||
log_login_fail(account, ip=ip, reason='account_disabled')
|
||||
raise AppError('AUTH_ACCOUNT_DISABLED', '账号已被禁用,请联系管理员', status_code=403)
|
||||
|
||||
# 校验密码
|
||||
if not user.check_password(password):
|
||||
# 校验密码 + 角色(角色不一致同样返回通用错误,避免暴露真实角色)
|
||||
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)
|
||||
log_login_fail(phone, ip=ip, reason='wrong_password')
|
||||
raise AppError('AUTH_BAD_CREDENTIALS', '手机号或密码错误')
|
||||
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)
|
||||
@@ -83,7 +97,7 @@ def login_password(request):
|
||||
user.save(update_fields=['last_login_time'])
|
||||
|
||||
tokens = get_tokens_for_user(user)
|
||||
log_login_success(user.id, phone, ip=ip, ua=ua)
|
||||
log_login_success(user.id, user.phone, ip=ip, ua=ua)
|
||||
|
||||
return Response({
|
||||
'message': '登录成功',
|
||||
@@ -103,14 +117,14 @@ _LOGIN_CODE_RESPONSE = inline_serializer('LoginCodeResponse', fields={
|
||||
|
||||
|
||||
@extend_schema(
|
||||
summary='U4 验证码登录(未注册自动注册)',
|
||||
description='前端一键登录/注册:验证码校验通过后,若手机号未注册则自动创建账号(角色=student,无密码)。'
|
||||
'机构不存在会自动创建。',
|
||||
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='机构编码(必填,唯一标识)'),
|
||||
'institution_name': drf_serializers.CharField(help_text='机构名称(必填)'),
|
||||
'institution_code': drf_serializers.CharField(help_text='机构编码(来自机构列表接口,必填)'),
|
||||
}),
|
||||
responses={200: _LOGIN_CODE_RESPONSE, 201: _LOGIN_CODE_RESPONSE},
|
||||
tags=['认证'],
|
||||
@@ -118,12 +132,11 @@ _LOGIN_CODE_RESPONSE = inline_serializer('LoginCodeResponse', fields={
|
||||
@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()
|
||||
|
||||
# ── 入参校验 ──────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -136,9 +149,6 @@ def login_code(request):
|
||||
if not institution_code:
|
||||
raise AppError('USER_INSTITUTION_CODE_REQUIRED', '机构编码不能为空')
|
||||
|
||||
if not institution_name:
|
||||
raise AppError('USER_INSTITUTION_REQUIRED', '机构名称不能为空')
|
||||
|
||||
# ── 校验验证码(先校验再查用户,避免未注册用户也暴露手机号状态)───────────
|
||||
|
||||
cache_key = f'sms:login:{phone}'
|
||||
@@ -152,11 +162,16 @@ def login_code(request):
|
||||
cache.delete(cache_key)
|
||||
cache.delete(f'login_fail:{phone}')
|
||||
|
||||
# ── 解析 / 创建机构 ──────────────────────────────────────────────────────
|
||||
# ── 解析机构(仅按编码查询,不创建)──────────────────────────────────────
|
||||
|
||||
institution = resolve_or_create_institution(institution_code, institution_name)
|
||||
try:
|
||||
institution = Institution.objects.get(code=institution_code)
|
||||
except Institution.DoesNotExist:
|
||||
raise AppError('USER_INSTITUTION_NOT_FOUND', '机构不存在,请重新选择')
|
||||
|
||||
# ── 查找用户 or 自动注册 ────────────────────────────────────────────────
|
||||
is_trial = institution.name == TRIAL_INSTITUTION_NAME
|
||||
|
||||
# ── 查找用户 ──────────────────────────────────────────────────────────────
|
||||
|
||||
ip = get_client_ip(request)
|
||||
ua = get_user_agent(request)
|
||||
@@ -167,6 +182,13 @@ def login_code(request):
|
||||
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,
|
||||
@@ -186,11 +208,15 @@ def login_code(request):
|
||||
else:
|
||||
if user.status == 0:
|
||||
raise AppError('AUTH_ACCOUNT_DISABLED', '账号已被禁用,请联系管理员', status_code=403)
|
||||
if user.institution_id != institution.id:
|
||||
user.institution = institution
|
||||
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=['institution', 'last_login_time'])
|
||||
user.save(update_fields=['last_login_time'])
|
||||
|
||||
tokens = get_tokens_for_user(user)
|
||||
log_login_success(user.id, phone, ip=ip, ua=ua)
|
||||
|
||||
Reference in New Issue
Block a user