Apply UserPassesTest to url namespace ?

Is possible to add a decorator/wrapper in urls.py to protect not just one view but the root namespace of multiple views


urlpatterns = [
.....
    path("", include("demandes.page_urls"), auth_fn), # where auth_fn is some impl of UserPassesTestMixin or similar
    path("", include("organisation.page_urls")),
    ...
]

There isn’t anything built-in to Django for that, but you could implement that functionality using middleware.

For example, see django-login-required-middleware · PyPI to get ideas on how to implement it.

I’ve done something like that in one of my projects, below is the code for your reference

urls.py

from django.contrib.auth.decorators import user_passes_test

def super_required(view_func=None, redirect_field_name=None, login_url=None):
    actual_decorator = user_passes_test(
        lambda u: u.is_active and u.is_staff or u.is_superuser,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if view_func:
        return actual_decorator(view_func)

    return actual_decorator

urlpatterns = [
    path('', super_required(views.AdminHome.as_view()), name="admin_home"),
    
    path('customer/', super_required(views.CustomerListView.as_view()), name="customer_list"),
    path('customer/<int:id>/', super_required(views.customer_update), name="customer_update"),
]
settings.py

LOGOUT_REDIRECT_URL = '/accounts/login/'
LOGIN_REDIRECT_URL = '/'

Note: This code is just for your reference modify it according to your need and use it.

I ended up writing a RouteAuthMiddleware that check if the user is authenticated (and not a superuser) and then runs group and perm_checks based on the URL.

Definitely should not be abused but it works for me as these are completely different dashboards that target completely different classes of users with permissions that can granularly provisioned

That being said, route-level middleware would be a cool feature to tack on