Closed ndarville closed 11 years ago
First version:
def login_required_ajax(function=None,redirect_field_name=None):
"""Supports an AJAX version of login_required().
Proceed, if user is authenticated, otherwise return 401, authentication required,
instead of the 302 redirect of the original Django decorator
"""
def _decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if request.user.is_authenticated():
return view_func(request, *args, **kwargs)
else:
return HttpResponse(status=401)
return _wrapped_view
if function is None:
return _decorator
else:
return _decorator(function)
The second one is intended to display a pop-up message instead of redirecting the user.
def login_required_ajax(function=None,redirect_field_name=None):
"""Supports an AJAX version of login_required().
Proceed, if user is authenticated, otherwise return 401, authentication required,
instead of the 302 redirect of the original Django decorator
"""
def _decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if request.user.is_authenticated():
return view_func(request, *args, **kwargs)
else:
return HttpResponse(status=401)
return _wrapped_view
if function is None:
return _decorator
else:
return _decorator(function)
Options:
Handle with
{% if user.is_authenticated %}class="button js"{% else %}class="button"{% endif %}
if (log-in link in the navigation bar) { (...) }
if (...) { e.preventdefault; }
@login_required_ajax()
// .length to evaluate the returned object,
// which otherwise always evaluates to true
if ($('.last:contains("Log out")').length) {
// entire action
}
Firebug:
"NetworkError: 403 FORBIDDEN - http://127.0.0.1:8000/thread/js/"
The return code is
403
, so there is a redirection involved; something just doesn’t hook properly into it.It throws an error, even when the decorator is not enabled. Looks like it’s something else.