From 72cc1638e65a906a0f8fe1b11d429a3e9183097a Mon Sep 17 00:00:00 2001 From: Yohann D'ANELLO Date: Thu, 10 Sep 2020 09:31:27 +0200 Subject: [PATCH] Authenticate correctly users that connect with an authorization token --- apps/permission/permissions.py | 2 +- note_kfet/middlewares.py | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/apps/permission/permissions.py b/apps/permission/permissions.py index b0885e81..f2ca28f0 100644 --- a/apps/permission/permissions.py +++ b/apps/permission/permissions.py @@ -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" perms_map = { - 'GET': [], # ['%(app_label)s.view_%(model_name)s'], + 'GET': ['%(app_label)s.view_%(model_name)s'], 'OPTIONS': [], 'HEAD': [], 'POST': ['%(app_label)s.add_%(model_name)s'], diff --git a/note_kfet/middlewares.py b/note_kfet/middlewares.py index 8987816d..22f3e264 100644 --- a/note_kfet/middlewares.py +++ b/note_kfet/middlewares.py @@ -50,6 +50,20 @@ class SessionMiddleware(object): def __call__(self, request): 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: ip = request.META.get('HTTP_X_REAL_IP') elif 'HTTP_X_FORWARDED_FOR' in request.META: