@login_required depending on setting?

While I expected this to be answered somewhere on StackOverflow, I haven't found it, so I apologise if this is a dupe.

I want a setting to control whether certain views require a user to be logged in. If the setting is turned on, I want the views to behave as if they were decorated with @login_required, i.e. after the user logs in, they should be redirected back to the view.

I don't mind putting code in the view to check the setting and calling redirect("account_login") if it's turned on. And, I suppose, passing request.get_full_path() as the next parameter would probably work.

But redirecting to login and back seems a common enough use case for me to expect some elegant function in django.contrib.auth or django-allauth to do it, or that it would be easy to roll my own conditional @login_required decorator. Am I missing something?

Thanks.

I would go about adding my own decorator that inherits the login required functionality if needed. I would make an decorator that maybe cross references between the user id and the settings options. Django has no standard way of achieving this so your best bet is creating a custom decorator.

from functools import wraps
from django.conf import settings
from django.shortcuts import redirect
from django.contrib.auth.views import redirect_to_login

def login_required_if_setting(setting_name):
    """
    Conditionally requires login for a view based on a Django setting.
    Example usage:
        @login_required_if_setting("REQUIRE_LOGIN_FOR_DASHBOARD")
    """
    def decorator(view_func):
        @wraps(view_func)
        def _wrapped_view(request, *args, **kwargs):
            require_login = getattr(settings, setting_name, False)
            if require_login and not request.user.is_authenticated:
                return redirect_to_login(request.get_full_path())
            return view_func(request, *args, **kwargs)
        return _wrapped_view
    return decorator
Back to Top