Skip to content

Instantly share code, notes, and snippets.

@allynt
Created April 12, 2021 14:38
Show Gist options
  • Save allynt/6fb771c44f28d98702beaee8c8f27946 to your computer and use it in GitHub Desktop.
Save allynt/6fb771c44f28d98702beaee8c8f27946 to your computer and use it in GitHub Desktop.
from jsonpath import JSONPath
from rest_framework.permissions import BasePermission
from rest_framework.exceptions import PermissionDenied
def TokenMatchesJSONPath(get_jsonpath_expression):
"""
This fn is a factory that returns a _dynamic_ DRF Permission based on a JSONPath Expression.
Only a request w/ a token that matches that expression is granted permission.
"""
class _TokenMatchesJSONPath(BasePermission):
def has_permission(self, request, view):
if callable(get_jsonpath_expression):
jsonpath = JSONPath(get_jsonpath_expression(request))
else:
jsonpath = JSONPath(get_jsonpath_expression)
token = request.auth
if token and jsonpath.parse(token.payload):
return True
raise PermissionDenied(
f"JWT does not have permission for '{view.get_view_name()}'."
)
return _TokenMatchesJSONPath
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment