| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from django.http import HttpRequest |
| 4 |
|
| 5 |
from rest_framework import authentication |
| 6 |
from rest_framework.exceptions import AuthenticationFailed |
| 7 |
|
| 8 |
from allauth.headless import app_settings |
| 9 |
from allauth.headless.internal.sessionkit import authenticate_by_x_session_token |
| 10 |
|
| 11 |
|
| 12 |
class XSessionTokenAuthentication(authentication.BaseAuthentication): |
| 13 |
""" |
| 14 |
This authentication class uses the X-Session-Token that django-allauth |
| 15 |
is using for authentication purposes. |
| 16 |
""" |
| 17 |
|
| 18 |
def authenticate(self, request: HttpRequest): |
| 19 |
token = self.get_session_token(request) |
| 20 |
if token: |
| 21 |
return authenticate_by_x_session_token(token) |
| 22 |
return None |
| 23 |
|
| 24 |
def get_session_token(self, request: HttpRequest) -> str | None: |
| 25 |
""" |
| 26 |
Returns the session token for the given request, by looking up the |
| 27 |
``X-Session-Token`` header. Override this if you want to extract the token |
| 28 |
from e.g. the ``Authorization`` header. |
| 29 |
""" |
| 30 |
return request.headers.get("X-Session-Token") |
| 31 |
|
| 32 |
|
| 33 |
class JWTTokenAuthentication(authentication.TokenAuthentication): |
| 34 |
|
| 35 |
@property |
| 36 |
def keyword(self) -> str: |
| 37 |
""" |
| 38 |
See: ``settings.HEADLESS_JWT_AUTHORIZATION_HEADER_SCHEME``. |
| 39 |
""" |
| 40 |
return app_settings.JWT_AUTHORIZATION_HEADER_SCHEME |
| 41 |
|
| 42 |
def authenticate_credentials(self, key: str): |
| 43 |
""" |
| 44 |
Validates the given access token. |
| 45 |
""" |
| 46 |
from allauth.headless.tokens.strategies.jwt.internal import ( |
| 47 |
validate_access_token, |
| 48 |
) |
| 49 |
|
| 50 |
user_payload = validate_access_token(key) |
| 51 |
if user_payload is None: |
| 52 |
raise AuthenticationFailed("Invalid token.") |
| 53 |
return user_payload |