我试图通过装饰器类在Django中实现一个权限。 在那里,我检查用户是否经过身份验证,以及用户具有的角色(ADMIN,HQ_ADMIN,...)
这是我的代码:
class UserPermissions(permissions.BasePermission):
def has_permission(self, request, view):
if not request.user and request.user.is_authenticated():
return False
method = request.method
authenticator = request._authenticator
response = self.check_permission_roles(request)
if(response == None):
if method == 'POST' and isinstance(authenticator, BasicAuthentication):
return True
if method == 'PUT' and isinstance(authenticator, BasicAuthentication):
return True
if method == 'DELETE' and isinstance(authenticator, BasicAuthentication):
return True
if method == 'GET':
return True
return False
def check_permission_roles(self, request):
""" checks the roles from the logged-in user """
headers = {'Access-Control-Allow-Origin':'*'}
logged_in_user_roles = request.user.roles
new_roles = request.DATA[models.ROLES]
# check roles for create ADMIN
if models.ADMIN in new_roles:
if models.ADMIN not in logged_in_user_roles:
return Response("no right to create role: ADMIN", status=400, headers=headers)
# check roles for create HQ_ADMIN
if models.HQ_ADMIN in new_roles:
if models.ADMIN not in logged_in_user_roles:
if models.HQ_ADMIN not in logged_in_user_roles:
return Response("no right to create role: HQ_ADMIN", status=400, headers=headers)
# check roles for create HQ_USER
if models.HQ_USER in new_roles:
if models.ADMIN not in logged_in_user_roles:
if models.HQ_ADMIN not in logged_in_user_roles:
return Response("no right to create role: HQ_USER", status=400, headers=headers)
# check roles for create WORKSHOP_USER
if models.WORKSHOP_USER in new_roles:
if models.ADMIN not in logged_in_user_roles:
if models.HQ_ADMIN not in logged_in_user_roles:
if models.HQ_USER not in logged_in_user_roles:
return Response("no right to create role: WORKSHOP_USER", status=400, headers=headers)
# check roles for create DRIVER
if models.DRIVER in new_roles:
if models.ADMIN not in logged_in_user_roles:
if models.HQ_ADMIN not in logged_in_user_roles:
if models.HQ_USER not in logged_in_user_roles:
if models.WORKSHOP_USER not in logged_in_user_roles:
return Response("no right to create role: DRIVER", status=400, headers=headers)
return None
如果我现在发送post命令,并且check_permission_roles方法返回的不是None,我希望Django发送从check_permission_roles函数而不是标准响应返回的Response(403,您没有权限执行此操作。)
如何阻止Django返回默认响应,而是返回自定义响应?
答案 0 :(得分:0)
回答旧问题
您可以创建一个自定义异常处理程序,在其中您可以处理“PermissionDenied”#39;带有所需错误代码和消息的异常
def core_exception_handler(exc, context):
response = exception_handler(exc, context)
handlers = {
'PermissionDenied': _handle_error,
}
exception_class = exc.__class__.__name__
if exception_class in handlers:
return handlers[exception_class](exc, context, response)
return response
def _handle_error(exc, context, response):
response.status_code=401 #setting response code as 401
response.data = {
'errors': response.data
}
return response
像这样的东西。