123456789101112131415161718192021222324252627282930313233343536373839404142434445464748 |
- import re
- import jwt
- from django.http import HttpResponse
- # from jwt import exceptions
- from rest_framework.exceptions import AuthenticationFailed
- from apps.user.models import User, Role
- class RoleControl(object):
- """使用类装饰器来权限校验"""
- def __init__(self, func):
- self.func = func
- def __call__(self, request, *args, **kwargs):
- token = request.META.get('HTTP_ACCESSTOKEN')
- SALT = 'django-insecure-zo64fvv02msf-se7!dek5*w$17#3nh6zta#!i=79bt9d#f88@i'
- try:
- payload = jwt.decode(token, SALT, True)
- # except exceptions.ExpiredSignatureError:
- # raise AuthenticationFailed({'code': 1003, "error": "token已失效"})
- except jwt.DecodeError:
- raise AuthenticationFailed({'code': 1003, 'error': "token认证失败"})
- except jwt.InvalidTokenError:
- raise AuthenticationFailed({'code': 1003, 'error': "非法token"})
- user = User.objects.get(id=payload['userid'])
- role = Role.objects.get(id="TestLaboratory_V1_Role_"+str(user.identify+1))
- permission = role.permissions.filter(method=request.method)
- match = False
- path = request.path
- if path[-1] == '\n':
- path = path[:-1]
- if path[-1] == '/':
- path = path[:-1]
- for per in permission:
- if re.fullmatch(per.url, path):
- match = True
- break
- if not match:
- return HttpResponse(status=500, content='用户无访问权限')
- return self.func(request, *args, **kwargs)
|