Open Natgho opened 1 year ago
Hi,
Yes you are right, I only put the login feature in this PR. I leave the other issue to you, I can help the code if you open it as a PR.
A few thoughts/comments:
staff_member_required
but I suspect other use cases may arise; for example user_is_authenticated
or user is in group 'x'.login_required
decorator). If we continue this route, we'll need to document it somewhere and also update the configuration docsA way to achieve point 1 is:
diff --git a/src/dj_tracker/constants.py b/src/dj_tracker/constants.py
index 0b311e1..1ef844a 100644
--- a/src/dj_tracker/constants.py
+++ b/src/dj_tracker/constants.py
@@ -34,6 +34,7 @@ def _set_dj_tracker_settings():
"APPS_TO_EXCLUDE": (),
"IGNORE_MODULES": (),
"IGNORE_PATHS": (),
+ "USER_TEST_FUNC": lambda user: True,
}
DJ_TRACKER_SETTINGS.update(getattr(settings, "DJ_TRACKER", {}))
@@ -102,6 +103,19 @@ def _get_collection_interval():
return DJ_TRACKER_SETTINGS.pop("COLLECTION_INTERVAL")
+def _get_user_test_func():
+ from django.contrib.auth.decorators import user_passes_test
+ from django.utils.module_loading import import_string
+
+ _set_dj_tracker_settings()
+
+ test_func = DJ_TRACKER_SETTINGS.pop("USER_TEST_FUNC")
+ if isinstance(test_func, str):
+ test_func = import_string(test_func)
+
+ return user_passes_test(test_func)
+
+
def _get_trackings_db():
from django.conf import settings
diff --git a/src/dj_tracker/urls.py b/src/dj_tracker/urls.py
index f45bd85..42fba7d 100644
--- a/src/dj_tracker/urls.py
+++ b/src/dj_tracker/urls.py
@@ -1,6 +1,8 @@
+from functools import update_wrapper
+
from django.urls import path, register_converter
-from dj_tracker import views
+from dj_tracker import constants, views
class CacheKeyConverter:
@@ -36,3 +38,7 @@ urlpatterns = [
name="query-group",
),
]
+
+wrapper = constants.USER_TEST_FUNC
+for pattern in urlpatterns:
+ pattern.callback = update_wrapper(wrapper(pattern.callback), pattern.callback)
WIth these changes, one could limit access to staff by doing the following:
# settings.py
DJ_TRACKER = { "USER_TEST_FUNC": lambda user: user.is_staff}
Thanks @Natgho. Please see my comment on https://github.com/Tijani-Dia/dj-tracker/pull/27.