2014-05-01 13:18:16 +04:00
|
|
|
from django.utils.translation import ugettext_lazy as _
|
|
|
|
|
2015-10-01 05:09:37 +03:00
|
|
|
from rest_framework import serializers
|
2017-10-05 12:43:49 +03:00
|
|
|
from rest_framework.compat import authenticate
|
2012-11-11 04:09:14 +04:00
|
|
|
|
2012-12-08 02:25:16 +04:00
|
|
|
|
2012-11-11 04:09:14 +04:00
|
|
|
class AuthTokenSerializer(serializers.Serializer):
|
2016-02-01 11:20:16 +03:00
|
|
|
username = serializers.CharField(label=_("Username"))
|
2017-05-17 22:17:55 +03:00
|
|
|
password = serializers.CharField(
|
|
|
|
label=_("Password"),
|
|
|
|
style={'input_type': 'password'},
|
|
|
|
trim_whitespace=False
|
|
|
|
)
|
2012-11-11 04:09:14 +04:00
|
|
|
|
|
|
|
def validate(self, attrs):
|
|
|
|
username = attrs.get('username')
|
|
|
|
password = attrs.get('password')
|
|
|
|
|
|
|
|
if username and password:
|
2017-10-05 12:43:49 +03:00
|
|
|
user = authenticate(request=self.context.get('request'),
|
|
|
|
username=username, password=password)
|
2012-11-11 04:09:14 +04:00
|
|
|
|
|
|
|
if user:
|
2016-10-10 15:03:46 +03:00
|
|
|
# From Django 1.10 onwards the `authenticate` call simply
|
|
|
|
# returns `None` for is_active=False users.
|
|
|
|
# (Assuming the default `ModelBackend` authentication backend.)
|
2012-11-11 04:09:14 +04:00
|
|
|
if not user.is_active:
|
2015-01-07 15:46:23 +03:00
|
|
|
msg = _('User account is disabled.')
|
2016-10-11 12:25:21 +03:00
|
|
|
raise serializers.ValidationError(msg, code='authorization')
|
2012-11-11 04:09:14 +04:00
|
|
|
else:
|
2015-01-07 15:46:23 +03:00
|
|
|
msg = _('Unable to log in with provided credentials.')
|
2016-10-11 12:25:21 +03:00
|
|
|
raise serializers.ValidationError(msg, code='authorization')
|
2012-11-11 04:09:14 +04:00
|
|
|
else:
|
2015-01-07 15:46:23 +03:00
|
|
|
msg = _('Must include "username" and "password".')
|
2016-10-11 12:25:21 +03:00
|
|
|
raise serializers.ValidationError(msg, code='authorization')
|
2014-09-02 20:41:23 +04:00
|
|
|
|
|
|
|
attrs['user'] = user
|
|
|
|
return attrs
|