iMerica / dj-rest-auth

Authentication for Django Rest Framework
https://dj-rest-auth.readthedocs.io/en/latest/index.html
MIT License
1.63k stars 304 forks source link

Support custom verification status based on email #504

Closed c-w closed 1 year ago

c-w commented 1 year ago

What does this change do?

This pull request extends the interface of LoginSerializer.validate_email_verification_status to pass-through the email value that's used for the current login. This interface change enables us to customize the logic to check the verification status in subclasses without needing to override the full validate method, thus reducing coupling between subclasses and the parent.

Why is this useful?

I'm working on a system where the user is allowed to change their email but they need to verify their new email before they can use it to log in. Currently, dj-rest-auth will allow the user to log in with their new email address even before it's verified as the code is checking that the user has any verified email address. I want to customize this behavior by subclassing to check that the specific email address the user is logging in with is verified:

class MyLoginSerializer(LoginSerializer):
    @staticmethod
    def validate_email_verification_status(user, email=None):
        if not user.emailaddress_set.filter(email=email, verified=True).exists():
            raise serializers.ValidationError(_('E-mail is not verified.'))

Arguably dj-rest-auth could even make this check the default behavior as it seems semantically correct, but this would be a backwards incompatible change which is why I propose the change in this PR to simply extend the interface of the validation function.