I doing some refactoring in our code. A @render_to_json
decorator was internally calling an is_logged_in
method. I'm removing that in favor of simply adding another explicit @login_required
decorator.
Problem is that some of our methods are called via AJAX and are expecting a json response of {"status": "logged_out"}
which they then act on. So I need to change our login_required method to somehow check one of two things.
- Was this method called via AJAX, perhaps detecting the
XMLHttpRequest
header - Was the
render_to_json
decorator also called for this request. The thought would be that if thelogin_required
method knew that the request was expecting json then it could return the json packet, else redirect as normal.
UPDATE Adding a 3rd option.
- In every case a method with the
@render_to_json
decorator, the@login_required
decorator is referenced before it. The@login_required
method returnsHttpResponseRedirect
if the user is logged out. In the@render_to_json
method how would I check the return type of the login_required method and respond appropriately?
Thoughts? Problems?
I should add I'm also fairly new to Python so I might be missing something basic. If so, help me learn?
UPDATE
I'm going to go ahead and add the two decorators here for reference.
def render_to_json(fn):
@wraps(fn)
def inner(request, *args, **kwargs):
result = fn(request, *args, **kwargs)
return HttpResponse(json.dumps(result), mimetype='application/json')
return inner
def login_required(func):
@wraps(func)
def _decorator(request, *args, **kwargs):
if not is_logged_in(request):
from apps.core.extendedLogging import ExtendedLogging
ExtendedLogging.log("In login req'd: it appears that the user is not logged in", request)
request.session['login_referrer_uri'] = request.build_absolute_uri()
return HttpResponseRedirect(settings.LOGIN_URL)
return func(request, *args, **kwargs)
return _decorator