rolecontrol.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import re
  2. import jwt
  3. from django.http import HttpResponse
  4. # from jwt import exceptions
  5. from rest_framework.exceptions import AuthenticationFailed
  6. from apps.user.models import User, Role
  7. class RoleControl(object):
  8. """使用类装饰器来权限校验"""
  9. def __init__(self, func):
  10. self.func = func
  11. def __call__(self, request, *args, **kwargs):
  12. token = request.META.get('HTTP_ACCESSTOKEN')
  13. SALT = 'django-insecure-zo64fvv02msf-se7!dek5*w$17#3nh6zta#!i=79bt9d#f88@i'
  14. try:
  15. payload = jwt.decode(token, SALT, True)
  16. # except exceptions.ExpiredSignatureError:
  17. # raise AuthenticationFailed({'code': 1003, "error": "token已失效"})
  18. except jwt.DecodeError:
  19. raise AuthenticationFailed({'code': 1003, 'error': "token认证失败"})
  20. except jwt.InvalidTokenError:
  21. raise AuthenticationFailed({'code': 1003, 'error': "非法token"})
  22. user = User.objects.get(id=payload['userid'])
  23. role = Role.objects.get(id="TestLaboratory_V1_Role_"+str(user.identify+1))
  24. permission = role.permissions.filter(method=request.method)
  25. match = False
  26. path = request.path
  27. if path[-1] == '\n':
  28. path = path[:-1]
  29. if path[-1] == '/':
  30. path = path[:-1]
  31. for per in permission:
  32. if re.fullmatch(per.url, path):
  33. match = True
  34. break
  35. if not match:
  36. return HttpResponse(status=500, content='用户无访问权限')
  37. return self.func(request, *args, **kwargs)