Python django.contrib.auth.password_validation.validate_password() Examples

The following are 21 code examples of django.contrib.auth.password_validation.validate_password(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.contrib.auth.password_validation , or try the search function .
Example #1
Source File: serializers.py    From cadasta-platform with GNU Affero General Public License v3.0 7 votes vote down vote up
def validate_new_password(self, password):
        user = self.context['request'].user
        validate_password(password, user=user)

        username = user.username
        if len(username) and username.casefold() in password.casefold():
            raise serializers.ValidationError(
                _("The password is too similar to the username."))

        phone = user.phone
        if phone and phone_validator(phone):
            phone = str(parse_phone(phone).national_number)
            if phone in password:
                raise serializers.ValidationError(
                    _("Passwords cannot contain your phone."))

        return password 
Example #2
Source File: auth.py    From arches with GNU Affero General Public License v3.0 6 votes vote down vote up
def post(self, request):
        messages = {"invalid_password": None, "password_validations": None, "success": None, "other": None, "mismatched": None}
        try:
            user = request.user
            old_password = request.POST.get("old_password")
            new_password = request.POST.get("new_password")
            new_password2 = request.POST.get("new_password2")
            if user.check_password(old_password) == False:
                messages["invalid_password"] = _("Invalid password")
            if new_password != new_password2:
                messages["mismatched"] = _("New password and confirmation must match")
            try:
                validation.validate_password(new_password, user)
            except ValidationError as val_err:
                messages["password_validations"] = val_err.messages

            if messages["invalid_password"] is None and messages["password_validations"] is None and messages["mismatched"] is None:
                user.set_password(new_password)
                user.save()
                authenticated_user = authenticate(username=user.username, password=new_password)
                login(request, authenticated_user)
                messages["success"] = _("Password successfully updated")

        except Exception as err:
            messages["other"] = err

        return JSONResponse(messages) 
Example #3
Source File: forms.py    From webterminal with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #4
Source File: change_password.py    From django-rest-registration with MIT License 5 votes vote down vote up
def validate_password(self, password):
        user = self.context['request'].user
        validate_password(password, user=user)
        return password 
Example #5
Source File: forms.py    From registration with MIT License 5 votes vote down vote up
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("The passwords do not match.")
        password_validation.validate_password(password2)
        return password2 
Example #6
Source File: registration.py    From lego with MIT License 5 votes vote down vote up
def validate_password(self, password):
        password_validation.validate_password(password)
        return password 
Example #7
Source File: password_change.py    From lego with MIT License 5 votes vote down vote up
def validate_new_password(self, password):
        if password:
            password_validation.validate_password(password)
        return password 
Example #8
Source File: password_change.py    From lego with MIT License 5 votes vote down vote up
def validate_password(self, value):
        user = self.context["request"].user
        if user.has_usable_password() and not user.check_password(value):
            raise serializers.ValidationError(self.error_messages["invalid_password"])
        return value 
Example #9
Source File: password_reset.py    From lego with MIT License 5 votes vote down vote up
def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        token = serializer.validated_data["token"]
        password = serializer.validated_data["password"]

        password_validation.validate_password(password)
        email = PasswordReset.validate_reset_token(token)

        try:
            user = User.objects.get(email__iexact=email)
        except User.DoesNotExist:
            raise ValidationError({"email": "User with that email does not exist"})

        user.set_password(password)
        user.save()
        return Response(DetailedUserSerializer(user).data, status=status.HTTP_200_OK) 
Example #10
Source File: test_audit_log.py    From zulip with Apache License 2.0 5 votes vote down vote up
def test_change_password(self) -> None:
        now = timezone_now()
        user = self.example_user('hamlet')
        password = 'test1'
        do_change_password(user, password)
        self.assertEqual(RealmAuditLog.objects.filter(event_type=RealmAuditLog.USER_PASSWORD_CHANGED,
                                                      event_time__gte=now).count(), 1)
        self.assertIsNone(validate_password(password, user)) 
Example #11
Source File: users.py    From cride-platzi with MIT License 5 votes vote down vote up
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 
Example #12
Source File: serializers.py    From desec-stack with MIT License 5 votes vote down vote up
def validate_password(self, value):
        if value is not None:
            validate_password(value)
        return value 
Example #13
Source File: admin.py    From devops with GNU General Public License v3.0 4 votes vote down vote up
def clean_password2(self):
        # Check that the two password entries 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")
        #self.instance.username = self.cleaned_data.get('email')
        #password_validation.validate_password(self.cleaned_data.get['password2'],self.instance)
        return password2 
Example #14
Source File: serializers.py    From cadasta-platform with GNU Affero General Public License v3.0 4 votes vote down vote up
def validate_password(self, password):
        validate_password(password)

        errors = []
        email = self.initial_data.get('email')
        if email:
            email = email.split('@')
            if email[0].casefold() in password.casefold():
                errors.append(_("Passwords cannot contain your email."))

        username = self.initial_data.get('username')
        if len(username) and username.casefold() in password.casefold():
            errors.append(
                _("The password is too similar to the username."))

        phone = self.initial_data.get('phone')
        if phone:
            if phone_validator(phone):
                try:
                    phone = str(parse_phone(phone).national_number)
                    if phone in password:
                        errors.append(
                            _("Passwords cannot contain your phone."))
                except NumberParseException:
                    pass
        if errors:
            raise serializers.ValidationError(errors)

        return password 
Example #15
Source File: fields.py    From django-zxcvbn-password with ISC License 4 votes vote down vote up
def __call__(self, value):
        """Call method, run django's validate_password method."""
        return validate_password(value) 
Example #16
Source File: rest_api.py    From scirius with GNU General Public License v3.0 4 votes vote down vote up
def create(self, validated_data):
        user_data = validated_data.pop('user')

        errors = {}
        if 'username' not in user_data:
            errors['username'] = ['This field is required.']

        if 'password' not in user_data:
            errors['password'] = ['This field is required.']

        if len(errors) > 0:
            raise serializers.ValidationError(errors)

        if 'timezone' not in validated_data:
            validated_data['timezone'] = 'UTC'

        if validated_data['timezone'] not in pytz.all_timezones:
            raise serializers.ValidationError({'timezone': ['Not a valid choice.']})

        password = user_data.pop('password')
        try:
            password_validation.validate_password(password=password, user=User)
        except exceptions.ValidationError as e:
            raise serializers.ValidationError({'password': [e.message]})

        user = User.objects.create(**user_data)
        user.set_password(password)
        user.save()

        return SciriusUser.objects.create(user=user, **validated_data) 
Example #17
Source File: rest_api.py    From scirius with GNU General Public License v3.0 4 votes vote down vote up
def validate_new_password(self, password):
        try:
            password_validation.validate_password(password=password, user=User)
        except exceptions.ValidationError as e:
            raise serializers.ValidationError({'password': [unicode(e)]})
        return password 
Example #18
Source File: forms.py    From registration with MIT License 4 votes vote down vote up
def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1", None)
        password2 = self.cleaned_data.get("password2", None)
        if not self.initial and password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        validate_password(password1)
        return password2 
Example #19
Source File: forms.py    From registration with MIT License 4 votes vote down vote up
def clean_password2(self):
        # Check that the two password entries match
        password = self.cleaned_data.get("password")
        password2 = self.cleaned_data.get("password2")
        if password and password2 and password != password2:
            raise forms.ValidationError("Passwords don't match")
        validate_password(password)
        return password2 
Example #20
Source File: createuser.py    From polyaxon with Apache License 2.0 4 votes vote down vote up
def validate_password(self, password: str, user_data: Dict, force: bool) -> None:
        try:
            validate_password(password, self.UserModel(**user_data))
        except ValidationError as e:
            _logger.warning("The password provided is not valid %s", e)
            if force:
                _logger.warning(
                    "The user will be created although the password does not meet the validation."
                )
            else:
                raise e 
Example #21
Source File: createuser.py    From polyaxon with Apache License 2.0 4 votes vote down vote up
def handle(self, *args, **options):  # pylint:disable=too-many-branches
        username = options[self.UserModel.USERNAME_FIELD].strip()
        password = options["password"].strip()
        email = options["email"].strip()
        force = to_bool(options["force"])
        is_superuser = to_bool(options["is_superuser"])

        try:
            username = self.username_field.clean(username, None)
        except exceptions.ValidationError as e:
            raise CommandError("; ".join(e.messages))

        try:
            self.email_field.clean(email, None)
        except exceptions.ValidationError as e:
            raise CommandError("; ".join(e.messages))

        try:
            self.UserModel.objects.get_by_natural_key(username)
        except self.UserModel.DoesNotExist:
            pass
        else:
            _logger.info(
                "Info: Username %s is already taken. Will not recreate user.", username
            )
            return

        try:
            self.UserModel.objects.get(email=email)
        except self.UserModel.DoesNotExist:
            pass
        except exceptions.MultipleObjectsReturned:
            raise CommandError("Error: That %s is already taken." % email)
        else:
            raise CommandError("Error: That %s is already taken." % email)

        if not username:
            raise CommandError("Error: Blank username aren't allowed.")

        if not password:
            raise CommandError("Error: Blank passwords aren't allowed.")

        if not email:
            raise CommandError("Error: Blank email aren't allowed.")

        user_data = {self.UserModel.USERNAME_FIELD: username, "email": email}

        self.validate_password(password=password, user_data=user_data, force=force)
        user_data["password"] = password

        if is_superuser:
            self.UserModel.objects.create_superuser(**user_data)
        else:
            self.UserModel.objects.create_user(**user_data)

        if options["verbosity"] >= 1:
            self.stdout.write(
                "{} created successfully.".format(
                    "Superuser" if is_superuser else "User"
                )
            )