Opened 8 years ago

Closed 8 years ago

#27483 closed New feature (wontfix)

Add a login_required decorator for AJAX requests

Reported by: Ramin Farajpour Cami Owned by: Ramin Farajpour Cami
Component: contrib.auth Version: 1.10
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Hi,

if users use the @login_required decorator or perform manually a redirect to a form on AJAX request , when an Ajax call is made the user is logged in, here is:

check users,

from functools import wraps
from django.core.exceptions import PermissionDenied


def ajax_login_required(function):
    def wrap(request, *args, **kwargs):
        if request.user.is_authenticated():
            return function(request, *args, **kwargs)
        return PermissionDenied ## or 401 == not authenticated
    wrap.__doc__ = function.__doc__
    wrap.__name__ = function.__name__
    return wrap

raise PermissionDenied will cause a 403 status code or 401 Unauthorized to be returned to the client,

check superusers:

from functools import wraps
from django.core.exceptions import PermissionDenied


def ajax_admin_required(function):
    def wrap(request, *args, **kwargs):
        if request.user.is_authenticated() and request.user.is_superuser:
            return function(request, *args, **kwargs)
        return PermissionDenied ## or 401 == not authenticated
    wrap.__doc__ = function.__doc__
    wrap.__name__ = function.__name__
    return wrap

Change History (4)

comment:1 by Ramin Farajpour Cami, 8 years ago

Owner: changed from nobody to Ramin Farajpour Cami
Status: newassigned

comment:2 by Tim Graham, 8 years ago

Similar things have been suggested on Stackoverflow 1, 2. I'm not sure whether or not it needs to be in Django, after all it's only a few lines. You could write to the DevelopersMailingList to see what others think.

comment:3 by Ramin Farajpour Cami, 8 years ago

Thanks,

First :
i think we should have on docs about use @login_required in request AJAX, i don't see this Note for AJAX request must developer cheat to use @login_required on request AJAX while @login_required is not return content type json or html to client,
https://docs.djangoproject.com/en/1.10/topics/auth/default/#django.contrib.auth.decorators.login_required,

now for subject this ticket ok i will write to google group

Last edited 8 years ago by Ramin Farajpour Cami (previous) (diff)

comment:4 by Tim Graham, 8 years ago

Resolution: wontfix
Status: assignedclosed
Summary: check login_required ajax users decorators and superuser decoratorsAdd a login_required decorator for AJAX requests

Closing, pending further discussion on the mailing list.

Note: See TracTickets for help on using tickets.
Back to Top