Last active
November 30, 2024 16:26
-
-
Save pizzapanther/dae8f5c9c5f680d3cef4ea715b1853a6 to your computer and use it in GitHub Desktop.
Django Ninja Headless Allauth Authentication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Django Ninja authentication using django-allauth headless sessions | |
from ninja.security.session import SessionAuth | |
from allauth.headless import app_settings | |
from allauth.headless.internal.authkit import purge_request_user_cache | |
class AllAuthHeadless(SessionAuth): | |
def authenticate(self, request, key=None): | |
strategy = app_settings.TOKEN_STRATEGY | |
session_token = strategy.get_session_token(request) | |
if session_token: | |
session = strategy.lookup_session(session_token) | |
if session: | |
user_id = session.get('_auth_user_id', None) | |
backend_path = session.get('_auth_user_backend', None) | |
if user_id and backend_path in settings.AUTHENTICATION_BACKENDS: | |
backend = load_backend(backend_path) | |
user = backend.get_user(user_id) | |
if user.is_authenticated: | |
purge_request_user_cache(request) | |
request.user = user | |
request.api_session = session | |
return user | |
if request.user.is_authenticated: | |
return request.user | |
return None | |
allauth_headless = AllAuthHeadless() | |
# Usage: api_v1 = NinjaAPI(title="My V1 API", auth=allauth_headless) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment