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

Allow overriding UidAndTokenSerializer's behaviour #692

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 18 additions & 16 deletions djoser/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,30 +170,32 @@ class UidAndTokenSerializer(serializers.Serializer):
"invalid_uid": settings.CONSTANTS.messages.INVALID_UID_ERROR,
}

def validate(self, attrs):
validated_data = super().validate(attrs)

# uid validation have to be here, because validate_<field_name>
# doesn't work with modelserializer
def validate_uid(self, value):
try:
uid = utils.decode_uid(self.initial_data.get("uid", ""))
self.user = User.objects.get(pk=uid)
except (User.DoesNotExist, ValueError, TypeError, OverflowError):
key_error = "invalid_uid"
raise ValidationError(
{"uid": [self.error_messages[key_error]]}, code=key_error
)

raise ValidationError(self.error_messages[key_error])
return value

def validate_token(self, value):
"""
- The order of the validation matters.
- self.user must have already been set by 'validate_uid'
- In the future, if for whatever reason, rest_framework
decided to change the order of the validation, then this
method must been changed accordingly. Alternatively,
it's also possible to use one of hasattr(self, 'user') or
getattr(self, 'user', None) to prevent an unexpected behavior.
"""
is_token_valid = self.context["view"].token_generator.check_token(
self.user, self.initial_data.get("token", "")
self.user, value
)
if is_token_valid:
return validated_data
else:
if not is_token_valid:
key_error = "invalid_token"
raise ValidationError(
{"token": [self.error_messages[key_error]]}, code=key_error
)
raise ValidationError(self.error_messages[key_error])
return value


class ActivationSerializer(UidAndTokenSerializer):
Expand Down