Authenticate correctly users that connect with an authorization token

This commit is contained in:
Yohann D'ANELLO 2020-09-10 09:31:27 +02:00
parent 6a0dc4cb10
commit 72cc1638e6
2 changed files with 15 additions and 1 deletions

View File

@ -16,7 +16,7 @@ class StrongDjangoObjectPermissions(DjangoObjectPermissions):
# The queryset is filtered, and permissions are more powerful than a simple check than just "can view this model" # The queryset is filtered, and permissions are more powerful than a simple check than just "can view this model"
perms_map = { perms_map = {
'GET': [], # ['%(app_label)s.view_%(model_name)s'], 'GET': ['%(app_label)s.view_%(model_name)s'],
'OPTIONS': [], 'OPTIONS': [],
'HEAD': [], 'HEAD': [],
'POST': ['%(app_label)s.add_%(model_name)s'], 'POST': ['%(app_label)s.add_%(model_name)s'],

View File

@ -50,6 +50,20 @@ class SessionMiddleware(object):
def __call__(self, request): def __call__(self, request):
user = request.user user = request.user
# If we authenticate through a token to connect to the API, then we query the good user
if 'HTTP_AUTHORIZATION' in request.META and request.path.startswith("/api"):
token = request.META.get('HTTP_AUTHORIZATION')
if token.startswith("Token "):
token = token[6:]
from rest_framework.authtoken.models import Token
if Token.objects.filter(key=token).exists():
token_obj = Token.objects.get(key=token)
user = token_obj.user
session = request.session
session["permission_mask"] = 42
session.save()
if 'HTTP_X_REAL_IP' in request.META: if 'HTTP_X_REAL_IP' in request.META:
ip = request.META.get('HTTP_X_REAL_IP') ip = request.META.get('HTTP_X_REAL_IP')
elif 'HTTP_X_FORWARDED_FOR' in request.META: elif 'HTTP_X_FORWARDED_FOR' in request.META: