serializers.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from django.contrib.auth import authenticate
  2. from django.utils.translation import gettext_lazy as _
  3. from rest_framework import serializers
  4. class AuthTokenSerializer(serializers.Serializer):
  5. username = serializers.CharField(
  6. label=_("Username"),
  7. write_only=True
  8. )
  9. password = serializers.CharField(
  10. label=_("Password"),
  11. style={'input_type': 'password'},
  12. trim_whitespace=False,
  13. write_only=True
  14. )
  15. token = serializers.CharField(
  16. label=_("Token"),
  17. read_only=True
  18. )
  19. def validate(self, attrs):
  20. username = attrs.get('username')
  21. password = attrs.get('password')
  22. if username and password:
  23. user = authenticate(request=self.context.get('request'),
  24. username=username, password=password)
  25. # The authenticate call simply returns None for is_active=False
  26. # users. (Assuming the default ModelBackend authentication
  27. # backend.)
  28. if not user:
  29. msg = _('Unable to log in with provided credentials.')
  30. raise serializers.ValidationError(msg, code='authorization')
  31. else:
  32. msg = _('Must include "username" and "password".')
  33. raise serializers.ValidationError(msg, code='authorization')
  34. attrs['user'] = user
  35. return attrs