django.contrib.auth.decorators: 33 total statements, 0.0% covered

Generated: Wed 2013-03-13 10:33 CET

Source file: /media/Envs/Envs/filer-gallery/lib/python2.7/site-packages/django/contrib/auth/decorators.py

Stats: 0 executed, 26 missed, 7 excluded, 34 ignored

  1. import urlparse
  2. from functools import wraps
  3. from django.conf import settings
  4. from django.contrib.auth import REDIRECT_FIELD_NAME
  5. from django.core.exceptions import PermissionDenied
  6. from django.utils.decorators import available_attrs
  7. def user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
  8. """
  9. Decorator for views that checks that the user passes the given test,
  10. redirecting to the log-in page if necessary. The test should be a callable
  11. that takes the user object and returns True if the user passes.
  12. """
  13. def decorator(view_func):
  14. @wraps(view_func, assigned=available_attrs(view_func))
  15. def _wrapped_view(request, *args, **kwargs):
  16. if test_func(request.user):
  17. return view_func(request, *args, **kwargs)
  18. path = request.build_absolute_uri()
  19. # If the login url is the same scheme and net location then just
  20. # use the path as the "next" url.
  21. login_scheme, login_netloc = urlparse.urlparse(login_url or
  22. settings.LOGIN_URL)[:2]
  23. current_scheme, current_netloc = urlparse.urlparse(path)[:2]
  24. if ((not login_scheme or login_scheme == current_scheme) and
  25. (not login_netloc or login_netloc == current_netloc)):
  26. path = request.get_full_path()
  27. from django.contrib.auth.views import redirect_to_login
  28. return redirect_to_login(path, login_url, redirect_field_name)
  29. return _wrapped_view
  30. return decorator
  31. def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
  32. """
  33. Decorator for views that checks that the user is logged in, redirecting
  34. to the log-in page if necessary.
  35. """
  36. actual_decorator = user_passes_test(
  37. lambda u: u.is_authenticated(),
  38. login_url=login_url,
  39. redirect_field_name=redirect_field_name
  40. )
  41. if function:
  42. return actual_decorator(function)
  43. return actual_decorator
  44. def permission_required(perm, login_url=None, raise_exception=False):
  45. """
  46. Decorator for views that checks whether a user has a particular permission
  47. enabled, redirecting to the log-in page if neccesary.
  48. If the raise_exception parameter is given the PermissionDenied exception
  49. is raised.
  50. """
  51. def check_perms(user):
  52. # First check if the user has the permission (even anon users)
  53. if user.has_perm(perm):
  54. return True
  55. # In case the 403 handler should be called raise the exception
  56. if raise_exception:
  57. raise PermissionDenied
  58. # As the last resort, show the login form
  59. return False
  60. return user_passes_test(check_perms, login_url=login_url)