From fc5d4aa74597a5d718b9c7838a61c625b36a957d Mon Sep 17 00:00:00 2001 From: jsa Date: Tue, 30 Jul 2013 17:13:48 -0400 Subject: [PATCH] make user_api compatible with HTTP basic auth --- lms/djangoapps/user_api/tests/test_views.py | 14 ++++++++++++++ lms/djangoapps/user_api/views.py | 3 +++ 2 files changed, 17 insertions(+) diff --git a/lms/djangoapps/user_api/tests/test_views.py b/lms/djangoapps/user_api/tests/test_views.py index 075c1f0d9f..451b167050 100644 --- a/lms/djangoapps/user_api/tests/test_views.py +++ b/lms/djangoapps/user_api/tests/test_views.py @@ -1,3 +1,5 @@ +import base64 + from django.contrib.auth.models import User from django.test import TestCase from django.test.utils import override_settings @@ -31,6 +33,9 @@ class UserApiTestCase(TestCase): UserPreferenceFactory.create(user=self.users[1], key="key0") ] + def basic_auth(self, username, password): + return {'HTTP_AUTHORIZATION': 'Basic ' + base64.b64encode('%s:%s' % (username, password))} + def request_with_auth(self, method, *args, **kwargs): """Issue a get request to the given URI with the API key header""" return getattr(self.client, method)(*args, HTTP_X_EDX_API_KEY=TEST_API_KEY, **kwargs) @@ -127,6 +132,15 @@ class UserViewSetTest(UserApiTestCase): def test_debug_auth(self): self.assertHttpOK(self.client.get(self.LIST_URI)) + @override_settings(DEBUG=False) + @override_settings(EDX_API_KEY=TEST_API_KEY) + def test_basic_auth(self): + # ensure that having basic auth headers in the mix does not break anything + self.assertHttpOK( + self.request_with_auth("get", self.LIST_URI, **self.basic_auth('someuser', 'somepass'))) + self.assertHttpForbidden( + self.client.get(self.LIST_URI, **self.basic_auth('someuser', 'somepass'))) + def test_get_list_empty(self): User.objects.all().delete() result = self.get_json(self.LIST_URI) diff --git a/lms/djangoapps/user_api/views.py b/lms/djangoapps/user_api/views.py index d4f19be099..c64a5a4d23 100644 --- a/lms/djangoapps/user_api/views.py +++ b/lms/djangoapps/user_api/views.py @@ -1,5 +1,6 @@ from django.conf import settings from django.contrib.auth.models import User +from rest_framework import authentication from rest_framework import filters from rest_framework import permissions from rest_framework import viewsets @@ -25,6 +26,7 @@ class ApiKeyHeaderPermission(permissions.BasePermission): class UserViewSet(viewsets.ReadOnlyModelViewSet): + authentication_classes = (authentication.SessionAuthentication,) permission_classes = (ApiKeyHeaderPermission,) queryset = User.objects.all() serializer_class = UserSerializer @@ -33,6 +35,7 @@ class UserViewSet(viewsets.ReadOnlyModelViewSet): class UserPreferenceViewSet(viewsets.ReadOnlyModelViewSet): + authentication_classes = (authentication.SessionAuthentication,) permission_classes = (ApiKeyHeaderPermission,) queryset = UserPreference.objects.all() filter_backends = (filters.DjangoFilterBackend,)