Files
2026-06-13 13:21:53 +08:00

77 lines
2.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from rest_framework_simplejwt.tokens import RefreshToken
from config.exceptions import AppError
# 系统五类角色:super_admin / hospital_admin / content_admin / doctor(带教医生)/ student
ROLE_TYPES = ('super_admin', 'hospital_admin', 'content_admin', 'doctor', 'student')
# 移动端可自注册的角色(带教老师即 doctor,不单列 teacher
ALLOWED_ROLE_TYPES = ('student', 'doctor')
# 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)
return {'access': str(refresh.access_token), 'refresh': str(refresh)}
def build_user_response(user):
inst = user.institution if user.institution_id else None
return {
'id': user.id,
'username': user.username,
'phone': user.phone,
'real_name': user.real_name,
'role_type': user.role_type,
'institution_code': inst.code if inst else None,
'institution_name': inst.name if inst else None,
'department': user.department.name if user.department_id else None,
}
def resolve_or_create_institution(code, name):
"""按机构编码查找,不存在则自动创建。
Args:
code: 机构编码(必填,唯一标识)
name: 机构名称(必填,创建时使用)
Returns:
Institution 实例
"""
from apps.user.models import Institution
if not code:
raise AppError('USER_INSTITUTION_CODE_REQUIRED', '机构编码不能为空')
if not name:
raise AppError('USER_INSTITUTION_REQUIRED', '机构名称不能为空')
institution, _ = Institution.objects.get_or_create(
code=code,
defaults={'name': name, 'type': 'hospital'},
)
return institution
def get_client_ip(request):
xff = request.META.get('HTTP_X_FORWARDED_FOR')
if xff:
return xff.split(',')[0].strip()
return request.META.get('REMOTE_ADDR')
def get_user_agent(request):
return request.META.get('HTTP_USER_AGENT', '')