Skip to content
Browse files

Add auth middleware.

  • Loading branch information...
1 parent 7437e06 commit 7fc26d583bb3716f2b36deeadcd1d1e4a71ec1c2 @neaf neaf committed
View
11 detector/accounts/decorators.py
@@ -0,0 +1,11 @@
+from functools import wraps
+from django.http import HttpResponse
+
+def authenticate(func):
+ @wraps
+ def auth_request(request, *args, **kwargs):
+ if request.user:
+ return func(request, *args, **kwargs)
+ else:
+ return HttpResponse(status=401)
+ return auth_request
View
13 detector/accounts/middlewares.py
@@ -0,0 +1,13 @@
+from django.http import HttpResponse
+from accounts.models import User
+
+class AuthenticatorMiddleware(object):
+ def process_request(self, request):
+ request.user = None
+ token = request.META.get('HTTP_X_TOKEN')
+ if token:
+ try:
+ user = User.objects.get(token=token)
+ request.user = user
+ except User.DoesNotExist:
+ pass
View
1 detector/accounts/tests/__init__.py
@@ -1,2 +1,3 @@
from detector.accounts.tests.models import *
from detector.accounts.tests.views import *
+from detector.accounts.tests.middlewares import *
View
30 detector/accounts/tests/middlewares.py
@@ -0,0 +1,30 @@
+from uuid import uuid4
+from django.test import TestCase
+from django.test.client import RequestFactory
+from accounts.middlewares import AuthenticatorMiddleware
+from accounts.models import generate_token, User
+
+class AuthenticatorMiddlewareTest(TestCase):
+ client_class = RequestFactory
+
+ def test_existing_user(self):
+ user = User.objects.create(
+ github_username = 'octocat',
+ token=generate_token()
+ )
+ request = self.client.get("/", HTTP_X_TOKEN=user.token)
+ auth_middleware = AuthenticatorMiddleware()
+ auth_middleware.process_request(request)
+ self.assertEqual(request.user, user)
+
+ def test_not_existing_user(self):
+ request = self.client.get("/", HTTP_X_TOKEN=uuid4())
+ auth_middleware = AuthenticatorMiddleware()
+ resp = auth_middleware.process_request(request)
+ self.assertIsNone(request.user)
+
+ def test_missing_header(self):
+ request = self.client.get("/")
+ auth_middleware = AuthenticatorMiddleware()
+ resp = auth_middleware.process_request(request)
+ self.assertIsNone(request.user)
View
5 detector/settings.py
@@ -97,10 +97,7 @@
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
- 'django.contrib.sessions.middleware.SessionMiddleware',
- 'django.middleware.csrf.CsrfViewMiddleware',
- 'django.contrib.auth.middleware.AuthenticationMiddleware',
- 'django.contrib.messages.middleware.MessageMiddleware',
+ 'detector.accounts.middlewares.AuthenticatorMiddleware',
)
ROOT_URLCONF = 'detector.urls'

0 comments on commit 7fc26d5

Please sign in to comment.
Something went wrong with that request. Please try again.