django.contrib.auth.password_validation.validate_password

Here are the examples of the python api django.contrib.auth.password_validation.validate_password taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

79 Examples 7

3 Source : forms.py
with GNU General Public License v3.0
from Aghoreshwar

    def _post_clean(self):
        super()._post_clean()
        # Validate the password after self.instance is updated with form data
        # by super().
        password = self.cleaned_data.get('password2')
        if password:
            try:
                password_validation.validate_password(password, self.instance)
            except forms.ValidationError as error:
                self.add_error('password2', error)

    def save(self, commit=True):

3 Source : forms.py
with GNU General Public License v3.0
from Aghoreshwar

    def clean_new_password2(self):
        password1 = self.cleaned_data.get('new_password1')
        password2 = self.cleaned_data.get('new_password2')
        if password1 and password2:
            if password1 != password2:
                raise forms.ValidationError(
                    self.error_messages['password_mismatch'],
                    code='password_mismatch',
                )
        password_validation.validate_password(password2, self.user)
        return password2

    def save(self, commit=True):

3 Source : forms.py
with GNU General Public License v3.0
from Aghoreshwar

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2:
            if password1 != password2:
                raise forms.ValidationError(
                    self.error_messages['password_mismatch'],
                    code='password_mismatch',
                )
        password_validation.validate_password(password2, self.user)
        return password2

    def save(self, commit=True):

3 Source : forms.py
with MIT License
from Air-999

    def _post_clean(self):
        super()._post_clean()
        # Validate the password after self.instance is updated with form data
        # by super().
        password = self.cleaned_data.get('password2')
        if password:
            try:
                password_validation.validate_password(password, self.instance)
            except ValidationError as error:
                self.add_error('password2', error)

    def save(self, commit=True):

3 Source : forms.py
with MIT License
from Air-999

    def clean_new_password2(self):
        password1 = self.cleaned_data.get('new_password1')
        password2 = self.cleaned_data.get('new_password2')
        if password1 and password2:
            if password1 != password2:
                raise ValidationError(
                    self.error_messages['password_mismatch'],
                    code='password_mismatch',
                )
        password_validation.validate_password(password2, self.user)
        return password2

    def save(self, commit=True):

3 Source : forms.py
with MIT License
from Air-999

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2:
            if password1 != password2:
                raise ValidationError(
                    self.error_messages['password_mismatch'],
                    code='password_mismatch',
                )
        password_validation.validate_password(password2, self.user)
        return password2

    def save(self, commit=True):

3 Source : serializers.py
with MIT License
from arcturus5340

    def validate(self, data):
        user = auth.get_user_model()(**data)
        password = data.get('password')
        errors = dict()
        try:
            validators.validate_password(password=password, user=user)

        except exceptions.ValidationError as e:
            errors['password'] = list(e.messages)

        if errors:
            raise serializers.ValidationError(errors)

        return super(BasicUserSerializer, self).validate(data)


class FullUserSerializer(BasicUserSerializer):

3 Source : forms.py
with MIT License
from betagouv

    def _post_clean(self):
        super()._post_clean()
        # Validate the password after self.instance is updated with form data
        # by super().
        password = self.cleaned_data.get("password")
        if password:
            try:
                password_validation.validate_password(password, self.instance)
            except forms.ValidationError as error:
                self.add_error("password", error)

    def save(self, commit=True):

3 Source : serializers.py
with GNU General Public License v3.0
from buildlyio

    def validate(self, attrs):

        attrs = super().validate(attrs)

        password1 = attrs.get('new_password1')
        password2 = attrs.get('new_password2')
        if password1 != password2:
            raise serializers.ValidationError("The two password fields didn't match.")
        password_validation.validate_password(password2, self.user)

        return attrs

    def save(self):

3 Source : forms.py
with MIT License
from cds-snc

    def _post_clean(self):
        super()._post_clean()
        # Validate the password after self.instance is updated with form data
        # by super().
        password = self.cleaned_data.get("password1")
        if password:
            try:
                password_validation.validate_password(password, self.user)
            except ValidationError as error:
                self.add_error("password1", error)

    def save(self, commit=True):

3 Source : forms.py
with MIT License
from cds-snc

    def clean_new_password1(self):
        password1 = self.cleaned_data.get("new_password1")
        # We can't use clean_data for password2, it hasn't been cleaned yet
        password2 = self.data.get("new_password2")
        if password1 and password2:
            if password1 != password2:
                raise ValidationError(
                    self.error_messages["password_mismatch"],
                    code="password_mismatch",
                )
        password_validation.validate_password(password1, self.user)
        return password1

    def clean_new_password2(self):

3 Source : forms.py
with MIT License
from cds-snc

    def _post_clean(self):
        # This function is the same as UserCreationForm._post_clean, except we
        # are pinning the error on field password1 instead of password2 for
        # accessibility reasons
        forms.ModelForm._post_clean(self)
        # Validate the password after self.instance is updated with form data
        # by super().
        password = self.cleaned_data.get("password1")
        if password:
            try:
                password_validation.validate_password(password, self.instance)
            except ValidationError as error:
                self.add_error("password1", error)

    @inject

3 Source : createdefaultsuperuser.py
with MIT License
from cds-snc

    def create_su(self):
        # Check to ensure SU password meets minimum requirements
        # If the password does not meet validation a Validation Error is raised by
        # the validate_password function.
        # https://docs.djangoproject.com/en/3.0/topics/auth/passwords/#django.contrib.auth.password_validation.validate_password
        if validate_password(SU_DEFAULT_PASSWORD) is None:
            HealthcareUser.objects.create_superuser(
                "[email protected]",
                "hcw_portal_admin",
                SU_DEFAULT_PASSWORD,
                phone_number="+16476675327",
            )
            self.stdout.write(self.style.SUCCESS("Successfully created new super user"))

3 Source : forms.py
with MIT License
from chunky2808

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
        self.instance.username = self.cleaned_data.get('username')
        password_validation.validate_password(self.cleaned_data.get('password2'), self.instance)
        return password2

    def save(self, commit=True):

3 Source : tests.py
with MIT License
from codingforentrepreneurs

    def test_secret_key_strength(self):
        # settings.SECRET_KEY
        SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY')
        # self.assertNotEqual(SECRET_KEY, 'abc123')
        try:
            is_strong = validate_password(SECRET_KEY)
        except Exception as e:
            msg = f'Weak Secret Key {e.messages}'
            self.fail(msg)

3 Source : forms.py
with GNU General Public License v3.0
from foonsun

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1', '')
        password2 = self.cleaned_data.get('password2', '')
        if password1 != password2:
            raise forms.ValidationError(
                _("两次密码不一致"))
        validate_password(password2, self.instance)
        return password2

    def clean_redirect_url(self):

3 Source : forms.py
with GNU General Public License v3.0
from foonsun

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1', '')
        password2 = self.cleaned_data.get('password2', '')

        if password1 != password2:
            raise forms.ValidationError(
                _("The two password fields didn't match."))
        validate_password(password2, self.instance)
        return password2

    def __init__(self, *args, **kwargs):

3 Source : forms.py
with GNU General Public License v3.0
from GeekZoneHQ

    def clean_password(self):
        password = self.cleaned_data.get("password")
        password_validation.validate_password(password, None)

        return self.cleaned_data["password"]

    def clean_email(self):

3 Source : forms.py
with Apache License 2.0
from genomicsengland

    def clean_password2(self):
        """Make sure passwords match"""

        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError(
                "Passwords don't match", code="password_mismatch"
            )
        password_validation.validate_password(
            self.cleaned_data.get("password2"), self.user
        )
        return password2

    def update_user_password(self, commit=True):

3 Source : test_validators.py
with Apache License 2.0
from gethue

    def test_validate_password(self):
        self.assertIsNone(validate_password('sufficiently-long'))
        msg_too_short = 'This password is too short. It must contain at least 12 characters.'

        with self.assertRaises(ValidationError) as cm:
            validate_password('django4242')
        self.assertEqual(cm.exception.messages, [msg_too_short])
        self.assertEqual(cm.exception.error_list[0].code, 'password_too_short')

        with self.assertRaises(ValidationError) as cm:
            validate_password('password')
        self.assertEqual(cm.exception.messages, ['This password is too common.', msg_too_short])
        self.assertEqual(cm.exception.error_list[0].code, 'password_too_common')

        self.assertIsNone(validate_password('password', password_validators=[]))

    def test_password_changed(self):

3 Source : models.py
with BSD 2-Clause "Simplified" License
from getmetamapper

    def change_password(self, password):
        """Changes user password and sends an alert email.
        """
        from app.authentication.emails import password_was_reset
        validate_password(password)
        self.set_password(password)
        self.save()
        password_was_reset(self.email)

    def check_email(self, email):

3 Source : serializers.py
with BSD 2-Clause "Simplified" License
from getmetamapper

    def validate_password(self, password):
        try:
            validate_password(password, user=models.User)
        except django_exceptions.ValidationError as e:
            raise serializers.ValidationError(e.messages[0], 'too_weak')
        return password

    def validate_email(self, email):

3 Source : serializers.py
with BSD 2-Clause "Simplified" License
from getmetamapper

    def validate_password(self, password):
        user = self.context['request'].user
        try:
            validate_password(password, user)
        except django_exceptions.ValidationError as e:
            raise serializers.ValidationError(e.messages[0], 'too_weak')
        return password

    def validate_email(self, email):

3 Source : admin_forms.py
with GNU General Public License v3.0
from gojuukaze

    def _clean_password(self):
        password = self.cleaned_data["password"]
        user_info = self.instance

        user = User(username=user_info.uid, first_name=user_info.name, is_staff=True, is_active=True)
        user._user_info = user_info
        validate_password(password, user)
        user.set_password(self.cleaned_data["password"])

        self.user = user
        return password

    def full_clean(self):

3 Source : change_password.py
with MIT License
from huychau

    def validate_new_password(self, new_password):
        """
        Validate user password
        """

        user = self.context['request'].user
        password_validation.validate_password(new_password, user)
        return new_password

    def save(self, **kwargs):

3 Source : register.py
with MIT License
from huychau

    def validate_password(self, value):
        """
        Validate user password
        """

        password_validation.validate_password(value, self.instance)
        return value

    def create(self, validated_data):

3 Source : set_password.py
with MIT License
from huychau

    def validate_password(self, password):
        """
        Validate user password
        """

        user = self.context['request'].user
        if user.password:
            raise serializers.ValidationError(_('Your password is already existed.'))
        password_validation.validate_password(password, user)
        return password

    def save(self, **kwargs):

3 Source : forms.py
with GNU General Public License v3.0
from JustFixNYC

    def clean_password(self):
        password = self.cleaned_data["password"]
        if password:
            validate_password(password)
        return password

    def clean(self):

3 Source : forms.py
with Apache License 2.0
from ldv-klever

    def clean_new_password2(self):
        password1 = self.cleaned_data.get('new_password1')
        password2 = self.cleaned_data.get('new_password2')
        if password1 != password2:
            raise forms.ValidationError(
                self.error_messages['password_mismatch'],
                code='password_mismatch',
            )
        elif password2:
            # Validate if passwords similar and both specified
            password_validation.validate_password(password2, self.instance)
        return password2

    def clean_default_threshold(self):

3 Source : forms.py
with Apache License 2.0
from ldv-klever

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1') or ''
        password2 = self.cleaned_data.get('password2') or ''
        if password1 != password2:
            raise forms.ValidationError(self.error_messages['password_mismatch'], code='password_mismatch')
        elif password2:
            # Validate if passwords similar and both specified
            password_validation.validate_password(password2, self.instance)
        return password2

    def clean(self):

3 Source : user_change_password_serializer.py
with MIT License
from Mangeneh

    def validate_new_password(self, value):
        utils.start_method_log('UserChangePasswordSerializer: validate_new_password')

        validate_password(value)

        logger.info('UserChangePasswordSerializer: validate_new_password (password validated!)')

        return value

3 Source : serializers.py
with MIT License
from Mehdi6

    def validate_password1(self, password):
        #TODO better password constraints (length, uppercase, lowercase, special characters, etc)
        errors = dict() 
        try:
            # validate the password and catch the exception
            validators.validate_password(password=password, user=User)

        # the exception raised here is different than serializers.ValidationError
        except exceptions.ValidationError as e:
            errors['password'] = list(e.messages)

        if errors:
            raise serializers.ValidationError(errors)
        
        return password

    def validate(self, data):

3 Source : serializers.py
with MIT License
from Mehdi6

    def pwd_constraints(self, pwd):
        errors = dict() 
        try:
            # validate the password and catch the exception
            validators.validate_password(password=pwd, user=User)

        # the exception raised here is different than serializers.ValidationError
        except exceptions.ValidationError as e:
            errors['password'] = list(e.messages)

        if errors:
            raise serializers.ValidationError(errors)
         
        #Add some security constraints such a regexp validation (criteria: cap letters, special chars, numbers, etc)
        return True
    
    def save(self):

3 Source : serializers.py
with MIT License
from ojengwa

    def validate_password(self, data):
        """initial_data has to be converted to an
        object for UserAttributeSimilarityValidator."""
        user = self.initial_data
        validators.validate_password(password=data, user=user)

    class Meta:

3 Source : serializers.py
with MIT License
from ojengwa

    def validate_new_password(self, data):
        """initial_data has to be converted to an object for
         UserAttributeSimilarityValidator."""
        user = self.initial_data
        validators.validate_password(password=data, user=user)


class CurrentPasswordSerializer(serializers.Serializer):

3 Source : serializers.py
with MIT License
from open-apparel-registry

    def validate(self, data):
        user = User(**data)
        password = data.get('password')

        try:
            password_validation.validate_password(password=password, user=user)
            return super(UserSerializer, self).validate(data)
        except exceptions.ValidationError as e:
            raise ValidationError({"password": list(e.messages)})

    def create(self, validated_data):

3 Source : users.py
with MIT License
from pablotrinidad

    def validate(self, data):
        """Verify passwords match."""
        passwd = data['password']
        passwd_conf = data['password_confirmation']
        if passwd != passwd_conf:
            raise serializers.ValidationError("Passwords don't match.")
        password_validation.validate_password(passwd)
        return data

    def create(self, data):

3 Source : forms.py
with MIT License
from rossm6

    def clean_password(self):
        password = self.cleaned_data.get("password")
        validate_password(password)
        return password

    def clean(self):

3 Source : forms.py
with BSD 3-Clause "New" or "Revised" License
from Ryuchen

    def _post_clean(self):
        super()._post_clean()
        # Validate the password after self.instance is updated with form data
        # by super().
        password = self.cleaned_data.get('password2')
        if password:
            try:
                password_validation.validate_password(password, self.instance)
            except vueForms.ValidationError as error:
                self.add_error('password2', error)

    def save(self, commit=True):

3 Source : forms.py
with BSD 3-Clause "New" or "Revised" License
from Ryuchen

    def clean_new_password2(self):
        password1 = self.cleaned_data.get('new_password1')
        password2 = self.cleaned_data.get('new_password2')
        if password1 and password2:
            if password1 != password2:
                raise vueForms.ValidationError(
                    self.error_messages['password_mismatch'],
                    code='password_mismatch',
                )
        password_validation.validate_password(password2, self.user)
        return password2

    def save(self, commit=True):

3 Source : forms.py
with BSD 3-Clause "New" or "Revised" License
from Ryuchen

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')
        if password1 and password2:
            if password1 != password2:
                raise vueForms.ValidationError(
                    self.error_messages['password_mismatch'],
                    code='password_mismatch',
                )
        password_validation.validate_password(password2, self.user)
        return password2

    def save(self, commit=True):

3 Source : mutations.py
with MIT License
from strawberry-graphql

    def create(self, data):
        input_data = get_input_data(self.input_type, data)
        validate_password(input_data["password"])
        instance = self.django_model.objects.create_user(**input_data)
        update_m2m([instance], data)
        return instance

3 Source : serializers.py
with GNU Affero General Public License v3.0
from thalesgroup-cert

    def validate(self, data):
        # add here additional check for password strength if needed
        if not self.context['request'].user.check_password(data.get('old_password')):
            raise serializers.ValidationError({'old_password': 'Wrong password.'})
        validate_password(data.get('password'))
        return data

    def create(self, validated_data):

3 Source : user.py
with MIT License
from thenewboston-developers

    def validate_password(password):
        validate_password(password)
        return password


class UserSerializerUpdate(UserSerializer):

3 Source : test_validators.py
with BSD 3-Clause "New" or "Revised" License
from ubernostrum

    def test_not_compromised(self):
        """
        Non-compromised passwords don't raise ValidationError.

        """
        request_mock = self._get_mock(
            response_text="{}:5".format(self.sample_password_suffix.replace("A", "3"))
        )
        with mock.patch("requests.get", request_mock):
            validate_password(self.sample_password)
            request_mock.assert_called_with(
                url=api.API_ENDPOINT.format(self.sample_password_prefix),
                headers=self.user_agent,
                timeout=api.REQUEST_TIMEOUT,
            )

    def test_default_help_message(self):

3 Source : test_validators.py
with BSD 3-Clause "New" or "Revised" License
from ubernostrum

    def test_message_override(self):
        """
        Custom messages are honored.

        """
        request_mock = self._get_mock()
        with mock.patch("requests.get", request_mock):
            with self.assertRaisesMessage(ValidationError, "Pwned"):
                validate_password(self.sample_password)

    @override_settings(

3 Source : user.py
with MIT License
from vigo

    def _post_clean(self):
        super()._post_clean()
        password = self.cleaned_data.get('password2')
        if password:
            try:
                password_validation.validate_password(password, self.instance)
            except forms.ValidationError as error:
                self.add_error('password2', error)

    def clean_password2(self):

3 Source : views.py
with MIT License
from VladimirARodionov

    def clean_new_password2(self, password1, password2):
        if password1 and password2:
            if password1 != password2:
                raise forms.ValidationError('Password mismatch')
        password_validation.validate_password(password2, self.get_object())
        return password2

    def post(self, request, *args, **kwargs):

3 Source : auth.py
with Apache License 2.0
from vstconsulting

    def update(self, instance, validated_data):
        if not instance.check_password(validated_data['old_password']):
            raise exceptions.AuthenticationFailed()
        if validated_data['password'] != validated_data['password2']:
            raise exceptions.ValidationError(
                translate("New passwords values are not equal.")
            )
        validate_password(validated_data['password'])
        instance.set_password(validated_data['password'])
        instance.save()
        return instance

    def to_representation(self, instance):

0 Source : changepassword.py
with GNU General Public License v3.0
from Aghoreshwar

    def handle(self, *args, **options):
        if options['username']:
            username = options['username']
        else:
            username = getpass.getuser()

        try:
            u = UserModel._default_manager.using(options['database']).get(**{
                UserModel.USERNAME_FIELD: username
            })
        except UserModel.DoesNotExist:
            raise CommandError("user '%s' does not exist" % username)

        self.stdout.write("Changing password for user '%s'\n" % u)

        MAX_TRIES = 3
        count = 0
        p1, p2 = 1, 2  # To make them initially mismatch.
        password_validated = False
        while (p1 != p2 or not password_validated) and count   <   MAX_TRIES:
            p1 = self._get_pass()
            p2 = self._get_pass("Password (again): ")
            if p1 != p2:
                self.stdout.write("Passwords do not match. Please try again.\n")
                count += 1
                # Don't validate passwords that don't match.
                continue
            try:
                validate_password(p2, u)
            except ValidationError as err:
                self.stderr.write('\n'.join(err.messages))
                count += 1
            else:
                password_validated = True

        if count == MAX_TRIES:
            raise CommandError("Aborting password change for user '%s' after %s attempts" % (u, count))

        u.set_password(p1)
        u.save()

        return "Password changed successfully for user '%s'" % u

See More Examples