feat: update login api
This commit is contained in:
@@ -4,6 +4,21 @@ from config.exceptions import AppError
|
||||
|
||||
ALLOWED_ROLE_TYPES = ('student', 'doctor', 'teacher')
|
||||
|
||||
# CMS 端可登录的角色(U3 密码登录):超级管理员 / 医院管理员 / 内容管理员 / 医生(带教老师)
|
||||
CMS_ROLE_TYPES = ('super_admin', 'hospital_admin', 'content_admin', 'doctor')
|
||||
|
||||
# U2 代注册:仅以下角色可代注册
|
||||
REGISTER_ADMIN_ROLES = ('super_admin', 'hospital_admin')
|
||||
# 各管理员可代注册创建的目标角色(超管可建所有角色;医院管理员可建内容管理员/医生/学生)
|
||||
REGISTERABLE_ROLES = {
|
||||
'super_admin': ('super_admin', 'hospital_admin', 'content_admin', 'doctor', 'student'),
|
||||
'hospital_admin': ('content_admin', 'doctor', 'student'),
|
||||
}
|
||||
|
||||
# 预留试用机构:移动端选择该机构时手机号+验证码首次即注册、后续即登录。识别以名称为准。
|
||||
TRIAL_INSTITUTION_NAME = '北大医学部(实验室)试用'
|
||||
TRIAL_INSTITUTION_CODE = 'PKU_LAB_TRIAL'
|
||||
|
||||
|
||||
def get_tokens_for_user(user):
|
||||
refresh = RefreshToken.for_user(user)
|
||||
|
||||
+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)
|
||||
|
||||
+40
-22
@@ -3,17 +3,18 @@ import re
|
||||
from django.db import transaction, IntegrityError
|
||||
from rest_framework import status
|
||||
from rest_framework.decorators import api_view, permission_classes, throttle_classes
|
||||
from rest_framework.permissions import AllowAny
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
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, Department
|
||||
from apps.user.permissions import IsRegisterPermitted
|
||||
from apps.user.throttling import RegisterIpThrottle
|
||||
from apps.user.audit import log_register
|
||||
from apps.user.auth import (
|
||||
get_tokens_for_user, build_user_response, ALLOWED_ROLE_TYPES,
|
||||
build_user_response, REGISTERABLE_ROLES,
|
||||
resolve_or_create_institution,
|
||||
)
|
||||
|
||||
@@ -22,30 +23,33 @@ DEFAULT_PASSWORD_PREFIX = 'Pass'
|
||||
|
||||
@extend_schema(
|
||||
summary='U2 管理员代注册',
|
||||
description='CMS 管理员为他人注册账号,无需验证码。默认密码为 Pass+手机号(如 Pass13800001001),用户可自行修改。'
|
||||
'机构不存在会自动创建。',
|
||||
description='CMS 管理员为他人注册账号,无需验证码。**仅超级管理员 / 医院管理员可调用**:'
|
||||
'超级管理员可创建所有角色、可指定或新建任意机构;'
|
||||
'医院管理员可创建内容管理员 / 医生 / 学生,且**只能在本机构内**建账号。'
|
||||
'默认密码为 Pass+手机号(如 Pass13800001001),用户可自行修改。'
|
||||
'**不返回 tokens**,新用户需自行登录(CMS 用 U3、移动端学生用 U4)。',
|
||||
request=inline_serializer('RegisterRequest', fields={
|
||||
'phone': drf_serializers.CharField(help_text='手机号'),
|
||||
'real_name': drf_serializers.CharField(help_text='真实姓名'),
|
||||
'role_type': drf_serializers.ChoiceField(
|
||||
choices=['student', 'doctor', 'teacher'],
|
||||
required=False, default='student', help_text='角色类型'),
|
||||
'institution_code': drf_serializers.CharField(help_text='机构编码(必填,唯一标识)'),
|
||||
'institution_name': drf_serializers.CharField(help_text='机构名称(必填)'),
|
||||
choices=['student', 'doctor', 'content_admin', 'hospital_admin', 'super_admin'],
|
||||
required=False, default='student', help_text='角色类型(受调用者角色限制)'),
|
||||
'institution_code': drf_serializers.CharField(
|
||||
help_text='机构编码(超管必填;医院管理员可省略,默认本机构,若填须与本机构一致)'),
|
||||
'institution_name': drf_serializers.CharField(help_text='机构名称(超管新建机构时必填)'),
|
||||
'department_name': drf_serializers.CharField(required=False, help_text='科室名称'),
|
||||
}),
|
||||
responses={201: inline_serializer('RegisterResponse', fields={
|
||||
'message': drf_serializers.CharField(),
|
||||
'user': drf_serializers.DictField(help_text='用户基本信息'),
|
||||
'tokens': drf_serializers.DictField(help_text='access + refresh'),
|
||||
})},
|
||||
tags=['认证'],
|
||||
)
|
||||
@api_view(['POST'])
|
||||
@permission_classes([AllowAny]) # TODO: 上线前改为管理员权限
|
||||
@permission_classes([IsAuthenticated, IsRegisterPermitted])
|
||||
@throttle_classes([RegisterIpThrottle])
|
||||
def register(request):
|
||||
"""U2 管理员代注册(手机号 + 密码,无需验证码)"""
|
||||
"""U2 管理员代注册(仅超级管理员 / 医院管理员,无需验证码)"""
|
||||
data = request.data
|
||||
|
||||
phone = str(data.get('phone', ''))
|
||||
@@ -63,20 +67,36 @@ def register(request):
|
||||
if not real_name or len(real_name) < 2 or len(real_name) > 20:
|
||||
raise AppError('USER_INVALID_NAME', '姓名长度应在 2-20 字符之间')
|
||||
|
||||
if role_type not in ALLOWED_ROLE_TYPES:
|
||||
raise AppError('AUTH_INVALID_ROLE', '角色类型无效,仅允许 student / doctor / teacher')
|
||||
actor = request.user
|
||||
|
||||
if not institution_code:
|
||||
raise AppError('USER_INSTITUTION_CODE_REQUIRED', '机构编码不能为空')
|
||||
|
||||
if not institution_name:
|
||||
raise AppError('USER_INSTITUTION_REQUIRED', '机构名称不能为空')
|
||||
# 目标角色须在调用者可创建的范围内(超管可建全部;医院管理员仅内容管理员/医生/学生)
|
||||
allowed_roles = REGISTERABLE_ROLES.get(actor.role_type, ())
|
||||
if role_type not in allowed_roles:
|
||||
raise AppError('USER_NO_REGISTER_ROLE_PERMISSION',
|
||||
'您无权创建该角色账号', status_code=403)
|
||||
|
||||
password = f'{DEFAULT_PASSWORD_PREFIX}{phone}'
|
||||
|
||||
# ── 机构 / 科室解析 ──────────────────────────────────────────────────────
|
||||
# ── 机构解析:超管任意;医院管理员仅限本机构 ─────────────────────────────
|
||||
|
||||
institution = resolve_or_create_institution(institution_code, institution_name)
|
||||
if actor.role_type == 'hospital_admin':
|
||||
if not actor.institution_id:
|
||||
raise AppError('USER_NO_REGISTER_INSTITUTION',
|
||||
'您未归属任何机构,无法代注册', status_code=403)
|
||||
institution = actor.institution
|
||||
# 若显式指定机构且与本机构不一致 → 拒绝(医院管理员不能跨机构建账号)
|
||||
if institution_code and institution_code != institution.code:
|
||||
raise AppError('USER_INSTITUTION_SCOPE_FORBIDDEN',
|
||||
'医院管理员只能在本机构内建账号', status_code=403)
|
||||
else:
|
||||
# super_admin:机构编码 + 名称必填,按 code 查找或新建
|
||||
if not institution_code:
|
||||
raise AppError('USER_INSTITUTION_CODE_REQUIRED', '机构编码不能为空')
|
||||
if not institution_name:
|
||||
raise AppError('USER_INSTITUTION_REQUIRED', '机构名称不能为空')
|
||||
institution = resolve_or_create_institution(institution_code, institution_name)
|
||||
|
||||
# ── 科室解析(可选)──────────────────────────────────────────────────────
|
||||
|
||||
department = None
|
||||
if department_name:
|
||||
@@ -113,11 +133,9 @@ def register(request):
|
||||
|
||||
# ── 善后 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
tokens = get_tokens_for_user(user)
|
||||
log_register(user.id, phone)
|
||||
|
||||
return Response({
|
||||
'message': '注册成功',
|
||||
'user': build_user_response(user),
|
||||
'tokens': tokens,
|
||||
}, status=status.HTTP_201_CREATED)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
from django.core.management.base import BaseCommand
|
||||
|
||||
from apps.user.models import Institution
|
||||
from apps.user.auth import TRIAL_INSTITUTION_NAME, TRIAL_INSTITUTION_CODE
|
||||
|
||||
|
||||
class Command(BaseCommand):
|
||||
help = '初始化预留试用机构「北大医学部(实验室)试用」'
|
||||
|
||||
def handle(self, *args, **options):
|
||||
inst, created = Institution.objects.get_or_create(
|
||||
code=TRIAL_INSTITUTION_CODE,
|
||||
defaults={'name': TRIAL_INSTITUTION_NAME, 'type': 'hospital'},
|
||||
)
|
||||
|
||||
if created:
|
||||
self.stdout.write(self.style.SUCCESS(
|
||||
f'[创建] 试用机构: {inst.code} / {inst.name}'
|
||||
))
|
||||
elif inst.name != TRIAL_INSTITUTION_NAME:
|
||||
old_name = inst.name
|
||||
inst.name = TRIAL_INSTITUTION_NAME
|
||||
inst.save(update_fields=['name'])
|
||||
self.stdout.write(self.style.WARNING(
|
||||
f'[更新] 试用机构名称: {old_name} -> {inst.name}'
|
||||
))
|
||||
else:
|
||||
self.stdout.write(self.style.WARNING(
|
||||
f'[已存在] 试用机构: {inst.code} / {inst.name}'
|
||||
))
|
||||
@@ -73,15 +73,6 @@ class Command(BaseCommand):
|
||||
'training_stage': '规培',
|
||||
'learning_target': '掌握常见病诊断',
|
||||
},
|
||||
{
|
||||
'username': 'teacher1',
|
||||
'password': 'teacher123',
|
||||
'real_name': '王老师',
|
||||
'role_type': 'teacher',
|
||||
'phone': '13800138003',
|
||||
'title_name': '副主任医师',
|
||||
'major': '呼吸内科',
|
||||
},
|
||||
{
|
||||
'username': 'content_admin',
|
||||
'password': 'content123',
|
||||
|
||||
@@ -41,6 +41,17 @@ class IsUserDetailPermitted(BasePermission):
|
||||
raise AppError('USER_NO_VIEW_PERMISSION', '您没有查看该用户信息的权限', status_code=403)
|
||||
|
||||
|
||||
class IsRegisterPermitted(BasePermission):
|
||||
"""U2 代注册权限:仅超级管理员 / 医院管理员"""
|
||||
|
||||
def has_permission(self, request, view):
|
||||
user = request.user
|
||||
if user and user.is_authenticated and user.role_type in ('super_admin', 'hospital_admin'):
|
||||
return True
|
||||
raise AppError('USER_NO_REGISTER_PERMISSION',
|
||||
'仅超级管理员或医院管理员可代注册用户', status_code=403)
|
||||
|
||||
|
||||
class IsCaseOperationPermitted(BasePermission):
|
||||
"""病例操作权限:所有已登录用户均可操作"""
|
||||
|
||||
|
||||
@@ -17,6 +17,8 @@ router.register(r'departments', views.DepartmentViewSet, basename='department')
|
||||
|
||||
urlpatterns = [
|
||||
path('', include(router.urls)),
|
||||
# 移动端机构列表(不分页,登录前可调用)
|
||||
path('institution_list/', views.institution_list, name='institution-list'),
|
||||
# 认证相关
|
||||
path('auth/send-code/', send_code, name='send-code'),
|
||||
path('auth/register/', register, name='register'),
|
||||
|
||||
+34
-2
@@ -1,10 +1,12 @@
|
||||
from rest_framework import viewsets, filters, status
|
||||
from rest_framework.decorators import action
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.decorators import action, api_view, permission_classes
|
||||
from rest_framework.permissions import IsAuthenticated, AllowAny
|
||||
from rest_framework.response import Response
|
||||
from django_filters.rest_framework import DjangoFilterBackend
|
||||
from drf_spectacular.utils import extend_schema
|
||||
|
||||
from config.exceptions import AppError
|
||||
from .auth import TRIAL_INSTITUTION_NAME
|
||||
from .models import User, Role, TeacherStudentRelation, Institution, Department
|
||||
from .serializers import (
|
||||
UserSerializer, UserCreateSerializer, UserUpdateSerializer,
|
||||
@@ -196,3 +198,33 @@ class DepartmentViewSet(viewsets.ModelViewSet):
|
||||
filter_backends = [DjangoFilterBackend, filters.SearchFilter]
|
||||
filterset_fields = ['institution', 'category']
|
||||
search_fields = ['name']
|
||||
|
||||
|
||||
# ── 移动端机构列表(不分页,登录前可调用)─────────────────────────────────────
|
||||
|
||||
@extend_schema(
|
||||
summary='移动端机构列表(不分页)',
|
||||
description='返回当前可选的全部机构,供移动端学生登录时选择所属机构。'
|
||||
f'is_trial=true 标识预留试用机构({TRIAL_INSTITUTION_NAME})。',
|
||||
responses={200: None},
|
||||
tags=['机构'],
|
||||
)
|
||||
@api_view(['GET'])
|
||||
@permission_classes([AllowAny])
|
||||
def institution_list(request):
|
||||
"""移动端机构列表 — 全部机构、不分页"""
|
||||
institutions = Institution.objects.all().order_by('name')
|
||||
data = [
|
||||
{
|
||||
'id': inst.id,
|
||||
'code': inst.code,
|
||||
'name': inst.name,
|
||||
'type': inst.type,
|
||||
'level': inst.level,
|
||||
'province': inst.province,
|
||||
'city': inst.city,
|
||||
'is_trial': inst.name == TRIAL_INSTITUTION_NAME,
|
||||
}
|
||||
for inst in institutions
|
||||
]
|
||||
return Response(data)
|
||||
|
||||
Reference in New Issue
Block a user