citusdata / citusdata/django-multitenant

Using JWT,Unable to get user in middleware

Open
#127 0 comments 2 reactions 0 assignees View on GitHub
enhancement question
Dominant language
Python
Stars
823
Forks
126
PR merge metrics
No merged PRs in 30d

Description

```
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](url)

I just want to simply use 'set_ current_ tenant()' . But it will repeat the work, is there a better solution ?
thanks.

Contributor guide

Open the contributing guide

Research direction

Start with MultitenantMiddleware.__call__ and process_view and the JSONWebTokenAuthentication entry point shown in the issue; trace when middleware runs relative to view authentication. Done means the project has a documented or supported way to call set_current_tenant without repeating JWT authentication.

Written by the indexing model from the issue text.

Assessment

Tech stack
django, python
Domain
authentication, backend
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.