def test_validate(self):
        expected_error = "This password is entirely numeric."
        self.assertIsNone(NumericPasswordValidator().validate('a-safe-password'))

        with self.assertRaises(ValidationError) as cm:
            NumericPasswordValidator().validate('42424242')
        self.assertEqual(cm.exception.messages, [expected_error])
        self.assertEqual(cm.exception.error_list[0].code, 'password_entirely_numeric')
示例#2
0
def validacao_senha_redefinicao(request):
    senha = loads(request.body)['valor']
    resposta = {}

    tamanho_minimo = MinimumLengthValidator(8)
    numerica = NumericPasswordValidator()
    comum = CommonPasswordValidator()
    similar = UserAttributeSimilarityValidator(('nome', 'sobrenome', 'email'),
                                               max_similarity=0.7)

    # Checando se a senha tem no mínimo 8 caracteres
    try:
        tamanho_minimo.validate(senha)
    except ValidationError:
        tamanho_minimo = False

    # Checando se a senha é totalmente numérica
    try:
        numerica.validate(senha)
    except ValidationError:
        numerica = False

    # Checando se a senha é comum
    try:
        comum.validate(senha)
    except ValidationError:
        comum = False

    # Checando se a senha é similar a outras informações do usuário

    try:
        similar.validate(senha, request.user)
    except ValidationError as e:
        similar = False

    if not tamanho_minimo:
        status = 400
        resposta['status'] = 'inválido'
        resposta['erro'] = 'Sua senha deve conter pelo menos 8 caracteres'
    elif not numerica:
        status = 400
        resposta['status'] = 'inválido'
        resposta['erro'] = 'Sua senha não pode ser inteiramente numérica'
    elif not comum:
        status = 400
        resposta['status'] = 'inválido'
        resposta['erro'] = 'Essa senha é muito comum. Tente outra'
    elif not similar:
        status = 400
        resposta['status'] = 'inválido'
        resposta[
            'erro'] = 'Essa senha é muito parecida com seu e-mail ou com seu nome'
    else:
        status = 200
        resposta['status'] = 'válido'

    return JsonResponse(resposta, status=status)
示例#3
0
def validate_password(pw):
    try:
        MinimumLengthValidator(8).validate(pw)
        NumericPasswordValidator().validate(pw)
        return True
    except ValidationError:
        return False
示例#4
0
    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")

        if password1 and password2 and password1 != password2:
            raise ValidationError("Password don't match")

        user = User(
            username=self.cleaned_data.get("username"),
            email=self.cleaned_data.get("email"),
            password=self.cleaned_data.get("password2"),
        )
        password_validators = [
            MinimumLengthValidator(),
            UserAttributeSimilarityValidator(),
            CommonPasswordValidator(),
            NumericPasswordValidator(),
        ]

        try:
            validate_password(
                password=self.cleaned_data["password2"],
                user=user,
                password_validators=password_validators,
            )
        except ValidationError as e:
            logger.error("validation failed")
            raise ValidationError(e)
        return self.cleaned_data["password2"]
示例#5
0
 def clean_password(self):
     password = self.cleaned_data.get('password')
     password_validation.validate_password(
         password,
         password_validators=(MinimumLengthValidator(min_length=6),
                              NumericPasswordValidator(),
                              CommonPasswordValidator()))
     return password
示例#6
0
 def clean_password_2(self):
     UserAttributeSimilarityValidator().validate(
         self.cleaned_data['password'])
     NumericPasswordValidator().validate(self.cleaned_data['password'])
     CommonPasswordValidator().validate(self.cleaned_data['password'])
     if self.cleaned_data['password'] != self.cleaned_data['password_2']:
         raise forms.ValidationError(
             'Passwords do not match. Please, provide password again.')
     return self.cleaned_data['password']
示例#7
0
class RegisterForm(forms.ModelForm):

    error_messages = {
        'password_mismatch': _("The two password fields didn't match."),
        'email_occupation': 'Данный адрес почты уже используется',
    }

    class Meta:
        model = User
        fields = ['username', 'first_name', 'last_name', 'email']

    def __init__(self, *args, **kwargs):
        super(RegisterForm, self).__init__(*args, **kwargs)
        for key in self.fields:
            self.fields[key].required = True

    password1 = forms.CharField(
        label=_("Password"),
        widget=forms.PasswordInput,
        validators=[
            MinimumLengthValidator(min_length=8).validate,
            UserAttributeSimilarityValidator().validate,
            CommonPasswordValidator().validate,
            NumericPasswordValidator().validate
        ])

    password2 = forms.CharField(
        label=_("Password confirmation"),
        widget=forms.PasswordInput,
        help_text=_("Enter the same password as above, for verification."))

    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',
            )
        return password2

    def clean_email(self, *args, **kwargs):
        email = self.cleaned_data.get("email")
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError(
                self.error_messages['email_occupation'],
                code='email_occupation',
            )
        return email

    def save(self, commit=True):
        user = super(RegisterForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()

        return user
示例#8
0
def validacao_senha_registro(request):
    senha = loads(request.body)['valor']
    resposta = {}

    tamanho_minimo = MinimumLengthValidator(8)
    numerica = NumericPasswordValidator()
    comum = CommonPasswordValidator()

    # Checando se a senha tem no mínimo 8 caracteres
    try:
        tamanho_minimo.validate(senha)
    except ValidationError:
        tamanho_minimo = False

    # Checando se a senha é totalmente numérica
    try:
        numerica.validate(senha)
    except ValidationError:
        numerica = False

    # Checando se a senha é comum
    try:
        comum.validate(senha)
    except ValidationError:
        comum = False

    if not tamanho_minimo:
        status = 400
        resposta['status'] = 'inválido'
        resposta['erro'] = 'Sua senha deve conter pelo menos 8 caracteres'
    elif not numerica:
        status = 400
        resposta['status'] = 'inválido'
        resposta['erro'] = 'Sua senha não pode ser inteiramente numérica'
    elif not comum:
        status = 400
        resposta['status'] = 'inválido'
        resposta['erro'] = 'Essa senha é muito comum. Tente outra.'
    else:
        status = 200
        resposta['status'] = 'válido'

    return JsonResponse(resposta, status=status)
class ProfileEditForm(forms.ModelForm):
    """
    Форма для редактирования пользователя.
    """
    password = forms.CharField(widget=forms.PasswordInput(), \
         label=_('Новый пароль'), required=False, validators=[
                UserAttributeSimilarityValidator(), MinimumLengthValidator(),
                CommonPasswordValidator(), NumericPasswordValidator()
             ])

    password_confirm = forms.CharField(widget=forms.PasswordInput(), \
         label=_('Подтвердите новый пароль'), required=False)

    class Meta:
        model = get_user_model()
        fields = ['username', 'email']
        labels = {
            'username': _('Username'),
            'email': _('Email'),
        }
        help_texts = {
            'username': _('Латинские буквы, цифры и @ / . / + / - / _')
        }
        error_messages = {
            'username': {
                'unique': _('Пользователь с таким username уже существует')
            }
        }

    def clean(self):
        """
        Валидация всей формы, в целом.
        """
        cleaned_data = super(ProfileEditForm, self).clean()

        password = cleaned_data.get('password')
        password_confirm = cleaned_data.get('password_confirm')

        if password != password_confirm:
            raise forms.ValidationError(_('Пароли не совпадают'))

    def save(self, commit=True):
        """
        Сохранение отредактированной формы в БД.
        """
        hr_user = super(ProfileEditForm, self).save(commit=False)

        password = self.cleaned_data['password']
        if password is not None and password:
            hr_user.set_password(password)

        if commit:
            hr_user.save()

        return hr_user
示例#10
0
 def clean(self):
     word = self.cleaned_data['password']
     repass = self.cleaned_data['re_password']
     if MinimumLengthValidator().validate(password=word) is not None:
         raise ValidationError
     if NumericPasswordValidator().validate(password=word) is not None:
         raise ValidationError
     if word != repass:
         raise ValidationError('Passwords do not match')
     if User.objects.all().filter(username=self.cleaned_data['username']):
         raise ValidationError('This Username is already taken')
示例#11
0
class SignUpSerializer(BaseSerializer):
    email = serializers.EmailField(max_length=254)
    password = serializers.CharField(
        max_length=128,
        validators=[
            UserAttributeSimilarityValidator(
                user_attributes=('username', 'email')).validate,
            MinimumLengthValidator().validate,
            CommonPasswordValidator().validate,
            NumericPasswordValidator().validate,
        ])

    @staticmethod
    def get_account_creation_data(validated_data: dict):
        creation_data = {
            'organization_slug': validated_data['organization_slug'],
            'username': validated_data.get('username') or 'master',
            'email': validated_data['email'],
            'password': validated_data['password'],
        }
        return creation_data
示例#12
0
 def test_help_text(self):
     self.assertEqual(
         NumericPasswordValidator().get_help_text(),
         "Your password can't be entirely numeric."
     )