From 9200bdbb3baa92256e1cf3707fe937ea463fcffd Mon Sep 17 00:00:00 2001 From: Dariusz Niemczyk Date: Sun, 13 Aug 2023 20:07:29 +0200 Subject: [PATCH] authentication: always require if defined env if SPEJSTORE_REQUIRE_AUTH is 'true' then always require auth otherwise make it read-only on unauthorized access --- spejstore/settings.py | 16 ++++++++++++---- storage/authentication.py | 7 +++++-- 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/spejstore/settings.py b/spejstore/settings.py index 600feab..17472a9 100644 --- a/spejstore/settings.py +++ b/spejstore/settings.py @@ -159,22 +159,30 @@ USE_TZ = True # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = "/static/" -STATICFILES_DIRS = [ - os.path.join(BASE_DIR, "static"), -] +STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] MEDIA_URL = "/media/" MEDIA_ROOT = env("MEDIA_ROOT", os.path.join(BASE_DIR, "media")) +REQUIRE_AUTH = env("REQUIRE_AUTH", "true") +if REQUIRE_AUTH == "true": + REQUIRE_AUTH = True +elif REQUIRE_AUTH == "false": + REQUIRE_AUTH = False + # REST Framework REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. "DEFAULT_PERMISSION_CLASSES": [ - "rest_framework.permissions.IsAuthenticatedOrReadOnly", + "rest_framework.permissions.IsAuthenticatedOrReadOnly" + if REQUIRE_AUTH + else "rest_framework.permissions.IsAuthenticated", ], "DEFAULT_AUTHENTICATION_CLASSES": [ "storage.authentication.LanAuthentication", + "rest_framework.authentication.BasicAuthentication", + "rest_framework.authentication.TokenAuthentication", ], } diff --git a/storage/authentication.py b/storage/authentication.py index 2da2c4d..959f071 100644 --- a/storage/authentication.py +++ b/storage/authentication.py @@ -1,7 +1,7 @@ import ipaddress from rest_framework import exceptions -from rest_framework.authentication import BaseAuthentication +from rest_framework.authentication import SessionAuthentication from spejstore.settings import ( LAN_ALLOWED_ADDRESS_SPACE, LAN_ALLOWED_HEADER, @@ -40,8 +40,11 @@ def get_ip_from_request(request): return None -class LanAuthentication(BaseAuthentication): +class LanAuthentication(SessionAuthentication): def authenticate(self, request): + is_session_authorized = super().authenticate(request) + if is_session_authorized: + return is_session_authorized is_authorized = self.has_permission(request) if is_authorized: user = getattr(request._request, "user", None)