django-multitenant
django-multitenant copied to clipboard
Using JWT,Unable to get user in middleware
class Product_ViewSet(viewsets.ModelViewSet):
serializer_class = Product_serializers
permission_classes = (IsAuthenticated,)
authentication_classes = (JSONWebTokenAuthentication, ) # this
def get_queryset(self):
return Product.objects.all()
class MultitenantMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if request.user and not request.user.is_anonymous: # AnonymousUser
set_current_tenant(request.user.store)
return self.get_response(request)
because jwt authentication mechanism works in view function.
solution:
from django.utils.functional import SimpleLazyObject
from django.contrib.auth.models import AnonymousUser
from rest_framework.request import Request
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
def get_user_jwt(request):
user = None
try:
user_jwt = JSONWebTokenAuthentication().authenticate(Request(request))
if user_jwt is not None:
user = user_jwt[0]
except:
pass
return user or AnonymousUser()
class MultitenantMiddleware():
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
return self.get_response(request)
def process_view(self, request, view_func, view_args, view_kwargs):
request.user = SimpleLazyObject(lambda: get_user_jwt(request))
if request.user and not request.user.is_anonymous:
set_current_tenant(request.user.store)
print(request.user)
https://gist.github.com/AndrewJHart/9bb9eaea2523cd2144cf959f48a14194
I just want to simply use 'set_ current_ tenant()' . But it will repeat the work, is there a better solution ? thanks.