init medical training project
This commit is contained in:
@@ -0,0 +1,150 @@
|
||||
import re
|
||||
|
||||
from django.core.cache import cache
|
||||
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
|
||||
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
|
||||
|
||||
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 密码登录',
|
||||
request=inline_serializer('LoginPasswordRequest', fields={
|
||||
'phone': drf_serializers.CharField(help_text='手机号'),
|
||||
'password': drf_serializers.CharField(help_text='密码'),
|
||||
}),
|
||||
responses={200: _LOGIN_RESPONSE},
|
||||
tags=['认证'],
|
||||
)
|
||||
@api_view(['POST'])
|
||||
@permission_classes([AllowAny])
|
||||
def login_password(request):
|
||||
"""U3 密码登录"""
|
||||
data = request.data
|
||||
phone = str(data.get('phone', ''))
|
||||
password = str(data.get('password', ''))
|
||||
|
||||
if not phone or not password:
|
||||
raise AppError('AUTH_BAD_CREDENTIALS', '手机号和密码不能为空')
|
||||
|
||||
ip = get_client_ip(request)
|
||||
ua = get_user_agent(request)
|
||||
|
||||
# 检查账号锁定
|
||||
fail_key = f'login_fail:{phone}'
|
||||
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)
|
||||
except User.DoesNotExist:
|
||||
log_login_fail(phone, ip=ip, reason='phone_not_found')
|
||||
raise AppError('AUTH_BAD_CREDENTIALS', '手机号或密码错误')
|
||||
|
||||
# 账号禁用检查
|
||||
if user.status == 0:
|
||||
log_login_fail(phone, ip=ip, reason='account_disabled')
|
||||
raise AppError('AUTH_ACCOUNT_DISABLED', '账号已被禁用,请联系管理员', status_code=403)
|
||||
|
||||
# 校验密码
|
||||
if not user.check_password(password):
|
||||
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', '手机号或密码错误')
|
||||
|
||||
# 登录成功
|
||||
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, phone, ip=ip, ua=ua)
|
||||
|
||||
return Response({
|
||||
'message': '登录成功',
|
||||
'user': build_user_response(user),
|
||||
'tokens': tokens,
|
||||
})
|
||||
|
||||
|
||||
# ── U4 验证码登录 ────────────────────────────────────────────────────────────
|
||||
|
||||
@extend_schema(
|
||||
summary='U4 验证码登录',
|
||||
request=inline_serializer('LoginCodeRequest', fields={
|
||||
'phone': drf_serializers.CharField(help_text='手机号'),
|
||||
'code': drf_serializers.CharField(help_text='6 位短信验证码'),
|
||||
}),
|
||||
responses={200: _LOGIN_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', ''))
|
||||
|
||||
if not re.match(r'^1[3-9]\d{9}$', phone):
|
||||
raise AppError('SMS_INVALID_PHONE', '手机号格式不合法')
|
||||
|
||||
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 user.status == 0:
|
||||
raise AppError('AUTH_ACCOUNT_DISABLED', '账号已被禁用,请联系管理员', status_code=403)
|
||||
|
||||
# 校验验证码
|
||||
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}')
|
||||
|
||||
user.last_login_time = timezone.now()
|
||||
user.save(update_fields=['last_login_time'])
|
||||
|
||||
tokens = get_tokens_for_user(user)
|
||||
ip = get_client_ip(request)
|
||||
ua = get_user_agent(request)
|
||||
log_login_success(user.id, phone, ip=ip, ua=ua)
|
||||
|
||||
return Response({
|
||||
'message': '登录成功',
|
||||
'user': build_user_response(user),
|
||||
'tokens': tokens,
|
||||
})
|
||||
Reference in New Issue
Block a user