You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

decorators.py 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import urlparse
  2. from functools import wraps
  3. from django.contrib.auth import REDIRECT_FIELD_NAME
  4. from django.shortcuts import render
  5. from django.contrib import messages
  6. from django.contrib.auth.views import redirect_to_login
  7. from django.core.exceptions import PermissionDenied
  8. from django.core.urlresolvers import reverse_lazy
  9. from django.utils.translation import ugettext_lazy as _
  10. def staff_member_required(view_func, login_url=None):
  11. """
  12. Ensure that the user is a logged-in staff member.
  13. * If not authenticated, redirect to a specified login URL.
  14. * If not staff, show a 403 page
  15. This decorator is based on the decorator with the same name from
  16. django.contrib.admin.view.decorators. This one is superior as it allows a
  17. redirect URL to be specified.
  18. """
  19. if login_url is None:
  20. login_url = reverse_lazy('customer:login')
  21. @wraps(view_func)
  22. def _checklogin(request, *args, **kwargs):
  23. if request.user.is_active and request.user.is_staff:
  24. return view_func(request, *args, **kwargs)
  25. # If user is not logged in, redirect to login page
  26. if not request.user.is_authenticated():
  27. # If the login url is the same scheme and net location then just
  28. # use the path as the "next" url.
  29. path = request.build_absolute_uri()
  30. login_scheme, login_netloc = urlparse.urlparse(login_url)[:2]
  31. current_scheme, current_netloc = urlparse.urlparse(path)[:2]
  32. if ((not login_scheme or login_scheme == current_scheme) and
  33. (not login_netloc or login_netloc == current_netloc)):
  34. path = request.get_full_path()
  35. messages.warning(request, _("You must log in to access this page"))
  36. return redirect_to_login(path, login_url, REDIRECT_FIELD_NAME)
  37. else:
  38. # User does not have permission to view this page
  39. raise PermissionDenied
  40. return _checklogin
  41. def login_forbidden(view_func, template_name='login_forbidden.html',
  42. status=403):
  43. """
  44. Only allow anonymous users to access this view.
  45. """
  46. @wraps(view_func)
  47. def _checklogin(request, *args, **kwargs):
  48. if not request.user.is_authenticated():
  49. return view_func(request, *args, **kwargs)
  50. return render(request, template_name, status=status)
  51. return _checklogin