Mark Lavin avatar Mark Lavin committed d353fc6

Add login required mixin. See #44.

Comments (0)

Files changed (2)

selectable/base.py

     'LookupBase',
     'ModelLookup',
     'AjaxRequiredMixin',
+    'LoginRequiredMixin',
 )
 
 
         if not request.is_ajax():
             return http.HttpResponseBadRequest()   
         return super(AjaxRequiredMixin, self).results(request)
+
+
+class LoginRequiredMixin(object):
+    "Lookup extension to require the user to be authenticated."
+
+    def results(self, request):
+        user = getattr(request, 'user', None)
+        if user is None or not user.is_authenticated():
+            return http.HttpResponse(status=401) # Unauthorized   
+        return super(LoginRequiredMixin, self).results(request)

selectable/tests/base.py

 from django.test import TestCase
 
 from mock import Mock
-from selectable.base import ModelLookup, AjaxRequiredMixin
+from selectable.base import ModelLookup, AjaxRequiredMixin, LoginRequiredMixin
 from selectable.tests import Thing
 
 __all__ = (
     'ModelLookupTestCase',
     'MultiFieldLookupTestCase',
     'AjaxRequiredLookupTestCase',
+    'LoginRequiredLookupTestCase',
 )
 
 
         request.is_ajax = lambda: False
         response = self.lookup.results(request)
         self.assertTrue(response.status_code, 400)
+
+
+class LoginRequiredLookupTestCase(BaseSelectableTestCase, LookupMixinTest):
+    
+    lookup_cls = SimpleModelLookup
+    lookup_mixin = LoginRequiredMixin
+
+    def setUp(self):
+        self.lookup = self.create_lookup_class()()
+    
+    def test_authenicated_call(self):
+        "Authenicated call should yield a successful response"
+        request = Mock()
+        user = Mock()
+        user.is_authenticated = lambda: True
+        request.user = user
+        response = self.lookup.results(request)
+        self.assertTrue(response.status_code, 200)
+
+    def test_non_authenicated_call(self):
+        "Non-Authenicated call should yield an unauthorized response"
+        request = Mock()
+        user = Mock()
+        user.is_authenticated = lambda: False
+        request.user = user
+        response = self.lookup.results(request)
+        self.assertTrue(response.status_code, 400)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.