Skip to content

Instantly share code, notes, and snippets.

@rtyley
Created September 9, 2010 15:23
Show Gist options
  • Save rtyley/572009 to your computer and use it in GitHub Desktop.
Save rtyley/572009 to your computer and use it in GitHub Desktop.
from django.utils.http import urlquote
from functools import wraps
from django.utils.decorators import available_attrs
from django.contrib.auth import REDIRECT_FIELD_NAME
from common.shortcuts import render_json
from django.http import HttpResponseRedirect
def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
"""
MODIFIED from django/contrib/auth/decorators.py - now returns our custom JSON-failure
message for AJAX requests.
Decorator for views that checks that the user passes the given test,
redirecting to the log-in page if necessary. The test should be a callable
that takes the user object and returns True if the user passes.
"""
if not login_url:
from django.conf import settings
login_url = settings.LOGIN_URL
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user):
return view_func(request, *args, **kwargs)
if request.is_ajax():
return render_json({
'fatal-error': True,
'description': 'You are not logged in!'
})
path = urlquote(request.get_full_path())
tup = login_url, redirect_field_name, path
return HttpResponseRedirect('%s?%s=%s' % tup)
return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
return decorator
def permission_required(perm, login_url=None):
"""
Decorator for views that checks whether a user has a particular permission
enabled, redirecting to the log-in page if necessary.
"""
return user_passes_test(lambda u: u.has_perm(perm), login_url=login_url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment