Exemplo n.º 1
0
def test_check_password(user_account):
    user = user_account()
    user.set_password("CORRECT_PASSWORD")
    user.save(update_fields=("password", ))

    with pytest.raises(WrongPasswordError):
        PasswordService.check_password(user, "INCORRECT_PASSWORD")
Exemplo n.º 2
0
class ChangePasswordSerializer(serializers.Serializer):

    old_password = serializers.CharField(max_length=128,
                                         write_only=True,
                                         style={"input_type": "password"})
    new_password = serializers.CharField(max_length=128,
                                         write_only=True,
                                         style={"input_type": "password"})

    def __init__(self, *args, **kwargs):
        super(ChangePasswordSerializer, self).__init__(*args, **kwargs)
        self.request = self.context.get("request")
        self.user = getattr(self.request, "user", None)
        self.password_service = PasswordService()

    def validate_old_password(self, old_password):
        try:
            self.password_service.check_password(self.user, old_password)
        except WrongPasswordError as e:
            raise serializers.ValidationError(e.message) from e
        return old_password

    def validate_new_password(self, new_password):
        try:
            self.password_service.validate_password(new_password,
                                                    user=self.user)
        except InvalidPasswordError as e:
            raise serializers.ValidationError(e.messages) from e
        return new_password

    def create(self, validated_data):
        assert False, "Do not use update directly"

    def update(self, instance, validated_data):
        assert False, "Do not use update directly"

    def save(self, **kwargs):
        self.password_service.change_password(
            self.user, self.validated_data["new_password"])