Last active
October 23, 2021 10:30
-
-
Save jsmedmar/d846eee063fa23148f8a87313dd590a3 to your computer and use it in GitHub Desktop.
A django LoginRequiredMixin that allows token authentication.
This file contains 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
from django.contrib.auth import mixins | |
from rest_framework.authentication import SessionAuthentication | |
from rest_framework.authentication import TokenAuthentication | |
from rest_framework import generics | |
class TokenLoginRequiredMixin(mixins.LoginRequiredMixin): | |
"""A login required mixin that allows token authentication.""" | |
def dispatch(self, request, *args, **kwargs): | |
"""If token was provided, ignore authenticated status.""" | |
http_auth = request.META.get("HTTP_AUTHORIZATION") | |
if http_auth and "Token" in http_auth: | |
pass | |
elif not request.user.is_authenticated: | |
return self.handle_no_permission() | |
return super(mixins.LoginRequiredMixin, self).dispatch( | |
request, *args, **kwargs) | |
class ListAPIView(TokenLoginRequiredMixin, generics.ListAPIView): | |
"""This view suppot both token and session authentication.""" | |
authentication_classes = [ | |
SessionAuthentication, | |
TokenAuthentication, | |
] |
For usage with the GraphQL views: graphql-python/graphene#249 (comment)
If you are using generics.ListAPIView why would you need to override the token auth provided by authentication.TokenAuthentication? Also, is this only bypassing token validation? How is it secure? I'm a bit confused.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! It's a really useful snippet.