Skip to content

Instantly share code, notes, and snippets.

@jamesalbert
Created July 31, 2018 20:04
Show Gist options
  • Save jamesalbert/ac11370b4209674549d1824f17168a37 to your computer and use it in GitHub Desktop.
Save jamesalbert/ac11370b4209674549d1824f17168a37 to your computer and use it in GitHub Desktop.
Django AuthTokenSerializer that requires only an email and password (instead of username).
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
from rest_framework.compat import authenticate
class AuthTokenSerializer(serializers.Serializer):
email = serializers.CharField(label=_("Email"))
password = serializers.CharField(
label=_("Password"),
style={'input_type': 'password'},
trim_whitespace=False
)
def validate(self, attrs):
email = attrs.get('email')
password = attrs.get('password')
if email and password:
user = authenticate(request=self.context.get('request'),
email=email, password=password)
# The authenticate call simply returns None for is_active=False
# users. (Assuming the default ModelBackend authentication
# backend.)
if not user:
msg = _('Unable to log in with provided credentials.')
raise serializers.ValidationError(msg, code='authorization')
else:
msg = _('Must include "email" and "password".')
raise serializers.ValidationError(msg, code='authorization')
attrs['user'] = user
return attrs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment