Skip to content

Commit

Permalink
Merge pull request #133 from akutsuacts/fix/api-gateway-middleware
Browse files Browse the repository at this point in the history
Fix ApiGatewayMiddleWare in Python3
  • Loading branch information
Martijn Jacobs committed Sep 25, 2018
2 parents a3f845e + b6314a8 commit 3b9d890
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
2 changes: 2 additions & 0 deletions oscarapi/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

from oscar.core.loading import get_class

from rest_framework import HTTP_HEADER_ENCODING
from rest_framework import exceptions
from rest_framework import authentication

Expand Down Expand Up @@ -175,6 +176,7 @@ class ApiGatewayMiddleWare(MiddlewareMixin, IsApiRequest):
def process_request(self, request):
if self.is_api_request(request):
key = authentication.get_authorization_header(request)
key = key.decode(HTTP_HEADER_ENCODING)
if models.ApiKey.objects.filter(key=key).exists():
return None

Expand Down
38 changes: 38 additions & 0 deletions oscarapi/tests/test_middleware.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from django.core.exceptions import PermissionDenied
from django.urls import reverse
from django.test import RequestFactory, TestCase

from oscarapi.middleware import ApiGatewayMiddleWare
from oscarapi.models import ApiKey


class ApiGatewayMiddleWareTest(TestCase):

rf = RequestFactory()

def setUp(self):
super(ApiGatewayMiddleWareTest, self).setUp()

ApiKey.objects.create(key='testapikey')

def tearDown(self):
ApiKey.objects.filter(key='testapikey').delete()

super(ApiGatewayMiddleWareTest, self).tearDown()

def test_process_request(self):
basket_url = reverse('api-basket')

# without Authorization header
request = self.rf.get(basket_url)
with self.assertRaises(PermissionDenied):
ApiGatewayMiddleWare().process_request(request)

# invalid Authorization header
request = self.rf.get(basket_url, HTTP_AUTHORIZATION='wrongkey')
with self.assertRaises(PermissionDenied):
ApiGatewayMiddleWare().process_request(request)

# valid Authorization header
request = self.rf.get(basket_url, HTTP_AUTHORIZATION='testapikey')
self.assertIsNone(ApiGatewayMiddleWare().process_request(request))

0 comments on commit 3b9d890

Please sign in to comment.