You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
34 lines
1.3 KiB
34 lines
1.3 KiB
from django.contrib.auth import authenticate |
|
from rest_framework import serializers |
|
from xenua.django.rest.views import UserScopedViewMixin |
|
|
|
from xenua.django.rest.models import Token |
|
|
|
|
|
class TokenSerializer(UserScopedViewMixin, serializers.ModelSerializer): |
|
password = serializers.CharField(style={'input_type': 'password'}, |
|
trim_whitespace=False, write_only=True, required=False) |
|
|
|
class Meta: |
|
model = Token |
|
fields = ('key', 'creation_date', 'password') |
|
read_only_fields = ('key', 'creation_date') |
|
|
|
def validate(self, attrs): |
|
username = self.context.get('request').user.username |
|
password = attrs.get('password') |
|
|
|
if username and password: |
|
user = authenticate(request=self.context['request'], |
|
username=username, password=password) |
|
|
|
if not user: |
|
raise serializers.ValidationError('unable to log in', code='authorization') |
|
|
|
else: |
|
raise serializers.ValidationError('include username and password for write operations', |
|
code='authorization') |
|
return {'user': user} |
|
|
|
def create(self, validated_data): |
|
return self.Meta.model.objects.create(**validated_data)
|
|
|