Password Validation with Python

0

I have the following requirement to validate a password in the registry:

  • Size: 10 characters
  • Uppercase: 2
  • Lower case: 2
  • Number: 1
  • Symbol: 2

How do I do this with python?

For the time being I have only been able to do this, since the part of the capital letter I just tested to see if there is any in the password:

if len(password or ()) < 10:
        raise forms.ValidationError("Senha mínimo 10 caracteres")
    if any(x.isupper() for x in password):
        raise forms.ValidationError("Senha tem letra maiúscula")
    if password and password_confirm:
        if password != password_confirm:
            raise forms.ValidationError("As senhas não conferem")
    
asked by anonymous 08.03.2018 / 14:52

2 answers

1

For these cases you should use regular expressions.

Look at this site later. link

import re
from django.forms import forms

def test_password(password):
    minimal_number = 2
    minimal_upper_char = 2
    minimal_lower_char = 2
    minimal_special_char = 1
    minimal_len_char = 10
    if len(password or ()) < minimal_len_char:
        raise forms.ValidationError('Senha tem que ter no mínimo '+str(minimal_len_char)+' caracteres')
    if len(re.findall(r"[A-Z]", password)) < minimal_upper_char:
        raise forms.ValidationError('Senha tem que ter no mínimo '+str(minimal_upper_char)+' letras maiusculas')
    if len(re.findall(r"[a-z]", password)) < minimal_lower_char:
        raise forms.ValidationError('Senha tem que ter no mínimo '+str(minimal_lower_char)+' letras minusculas')
    if len(re.findall(r"[0-9]", password)) < minimal_number:
        raise forms.ValidationError('Senha tem que ter no mínimo '+str(minimal_number)+' numeros')
    if len(re.findall(r"[~'!@#$%^&*()_+=-{};:'><]", password)) < minimal_special_char:
        raise forms.ValidationError('Senha tem que ter no mínimo '+str(minimal_special_char)+' caracteres especiais')
    
11.03.2018 / 04:47
1

I think the best option is for you to write the validator itself and add it to your settings.py . Here in Django's doc you can see how, but it would be something like this draft I made below (I just added an example, missing all validation methods):

from django.core.exceptions import ValidationError
from django.utils.translation import gettext as _


class MyCustomValidator:
    def __init__(self):
        self.length = 10
        self.max_upper_case = 2
        self.max_lower_case = 2
        self.max_int_case = 1
        self.max_symbols_case = 2

    def validate_length_password(self, password):
        if len(self.password) < self.length:
            return True

        return False

    def validate_upper_case(self, password):
        pass

    def validate_lower_case(self, password):
        pass

    def validate_int_case(self, password):
        pass

    def validate_max_symbols_case(self, password):
        pass

    def validate(self, password, user=None):
        if self.validate_length_password(password):
            raise ValidationError(
                _("This password must contain at least "
                    "%(length)d characters."),
                code='password_too_short',
                params={'length': self.length},
            )

    def get_help_text(self):
        return _(
            "Your password must contain at least %(length)d characters."
            % {'length': self.length}
        )

From there on your settings.py on AUTH_PASSWORD_VALIDATORS you add this class, type:

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'path.onde.ta.o.arquivo.do.seu.validator.finalizando.com.a.classe.MyCustomValidator',
    },
]
    
12.03.2018 / 17:24