custom.py 1.48 KB
Newer Older
David Seaward's avatar
David Seaward committed
1 2 3
import logging

from django.contrib.auth.password_validation import MinimumLengthValidator as BaseValidator
4 5 6
from django.core import validators
from django.utils.deconstruct import deconstructible
from django.utils.translation import ugettext_lazy as _
David Seaward's avatar
David Seaward committed
7 8 9 10 11
from django_auth_ldap.backend import LDAPBackend as BaseBackend

log = logging.getLogger(__name__)


12
class AuthenticationBackend(BaseBackend):
David Seaward's avatar
David Seaward committed
13 14

    def __init__(self, *args, **kwargs):
15
        super(AuthenticationBackend, self).__init__(*args, **kwargs)
David Seaward's avatar
David Seaward committed
16

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
    def authenticate(self, request=None, username=None, password=None, **kwargs):
        model = self.get_user_model()
        username = model.normalize_username(username)

        # TODO: also validate, so that existing but invalid usernames are not permitted?

        return super(AuthenticationBackend, self).authenticate(request, username, password, **kwargs)


@deconstructible
class UsernameValidator(validators.RegexValidator):
    regex = r'^[A-Za-z][A-Za-z0-9]*$'
    message = _(
        'Enter a valid username. Must start with a letter, followed by letters and numbers. No punctuation or special characters.'
    )
David Seaward's avatar
David Seaward committed
32 33


34 35
class PassphraseValidator(BaseValidator):
    # TODO: bundle in all the other validators from django.contrib.auth.password_validation
David Seaward's avatar
David Seaward committed
36

37
    def __init__(self, min_length=15, *args, **kwargs):
38
        super(PassphraseValidator, self).__init__(min_length, *args, **kwargs)
David Seaward's avatar
David Seaward committed
39 40

    def get_help_text(self):
41
        return _("A good passphrase is made of at least three long words.")