2022-12-10 23:25:48 -08:00
|
|
|
from django.http import HttpResponse
|
|
|
|
|
|
|
|
from api.models import Token
|
|
|
|
|
|
|
|
|
|
|
|
class ApiTokenMiddleware:
|
|
|
|
"""
|
|
|
|
Adds request.user and request.identity if an API token appears.
|
|
|
|
Also nukes request.session so it can't be used accidentally.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self, get_response):
|
|
|
|
self.get_response = get_response
|
|
|
|
|
|
|
|
def __call__(self, request):
|
|
|
|
auth_header = request.headers.get("authorization", None)
|
2023-02-19 10:37:02 -08:00
|
|
|
request.token = None
|
2023-05-04 10:50:17 -07:00
|
|
|
request.identity = None
|
2022-12-10 23:25:48 -08:00
|
|
|
if auth_header and auth_header.startswith("Bearer "):
|
|
|
|
token_value = auth_header[7:]
|
2023-03-06 14:48:43 -08:00
|
|
|
if token_value == "__app__":
|
|
|
|
# Special client app token value
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
token = Token.objects.get(token=token_value, revoked=None)
|
|
|
|
except Token.DoesNotExist:
|
|
|
|
return HttpResponse("Invalid Bearer token", status=400)
|
|
|
|
request.user = token.user
|
|
|
|
request.identity = token.identity
|
|
|
|
request.token = token
|
2022-12-10 23:25:48 -08:00
|
|
|
request.session = None
|
|
|
|
response = self.get_response(request)
|
|
|
|
return response
|