hotpocket/services/backend/hotpocket_backend/apps/accounts/middleware.py
Tomek Wójcik b6d02dbe78 BTHLABS-50: Safari Web extension
Co-authored-by: Tomek Wójcik <labs@tomekwojcik.pl>
Co-committed-by: Tomek Wójcik <labs@tomekwojcik.pl>
2025-09-08 18:11:36 +00:00

43 lines
1.4 KiB
Python

# -*- coding: utf-8 -*-
from __future__ import annotations
import logging
from django.contrib import auth
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpRequest
from django.utils.deprecation import MiddlewareMixin
from hotpocket_backend.apps.accounts.models import AccessToken, Account
LOGGER = logging.getLogger(__name__)
class AccessTokenMiddleware(MiddlewareMixin):
def process_request(self, request: HttpRequest):
if not hasattr(request, 'user'):
raise ImproperlyConfigured('No `AuthenticationMiddleware`?')
authorization_header = request.headers.get('Authorization', None)
if authorization_header is None:
return
try:
scheme, authorization = authorization_header.split(' ', maxsplit=1)
assert scheme == 'Bearer', (
f'Unsupported authorization scheme: `{scheme}`'
)
access_token = AccessToken.active_objects.get(key=authorization)
except (ValueError, AssertionError, AccessToken.DoesNotExist, Account.DoesNotExist) as exception:
LOGGER.error(
'Unhandled exception in AccessToken middleware: %s',
exception,
exc_info=exception,
)
return
account = auth.authenticate(request, access_token=access_token)
if account:
request.user = account