From 2f5f312d9c6a1b65c128646351f5c69851791cd5 Mon Sep 17 00:00:00 2001 From: Alexander PapaTutuWawa Date: Fri, 5 Feb 2021 13:28:08 +0100 Subject: [PATCH] Move the Django API Permissions to a FastAPI dependency --- etebase_server/settings.py | 5 +---- myauth/ldap.py | 18 +++++++----------- 2 files changed, 8 insertions(+), 15 deletions(-) diff --git a/etebase_server/settings.py b/etebase_server/settings.py index e5dad08..0a4d1e2 100644 --- a/etebase_server/settings.py +++ b/etebase_server/settings.py @@ -130,7 +130,6 @@ STATIC_ROOT = os.environ.get("DJANGO_STATIC_ROOT", os.path.join(BASE_DIR, "stati MEDIA_ROOT = os.environ.get("DJANGO_MEDIA_ROOT", os.path.join(BASE_DIR, "media")) MEDIA_URL = "/user-media/" -ETEBASE_API_PERMISSIONS = ["rest_framework.permissions.IsAuthenticated"] ETEBASE_API_AUTHENTICATORS = ( "django_etebase.token_auth.authentication.TokenAuthentication", "rest_framework.authentication.SessionAuthentication", @@ -143,8 +142,6 @@ config_locations = [ "/etc/etebase-server/etebase-server.ini", ] -ETEBASE_CREATE_USER_FUNC = "django_etebase.utils.create_user_blocked" - # Use config file if present if any(os.path.isfile(x) for x in config_locations): config = configparser.ConfigParser() @@ -180,7 +177,7 @@ if any(os.path.isfile(x) for x in config_locations): # Configure EteBase to use LDAP ETEBASE_CREATE_USER_FUNC = "myauth.ldap.create_user" - ETEBASE_API_PERMISSIONS.append("myauth.ldap.LDAPUserExists") + ETEBASE_API_PERMISSIONS_READ = ["myauth.ldap.is_user_in_ldap"] # Efficient file streaming (for large files) SENDFILE_BACKEND = "django_etebase.sendfile.backends.simple" diff --git a/myauth/ldap.py b/myauth/ldap.py index 1d757e7..a79c4af 100644 --- a/myauth/ldap.py +++ b/myauth/ldap.py @@ -4,8 +4,10 @@ from django.utils import timezone from django.conf import settings from django.core.exceptions import PermissionDenied from django_etebase.utils import CallbackContext -from myauth.models import get_typed_user_model -from rest_framework.permissions import BasePermission +from myauth.models import get_typed_user_model, UserType +from etebase_fastapi.dependencies import get_authenticated_user +from etebase_fastapi.exceptions import PermissionDenied +from fastapi import Depends import ldap @@ -76,15 +78,9 @@ class LDAPConnection: return True return False - -class LDAPUserExists(BasePermission): - """ - A permission check which first checks with the LDAP directory if the user - exists. - """ - - def has_permission(self, request, view): - return LDAPConnection.get_instance().has_user(request.user.username) +def is_user_in_ldap(user: UserType = Depends(get_authenticated_user)): + if not LDAPConnection.get_instance().has_user(user.username): + raise PermissionDenied("User not in LDAP directory.") def create_user(context: CallbackContext, *args, **kwargs): """