60 lines
2.1 KiB
Python
60 lines
2.1 KiB
Python
from rest_framework.permissions import BasePermission
|
|
|
|
from config.exceptions import AppError
|
|
from apps.user.models import TeacherStudentRelation
|
|
|
|
|
|
def _is_admin(user):
|
|
"""管理员判定:super_admin / content_admin / is_staff"""
|
|
return user.role_type in ('super_admin', 'content_admin') or user.is_staff
|
|
|
|
|
|
class IsUserListPermitted(BasePermission):
|
|
"""U9 用户列表权限:管理员全员、教师仅看自己学生、其他 403"""
|
|
|
|
def has_permission(self, request, view):
|
|
user = request.user
|
|
if _is_admin(user):
|
|
return True
|
|
if user.role_type == 'teacher':
|
|
return True
|
|
raise AppError('USER_NO_LIST_PERMISSION', '您没有查看用户列表的权限', status_code=403)
|
|
|
|
|
|
class IsUserDetailPermitted(BasePermission):
|
|
"""U10 用户详情权限:管理员任意、本人、教师看自己学生"""
|
|
|
|
def has_object_permission(self, request, view, obj):
|
|
user = request.user
|
|
# 管理员:可查看任意用户
|
|
if _is_admin(user):
|
|
return True
|
|
# 本人:可查看自己
|
|
if user.id == obj.id:
|
|
return True
|
|
# 教师:可查看自己名下活跃学生
|
|
if user.role_type == 'teacher':
|
|
if TeacherStudentRelation.objects.filter(
|
|
teacher=user, student=obj, status=1
|
|
).exists():
|
|
return True
|
|
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):
|
|
"""病例操作权限:所有已登录用户均可操作"""
|
|
|
|
def has_permission(self, request, view):
|
|
return request.user and request.user.is_authenticated
|