Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Creating a custom serializer for token creation #710

Open
prp-e opened this issue Jan 18, 2023 · 0 comments
Open

Creating a custom serializer for token creation #710

prp-e opened this issue Jan 18, 2023 · 0 comments

Comments

@prp-e
Copy link

prp-e commented Jan 18, 2023

Greetings.
I created this serializer:

from djoser.serializers import TokenCreateSerializer
from rest_framework.exceptions import ValidationError
from django.contrib.auth import authenticate
from djoser.conf import settings

class CustomTokenCreateSerializer(TokenCreateSerializer):
    password = serializers.CharField(required=False, style={"input_type": "password"})

    default_error_messages = {
        "invalid_credentials": "Invalid Email or Password, please try again",
        "inactive_account": "No active account found with given credentials",
    }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.user = None
        self.fields[settings.LOGIN_FIELD] = serializers.CharField(required=False)

    def validate(self, attrs):
        password = attrs.get("password")
        params = {settings.LOGIN_FIELD: attrs.get(settings.LOGIN_FIELD)}
        self.user = authenticate(
            request=self.context.get("request"), **params, password=password
        )
        if not self.user:
            self.user = User.objects.filter(**params).first()
            if self.user and not self.user.check_password(password):
                self.fail("invalid_credentials")
        if self.user and self.user.is_active:
            return attrs
        self.fail("invalid_credentials")

and I also made this view:

class CutomObtainPairView(TokenObtainPairView):
    serializer_class = CustomTokenCreateSerializer

and when I post the data responsible for creating the JWT token to the /jwt/create endpoint, it only returns username and password and not tokens.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant