Last active
November 28, 2019 09:19
-
-
Save RockingRolli/79ceab04adb72c106cd6 to your computer and use it in GitHub Desktop.
DRF token auth with mongoengine
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 rest_framework.authentication import TokenAuthentication | |
from .models import MongoToken | |
from rest_framework import exceptions | |
class MongoTokenAuthentication(TokenAuthentication): | |
model = MongoToken | |
def authenticate_credentials(self, key): | |
try: | |
token = self.model.objects.get(key=key.decode('UTF-8')) | |
except self.model.DoesNotExist: | |
raise exceptions.AuthenticationFailed('Invalid token') | |
if not token.user.is_active: | |
raise exceptions.AuthenticationFailed('User inactive or deleted') | |
return (token.user, token) |
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
import binascii | |
import os | |
from django.conf import settings | |
from django.utils.timezone import now | |
from mongoengine import Document, StringField, ReferenceField | |
from mongoengine.fields import DateTimeField | |
AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.user') | |
class MongoToken(Document): | |
key = StringField(max_length=44) | |
user = ReferenceField('PortalUser', required=True) | |
created = DateTimeField() | |
def __init__(self, *args, **values): | |
super().__init__(*args, **values) | |
if not self.key: | |
self.key = self.generate_key() | |
def save(self, *args, **kwargs): | |
if not self.id: | |
self.created = now() | |
return super().save(*args, **kwargs) | |
def generate_key(self): | |
return binascii.hexlify(os.urandom(22)).decode() | |
def __unicode__(self): | |
return self.key |
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 rest_framework.authtoken.views import ObtainAuthToken | |
from rest_framework import status | |
from rest_framework.response import Response | |
from .models import MongoToken | |
class ObtainMongoAuthToken(ObtainAuthToken): | |
model = MongoToken | |
def post(self, request): | |
serializer = self.serializer_class(data=request.DATA) | |
if serializer.is_valid(): | |
token, created = self.model.objects.get_or_create(user=serializer.object['user']) | |
return Response({'token': token.key}) | |
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) | |
obtain_mongo_auth_token = ObtainMongoAuthToken.as_view() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Roland,
Thanks for putting this up.
I am facing error while trying to integrate this in my project. In the
urls.py
for the app, I makelogin
point to the view you suggested above:However, when I post username and password to
/api/login/
it fails with belowAttributeError
:Below is the complete traceback:
It is my first attempt at working with
mongoengine
. So I might be making some naive mistake.