2026-05-29 15:58:00 +08:00
|
|
|
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
|
2026-06-03 17:34:47 +08:00
|
|
|
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,
|
|
|
|
|
)
|
2026-05-29 15:58:00 +08:00
|
|
|
|
|
|
|
|
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,
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
|
2026-06-03 17:34:47 +08:00
|
|
|
# ── 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='是否为新注册用户'),
|
|
|
|
|
})
|
|
|
|
|
|
2026-05-29 15:58:00 +08:00
|
|
|
|
|
|
|
|
@extend_schema(
|
2026-06-03 17:34:47 +08:00
|
|
|
summary='U4 验证码登录(未注册自动注册)',
|
|
|
|
|
description='前端一键登录/注册:验证码校验通过后,若手机号未注册则自动创建账号(角色=student,无密码)。'
|
|
|
|
|
'机构不存在会自动创建。',
|
2026-05-29 15:58:00 +08:00
|
|
|
request=inline_serializer('LoginCodeRequest', fields={
|
|
|
|
|
'phone': drf_serializers.CharField(help_text='手机号'),
|
|
|
|
|
'code': drf_serializers.CharField(help_text='6 位短信验证码'),
|
2026-06-03 17:34:47 +08:00
|
|
|
'institution_code': drf_serializers.CharField(help_text='机构编码(必填,唯一标识)'),
|
|
|
|
|
'institution_name': drf_serializers.CharField(help_text='机构名称(必填)'),
|
2026-05-29 15:58:00 +08:00
|
|
|
}),
|
2026-06-03 17:34:47 +08:00
|
|
|
responses={200: _LOGIN_CODE_RESPONSE, 201: _LOGIN_CODE_RESPONSE},
|
2026-05-29 15:58:00 +08:00
|
|
|
tags=['认证'],
|
|
|
|
|
)
|
|
|
|
|
@api_view(['POST'])
|
|
|
|
|
@permission_classes([AllowAny])
|
|
|
|
|
def login_code(request):
|
2026-06-03 17:34:47 +08:00
|
|
|
"""U4 验证码登录 — 未注册用户自动注册"""
|
2026-05-29 15:58:00 +08:00
|
|
|
data = request.data
|
|
|
|
|
phone = str(data.get('phone', ''))
|
|
|
|
|
code = str(data.get('code', ''))
|
2026-06-03 17:34:47 +08:00
|
|
|
institution_code = str(data.get('institution_code', '')).strip()
|
|
|
|
|
institution_name = str(data.get('institution_name', '')).strip()
|
|
|
|
|
|
|
|
|
|
# ── 入参校验 ──────────────────────────────────────────────────────────────
|
2026-05-29 15:58:00 +08:00
|
|
|
|
|
|
|
|
if not re.match(r'^1[3-9]\d{9}$', phone):
|
|
|
|
|
raise AppError('SMS_INVALID_PHONE', '手机号格式不合法')
|
|
|
|
|
|
|
|
|
|
if not code:
|
|
|
|
|
raise AppError('AUTH_CODE_INVALID', '请输入验证码')
|
|
|
|
|
|
2026-06-03 17:34:47 +08:00
|
|
|
if not institution_code:
|
|
|
|
|
raise AppError('USER_INSTITUTION_CODE_REQUIRED', '机构编码不能为空')
|
2026-05-29 15:58:00 +08:00
|
|
|
|
2026-06-03 17:34:47 +08:00
|
|
|
if not institution_name:
|
|
|
|
|
raise AppError('USER_INSTITUTION_REQUIRED', '机构名称不能为空')
|
|
|
|
|
|
|
|
|
|
# ── 校验验证码(先校验再查用户,避免未注册用户也暴露手机号状态)───────────
|
2026-05-29 15:58:00 +08:00
|
|
|
|
|
|
|
|
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', '验证码错误')
|
|
|
|
|
|
2026-06-03 17:34:47 +08:00
|
|
|
# 验证码一次性使用
|
2026-05-29 15:58:00 +08:00
|
|
|
cache.delete(cache_key)
|
|
|
|
|
cache.delete(f'login_fail:{phone}')
|
|
|
|
|
|
2026-06-03 17:34:47 +08:00
|
|
|
# ── 解析 / 创建机构 ──────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
institution = resolve_or_create_institution(institution_code, institution_name)
|
|
|
|
|
|
|
|
|
|
# ── 查找用户 or 自动注册 ────────────────────────────────────────────────
|
2026-05-29 15:58:00 +08:00
|
|
|
|
|
|
|
|
ip = get_client_ip(request)
|
|
|
|
|
ua = get_user_agent(request)
|
2026-06-03 17:34:47 +08:00
|
|
|
|
|
|
|
|
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)
|
2026-05-29 15:58:00 +08:00
|
|
|
log_login_success(user.id, phone, ip=ip, ua=ua)
|
|
|
|
|
|
|
|
|
|
return Response({
|
2026-06-03 17:34:47 +08:00
|
|
|
'message': '注册并登录成功' if is_new else '登录成功',
|
2026-05-29 15:58:00 +08:00
|
|
|
'user': build_user_response(user),
|
|
|
|
|
'tokens': tokens,
|
2026-06-03 17:34:47 +08:00
|
|
|
'is_new_user': is_new,
|
|
|
|
|
}, status=201 if is_new else 200)
|