1
0
Fork 0

authentication: always require if defined env

if SPEJSTORE_REQUIRE_AUTH is 'true' then always require auth
otherwise make it read-only on unauthorized access
This commit is contained in:
Dariusz Niemczyk 2023-08-13 20:07:29 +02:00
parent d942c99cb9
commit 9200bdbb3b
No known key found for this signature in database
2 changed files with 17 additions and 6 deletions

View File

@ -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",
],
}

View File

@ -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)