Co-authored-by: Tomek Wójcik <labs@tomekwojcik.pl> Co-committed-by: Tomek Wójcik <labs@tomekwojcik.pl>
37 lines
1.0 KiB
Python
37 lines
1.0 KiB
Python
# -*- coding: utf-8 -*-
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import typing
|
|
|
|
from django.contrib.auth.backends import ModelBackend, UserModel
|
|
from django.http import HttpRequest
|
|
|
|
from hotpocket_backend.apps.accounts.models import AccessToken, Account
|
|
|
|
LOGGER = logging.getLogger(__name__)
|
|
|
|
|
|
class AccessTokenBackend(ModelBackend):
|
|
def authenticate(self,
|
|
request: HttpRequest,
|
|
access_token: AccessToken | None,
|
|
) -> Account | None:
|
|
if not access_token:
|
|
return None
|
|
|
|
try:
|
|
user = UserModel.objects.get(pk=access_token.account_uuid)
|
|
except UserModel.DoesNotExist as exception:
|
|
LOGGER.error(
|
|
'Unhandled exception in AccessToken auth: %s',
|
|
exception,
|
|
exc_info=exception,
|
|
)
|
|
|
|
if self.user_can_authenticate(user) is False:
|
|
return None
|
|
|
|
request.access_token = access_token
|
|
return typing.cast(Account, user)
|