Password Validation with Python

Asked

Viewed 2,615 times

0

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

  • Size: 10 characters
  • Capital letters: 2
  • Lower case: 2
  • Number: 1
  • Symbol: 2

How do I check with python?

So far I’ve only been able to do that, and the uppercase part I just tested to see if there’s 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")

2 answers

1

For these cases you should use regular expressions.

Check out this website later. https://docs.python.org/3/library/re.html

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')
  • What if the user puts accented letters in the password? The regular expression won’t pick them up.

  • Thanks Ytalo, only the special characters did not work... but I understood the logic!

1

I think the best option is for you to write your own Validator and add it to your settings.py. Here in django doc you can see how to do, but it would be something like this draft I did below (I added only one example, missing implement all methods for validations):

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 in the AUTH_PASSWORD_VALIDATORS you add this class, like:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.