inputlogic / django-api-starter

Boilerplate for starting Django DRF / API projects
2 stars 0 forks source link

Accept `email` in body instead of `username` for login #28

Closed staydecent closed 4 years ago

staydecent commented 5 years ago

The UserCustomObtainAuthToken view can set a custom serializer:

serializer_class = CustomAuthTokenSerializer

And the custom serializer (based on DRF AuthTokenSerializer):

class CustomAuthTokenSerializer(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'),
                                username=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