Skip to content

Commit

Permalink
add serializer for auth token
Browse files Browse the repository at this point in the history
  • Loading branch information
iameraj committed Jan 3, 2024
1 parent 8dbd966 commit aac1022
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
1 change: 1 addition & 0 deletions app/myproject/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
"django.contrib.staticfiles",
"core.apps.CoreConfig",
"rest_framework",
"rest_framework.authtoken",
"drf_spectacular",
"user.apps.UserConfig",
]
Expand Down
32 changes: 31 additions & 1 deletion app/user/serializers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
"""
Serializers for API view
"""
from django.contrib.auth import get_user_model
from django.contrib.auth import (
get_user_model,
authenticate,
)
from rest_framework import serializers
from django.utils.translation import gettext as _


class UserSerializer(serializers.ModelSerializer):
Expand All @@ -16,3 +20,29 @@ class Meta:
def create(self, validated_data):
"""Created and return a user with encrypted password"""
return get_user_model().objects.create_user(**validated_data)


class AuthTokenSerializer(serializers.Serializer):
"""Serializer for the user authentication token"""

email = serializers.EmailField()
password = serializers.CharField(
style={"input_type": "password"},
trim_whitespace=False,
)

def validate(self, attrs):
email = attrs.get("email")
password = attrs.get("password")
user = authenticate(
request=self.context.get("request"),
username=email,
password=password,
)

if not user:
msg = _("Unable to authenticate with provided credentials")
raise serializers.ValidationError(msg, code="authorization")

attrs["user"] = user
return attrs

0 comments on commit aac1022

Please sign in to comment.