Skip to content

Instantly share code, notes, and snippets.

@BrockHerion
Last active August 27, 2020 00:59
Show Gist options
  • Save BrockHerion/558676b77099beef4f3cb0c181a96c12 to your computer and use it in GitHub Desktop.
Save BrockHerion/558676b77099beef4f3cb0c181a96c12 to your computer and use it in GitHub Desktop.
User Login Serializer
from rest_framework import serializers
from rest_framework_simplejwt.tokens import RefreshToken
class UserLoginSerializer(serializers.Serializer):
email = serializers.EmailField()
password = serializers.CharField(max_length=128, write_only=True)
access = serializers.CharField(read_only=True)
refresh = serializers.CharField(read_only=True)
role = serializers.CharField(read_only=True)
def create(self, validated_date):
pass
def update(self, instance, validated_data):
pass
def validate(self, data):
email = data['email']
password = data['password']
user = authenticate(email=email, password=password)
if user is None:
raise serializers.ValidationError("Invalid login credentials")
try:
refresh = RefreshToken.for_user(user)
refresh_token = str(refresh)
access_token = str(refresh.access_token)
update_last_login(None, user)
validation = {
'access': access_token,
'refresh': refresh_token,
'email': user.email,
'role': user.role,
}
return validation
except AuthUser.DoesNotExist:
raise serializers.ValidationError("Invalid login credentials")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment