Fix integer division
[pgweb/local.git] / dep / django-selectable / selectable / decorators.py
bloba831a007dc421be88be8d35a420a04cc30322ad9
1 "Decorators for additional lookup functionality."
2 from __future__ import unicode_literals
4 from functools import wraps
6 from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden
9 __all__ = (
10 'ajax_required',
11 'login_required',
12 'staff_member_required',
16 def results_decorator(func):
17 """
18 Helper for constructing simple decorators around Lookup.results.
20 func is a function which takes a request as the first parameter. If func
21 returns an HttpReponse it is returned otherwise the original Lookup.results
22 is returned.
23 """
24 # Wrap function to maintian the original doc string, etc
25 @wraps(func)
26 def decorator(lookup_cls):
27 # Construct a class decorator from the original function
28 original = lookup_cls.results
29 def inner(self, request):
30 # Wrap lookup_cls.results by first calling func and checking the result
31 result = func(request)
32 if isinstance(result, HttpResponse):
33 return result
34 return original(self, request)
35 # Replace original lookup_cls.results with wrapped version
36 lookup_cls.results = inner
37 return lookup_cls
38 # Return the constructed decorator
39 return decorator
42 @results_decorator
43 def ajax_required(request):
44 "Lookup decorator to require AJAX calls to the lookup view."
45 if not request.is_ajax():
46 return HttpResponseBadRequest()
49 @results_decorator
50 def login_required(request):
51 "Lookup decorator to require the user to be authenticated."
52 user = getattr(request, 'user', None)
53 if user is None or not user.is_authenticated():
54 return HttpResponse(status=401) # Unauthorized
57 @results_decorator
58 def staff_member_required(request):
59 "Lookup decorator to require the user is a staff member."
60 user = getattr(request, 'user', None)
61 if user is None or not user.is_authenticated():
62 return HttpResponse(status=401) # Unauthorized
63 elif not user.is_staff:
64 return HttpResponseForbidden()