Tijani-Dia / dj-tracker

A Django app that tracks your queries to help optimize them. Demo: https://dj-tracker-bakerydemo.fly.dev/dj-tracker/
https://tijani-dia.github.io/dj-tracker/
BSD 3-Clause "New" or "Revised" License
80 stars 3 forks source link

LOGIN page functionality #28

Open Natgho opened 1 year ago

Tijani-Dia commented 1 year ago

Thanks @Natgho. Please see my comment on https://github.com/Tijani-Dia/dj-tracker/pull/27.

Natgho commented 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.

Tijani-Dia commented 1 year ago

A few thoughts/comments:

  1. I think we may want to make the user test configurable. Currently, this uses staff_member_required but I suspect other use cases may arise; for example user_is_authenticated or user is in group 'x'.
  2. This implementation assumes one has an authentication system in place (See notes on login_required decorator). If we continue this route, we'll need to document it somewhere and also update the configuration docs

A 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}