django-rest-framework/rest_framework/authtoken/serializers.py
Marlon 670b0b710b Use serializers.ValidationError
Per django rest framework docs, and to prevent confusion with Django's ValidationError, `serializers.ValidationError` is preferred to `exceptions.ValidationError`.
2015-09-30 21:09:37 -05:00

31 lines
1023 B
Python

from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class AuthTokenSerializer(serializers.Serializer):
username = serializers.CharField()
password = serializers.CharField(style={'input_type': 'password'})
def validate(self, attrs):
username = attrs.get('username')
password = attrs.get('password')
if username and password:
user = authenticate(username=username, password=password)
if user:
if not user.is_active:
msg = _('User account is disabled.')
raise serializers.ValidationError(msg)
else:
msg = _('Unable to log in with provided credentials.')
raise serializers.ValidationError(msg)
else:
msg = _('Must include "username" and "password".')
raise serializers.ValidationError(msg)
attrs['user'] = user
return attrs