ndarville / pony-forum

A modern alternative to ancient forum CMSes like vBulletin and PHPBB in Python on Django. (Alpha stage.) (NB: dotCloud have since removed their free Sandbox tier.)
http://pony-forum.com
26 stars 7 forks source link

@login_required for thread_js and user_js #6

Closed ndarville closed 11 years ago

ndarville commented 12 years ago

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.

ndarville commented 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)
ndarville commented 11 years ago

Options:

Handle with

  1. Jinja:
    • {% if user.is_authenticated %}class="button js"{% else %}class="button"{% endif %}
  2. JS:
    • if (log-in link in the navigation bar) { (...) }
    • if (...) { e.preventdefault; }
  3. Django view:
    • @login_required_ajax()

JS

// .length to evaluate the returned object,
// which otherwise always evaluates to true
if ($('.last:contains("Log out")').length) {
    // entire action
}