Skip to content

Instantly share code, notes, and snippets.

@gilsonbp
Created January 10, 2019 15:55
Show Gist options
  • Save gilsonbp/741873ab52fb7d60eb79ba2f58f65794 to your computer and use it in GitHub Desktop.
Save gilsonbp/741873ab52fb7d60eb79ba2f58f65794 to your computer and use it in GitHub Desktop.
It increments the request.user when the authentication is of type jwt. By default it is not incremented.
from re import sub
import jwt
from django.conf import settings
from django.contrib.auth import get_user_model
from jwt import DecodeError
from rest_framework.exceptions import PermissionDenied
User = get_user_model()
class SetCurrentTenantFromUser(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
header_token = request.META.get('HTTP_AUTHORIZATION', None)
if header_token is not None:
try:
token = sub('Bearer ', '',
request.META.get('HTTP_AUTHORIZATION', None))
token_decode = jwt.decode(token, settings.SECRET_KEY,
algorithms=['HS256'])
request.user = User.objects.get(pk=token_decode['user_id'])
except (DecodeError, User.DoesNotExist):
pass
"""
Verifying that the user who made the request is the same one
related to the company, except when the request is in
an endpoint of public schema_name.
"""
if hasattr(request.user,
'empresauser') and request.tenant.schema_name != \
'public':
empresa = request.user.empresauser.empresa
if not request.tenant == empresa:
# TODO: Handle, is returning an HTML
raise PermissionDenied()
response = self.get_response(request)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment