Created
January 10, 2019 15:55
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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