Skip to content

Commit

Permalink
Optimization CookiesTokenAuthentication
Browse files Browse the repository at this point in the history
  • Loading branch information
EXG1O committed May 7, 2024
1 parent fecef00 commit 7e1a77e
Showing 1 changed file with 27 additions and 6 deletions.
33 changes: 27 additions & 6 deletions constructor_telegram_bots/authentication.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
from django.utils.translation import gettext as _

from rest_framework.authentication import TokenAuthentication
from rest_framework.authtoken.models import Token
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.request import Request

from users.models import User
Expand All @@ -19,12 +22,30 @@ class CookiesTokenAuthentication(TokenAuthentication):
auth-token=401f7ac837da42b97f613d789819ff93537bee6a
"""

def authenticate(self, request: Request) -> tuple[User, str] | None:
def get_token(self, key: str) -> Token:
return Token.objects.select_related('user').get(key=key)

def authenticate(self, request: Request) -> tuple[User, Token] | None:
auth_token: str | None = request.COOKIES.get('auth-token')

try:
token: Token = Token.objects.get(key=auth_token)
if auth_token:
try:
token: Token = self.get_token(auth_token)

return self.authenticate_credentials(token)
except Token.DoesNotExist:
pass

return super().authenticate(request)

def authenticate_credentials(self, token: Token | str) -> tuple[User, Token]:
if isinstance(token, str):
try:
token = self.get_token(token)
except Token.DoesNotExist:
raise AuthenticationFailed(_('Неверный токен.'))

if not token.user.is_active:
raise AuthenticationFailed(_('Пользователь неактивен или удалён.'))

return self.authenticate_credentials(token.key)
except Token.DoesNotExist:
return super().authenticate(request)
return (token.user, token)

0 comments on commit 7e1a77e

Please sign in to comment.