2026-05-29 15:58:00 +08:00
|
|
|
from rest_framework_simplejwt.tokens import RefreshToken
|
|
|
|
|
|
2026-06-03 17:34:47 +08:00
|
|
|
from config.exceptions import AppError
|
|
|
|
|
|
2026-05-29 15:58:00 +08:00
|
|
|
ALLOWED_ROLE_TYPES = ('student', 'doctor', 'teacher')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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):
|
2026-06-03 17:34:47 +08:00
|
|
|
inst = user.institution if user.institution_id else None
|
2026-05-29 15:58:00 +08:00
|
|
|
return {
|
|
|
|
|
'id': user.id,
|
|
|
|
|
'username': user.username,
|
|
|
|
|
'phone': user.phone,
|
|
|
|
|
'real_name': user.real_name,
|
|
|
|
|
'role_type': user.role_type,
|
2026-06-03 17:34:47 +08:00
|
|
|
'institution_code': inst.code if inst else None,
|
|
|
|
|
'institution_name': inst.name if inst else None,
|
2026-05-29 15:58:00 +08:00
|
|
|
'department': user.department.name if user.department_id else None,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
2026-06-03 17:34:47 +08:00
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
2026-05-29 15:58:00 +08:00
|
|
|
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', '')
|