47 lines
1.7 KiB
Python
47 lines
1.7 KiB
Python
import functools
|
|
import logging
|
|
|
|
from django.http import HttpResponseForbidden
|
|
from django.views.decorators.csrf import csrf_exempt
|
|
|
|
from mydata_benchmarks.models import ClientToken
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
def client_token_required(view_func):
|
|
"""Decorator which ensures the client has provided a valid token."""
|
|
|
|
my_log = log.getChild('client_token_required')
|
|
|
|
@csrf_exempt
|
|
@functools.wraps(view_func)
|
|
def _wrapped_view(request, *args, **kwargs):
|
|
auth_header = request.META.get('HTTP_AUTHORIZATION')
|
|
|
|
if not auth_header:
|
|
my_log.debug('Request without Authorization header')
|
|
return HttpResponseForbidden("Must include Bearer token authorization with request.")
|
|
|
|
if not auth_header.startswith('Bearer '):
|
|
my_log.debug('Authorization header has no Bearer token: %r', auth_header)
|
|
return HttpResponseForbidden("Must include Bearer token authorization with request.")
|
|
|
|
auth_string = auth_header[7:].strip()
|
|
if not auth_string:
|
|
my_log.debug('Authorization header has empty bearer token: %r', auth_header)
|
|
return HttpResponseForbidden("Must include Bearer token authorization with request.")
|
|
|
|
try:
|
|
token = ClientToken.objects.get(token=auth_string)
|
|
except ClientToken.DoesNotExist:
|
|
my_log.debug('Authorization header contains non-existant bearer token: %r', auth_string)
|
|
return HttpResponseForbidden("Token invalid or revoked.")
|
|
|
|
request.user = token.user
|
|
my_log.debug('Logging in user %s via Bearer token', token.user)
|
|
|
|
return view_func(request, *args, **kwargs)
|
|
|
|
return _wrapped_view
|