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