permission.decorators.function_decorators: 28 total statements, 94.7% covered

Generated: Thu 2012-03-01 14:22 CST

Source file: /home/alisue/Dropbox/Codes/django-permission/permission/decorators/function_decorators.py

Stats: 18 executed, 1 missed, 9 excluded, 46 ignored

  1. #!/usr/bin/env python
  2. # vim: set fileencoding=utf-8 :
  3. """
  4. Generic view function decorators
  5. AUTHOR:
  6. lambdalisue[Ali su ae] (lambdalisue@hashnote.net)
  7. License:
  8. The MIT License (MIT)
  9. Copyright (c) 2012 Alisue allright reserved.
  10. Permission is hereby granted, free of charge, to any person obtaining a copy
  11. of this software and associated documentation files (the "Software"), to
  12. deal in the Software without restriction, including without limitation the
  13. rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  14. sell copies of the Software, and to permit persons to whom the Software is
  15. furnished to do so, subject to the following conditions:
  16. The above copyright notice and this permission notice shall be included in
  17. all copies or substantial portions of the Software.
  18. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  23. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  24. IN THE SOFTWARE.
  25. """
  26. from __future__ import with_statement
  27. import copy
  28. import datetime
  29. from functools import wraps
  30. from django.http import Http404
  31. from django.utils.decorators import available_attrs
  32. from utils import redirect_to_login
  33. from utils import get_object_from_date_based_view
  34. from utils import get_object_from_list_detail_view
  35. __all__ = ['permission_required']
  36. def permission_required(perm, queryset=None, login_url=None, raise_exception=False):
  37. def wrapper(view_func):
  38. @wraps(view_func, assigned=available_attrs(view_func))
  39. def inner(request, *args, **kwargs):
  40. _kwargs = copy.copy(kwargs)
  41. # overwrite queryset if specified
  42. if queryset:
  43. _kwargs['queryset'] = queryset
  44. # get object from view
  45. if 'date_field' in kwargs:
  46. fn = get_object_from_date_based_view
  47. else:
  48. fn = get_object_from_list_detail_view
  49. if fn.validate(request, *args, **kwargs):
  50. obj = fn(request, *args, **kwargs)
  51. else:
  52. # required arguments is not passed
  53. obj = None
  54. if not request.user.has_perm(perm, obj=obj):
  55. return redirect_to_login(request, login_url, raise_exception)
  56. return view_func(request, *args, **kwargs)
  57. return inner
  58. return wrapper