2015-03-08 22:07:57 +08:00
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
|
|
|
import gzip
|
|
|
|
import os
|
|
|
|
import re
|
|
|
|
from difflib import SequenceMatcher
|
|
|
|
|
|
|
|
from django.conf import settings
|
2016-07-22 16:51:38 +08:00
|
|
|
from django.core.exceptions import (
|
|
|
|
FieldDoesNotExist, ImproperlyConfigured, ValidationError,
|
|
|
|
)
|
2015-03-08 22:07:57 +08:00
|
|
|
from django.utils import lru_cache
|
2015-06-09 01:27:47 +08:00
|
|
|
from django.utils._os import upath
|
2015-03-08 22:07:57 +08:00
|
|
|
from django.utils.encoding import force_text
|
2016-05-06 18:23:52 +08:00
|
|
|
from django.utils.functional import lazy
|
2015-03-08 22:07:57 +08:00
|
|
|
from django.utils.html import format_html
|
|
|
|
from django.utils.module_loading import import_string
|
2016-05-06 18:23:52 +08:00
|
|
|
from django.utils.six import string_types, text_type
|
2015-10-10 21:12:55 +08:00
|
|
|
from django.utils.translation import ugettext as _, ungettext
|
2015-03-08 22:07:57 +08:00
|
|
|
|
|
|
|
|
|
|
|
@lru_cache.lru_cache(maxsize=None)
|
|
|
|
def get_default_password_validators():
|
|
|
|
return get_password_validators(settings.AUTH_PASSWORD_VALIDATORS)
|
|
|
|
|
|
|
|
|
|
|
|
def get_password_validators(validator_config):
|
|
|
|
validators = []
|
|
|
|
for validator in validator_config:
|
|
|
|
try:
|
|
|
|
klass = import_string(validator['NAME'])
|
|
|
|
except ImportError:
|
|
|
|
msg = "The module in NAME could not be imported: %s. Check your AUTH_PASSWORD_VALIDATORS setting."
|
|
|
|
raise ImproperlyConfigured(msg % validator['NAME'])
|
|
|
|
validators.append(klass(**validator.get('OPTIONS', {})))
|
|
|
|
|
|
|
|
return validators
|
|
|
|
|
|
|
|
|
|
|
|
def validate_password(password, user=None, password_validators=None):
|
|
|
|
"""
|
|
|
|
Validate whether the password meets all validator requirements.
|
|
|
|
|
|
|
|
If the password is valid, return ``None``.
|
|
|
|
If the password is invalid, raise ValidationError with all error messages.
|
|
|
|
"""
|
|
|
|
errors = []
|
|
|
|
if password_validators is None:
|
|
|
|
password_validators = get_default_password_validators()
|
|
|
|
for validator in password_validators:
|
|
|
|
try:
|
|
|
|
validator.validate(password, user)
|
|
|
|
except ValidationError as error:
|
2015-06-09 01:27:47 +08:00
|
|
|
errors.append(error)
|
2015-03-08 22:07:57 +08:00
|
|
|
if errors:
|
|
|
|
raise ValidationError(errors)
|
|
|
|
|
|
|
|
|
|
|
|
def password_changed(password, user=None, password_validators=None):
|
|
|
|
"""
|
|
|
|
Inform all validators that have implemented a password_changed() method
|
|
|
|
that the password has been changed.
|
|
|
|
"""
|
|
|
|
if password_validators is None:
|
|
|
|
password_validators = get_default_password_validators()
|
|
|
|
for validator in password_validators:
|
|
|
|
password_changed = getattr(validator, 'password_changed', lambda *a: None)
|
|
|
|
password_changed(password, user)
|
|
|
|
|
|
|
|
|
|
|
|
def password_validators_help_texts(password_validators=None):
|
|
|
|
"""
|
|
|
|
Return a list of all help texts of all configured validators.
|
|
|
|
"""
|
|
|
|
help_texts = []
|
|
|
|
if password_validators is None:
|
|
|
|
password_validators = get_default_password_validators()
|
|
|
|
for validator in password_validators:
|
|
|
|
help_texts.append(validator.get_help_text())
|
|
|
|
return help_texts
|
|
|
|
|
|
|
|
|
2016-05-06 18:23:52 +08:00
|
|
|
def _password_validators_help_text_html(password_validators=None):
|
2015-03-08 22:07:57 +08:00
|
|
|
"""
|
|
|
|
Return an HTML string with all help texts of all configured validators
|
|
|
|
in an <ul>.
|
|
|
|
"""
|
|
|
|
help_texts = password_validators_help_texts(password_validators)
|
|
|
|
help_items = [format_html('<li>{}</li>', help_text) for help_text in help_texts]
|
2015-09-26 05:32:23 +08:00
|
|
|
return '<ul>%s</ul>' % ''.join(help_items) if help_items else ''
|
2016-11-13 01:11:23 +08:00
|
|
|
|
|
|
|
|
2016-05-06 18:23:52 +08:00
|
|
|
password_validators_help_text_html = lazy(_password_validators_help_text_html, text_type)
|
2015-03-08 22:07:57 +08:00
|
|
|
|
|
|
|
|
|
|
|
class MinimumLengthValidator(object):
|
|
|
|
"""
|
|
|
|
Validate whether the password is of a minimum length.
|
|
|
|
"""
|
|
|
|
def __init__(self, min_length=8):
|
|
|
|
self.min_length = min_length
|
|
|
|
|
|
|
|
def validate(self, password, user=None):
|
|
|
|
if len(password) < self.min_length:
|
2015-06-09 01:27:47 +08:00
|
|
|
raise ValidationError(
|
2015-10-10 21:12:55 +08:00
|
|
|
ungettext(
|
|
|
|
"This password is too short. It must contain at least %(min_length)d character.",
|
|
|
|
"This password is too short. It must contain at least %(min_length)d characters.",
|
|
|
|
self.min_length
|
|
|
|
),
|
2015-06-09 01:27:47 +08:00
|
|
|
code='password_too_short',
|
|
|
|
params={'min_length': self.min_length},
|
|
|
|
)
|
2015-03-08 22:07:57 +08:00
|
|
|
|
|
|
|
def get_help_text(self):
|
2015-10-10 21:12:55 +08:00
|
|
|
return ungettext(
|
|
|
|
"Your password must contain at least %(min_length)d character.",
|
|
|
|
"Your password must contain at least %(min_length)d characters.",
|
|
|
|
self.min_length
|
|
|
|
) % {'min_length': self.min_length}
|
2015-03-08 22:07:57 +08:00
|
|
|
|
|
|
|
|
|
|
|
class UserAttributeSimilarityValidator(object):
|
|
|
|
"""
|
|
|
|
Validate whether the password is sufficiently different from the user's
|
|
|
|
attributes.
|
|
|
|
|
|
|
|
If no specific attributes are provided, look at a sensible list of
|
|
|
|
defaults. Attributes that don't exist are ignored. Comparison is made to
|
|
|
|
not only the full attribute value, but also its components, so that, for
|
|
|
|
example, a password is validated against either part of an email address,
|
|
|
|
as well as the full address.
|
|
|
|
"""
|
|
|
|
DEFAULT_USER_ATTRIBUTES = ('username', 'first_name', 'last_name', 'email')
|
|
|
|
|
|
|
|
def __init__(self, user_attributes=DEFAULT_USER_ATTRIBUTES, max_similarity=0.7):
|
|
|
|
self.user_attributes = user_attributes
|
|
|
|
self.max_similarity = max_similarity
|
|
|
|
|
|
|
|
def validate(self, password, user=None):
|
|
|
|
if not user:
|
|
|
|
return
|
|
|
|
|
|
|
|
for attribute_name in self.user_attributes:
|
|
|
|
value = getattr(user, attribute_name, None)
|
|
|
|
if not value or not isinstance(value, string_types):
|
|
|
|
continue
|
2016-09-17 00:15:00 +08:00
|
|
|
value_parts = re.split(r'\W+', value) + [value]
|
2015-03-08 22:07:57 +08:00
|
|
|
for value_part in value_parts:
|
2016-11-10 19:30:38 +08:00
|
|
|
if SequenceMatcher(a=password.lower(), b=value_part.lower()).quick_ratio() >= self.max_similarity:
|
2016-07-22 16:51:38 +08:00
|
|
|
try:
|
|
|
|
verbose_name = force_text(user._meta.get_field(attribute_name).verbose_name)
|
|
|
|
except FieldDoesNotExist:
|
|
|
|
verbose_name = attribute_name
|
2015-06-09 01:27:47 +08:00
|
|
|
raise ValidationError(
|
|
|
|
_("The password is too similar to the %(verbose_name)s."),
|
|
|
|
code='password_too_similar',
|
|
|
|
params={'verbose_name': verbose_name},
|
|
|
|
)
|
2015-03-08 22:07:57 +08:00
|
|
|
|
|
|
|
def get_help_text(self):
|
|
|
|
return _("Your password can't be too similar to your other personal information.")
|
|
|
|
|
|
|
|
|
|
|
|
class CommonPasswordValidator(object):
|
|
|
|
"""
|
|
|
|
Validate whether the password is a common password.
|
|
|
|
|
|
|
|
The password is rejected if it occurs in a provided list, which may be gzipped.
|
|
|
|
The list Django ships with contains 1000 common passwords, created by Mark Burnett:
|
|
|
|
https://xato.net/passwords/more-top-worst-passwords/
|
|
|
|
"""
|
2015-06-09 01:27:47 +08:00
|
|
|
DEFAULT_PASSWORD_LIST_PATH = os.path.join(
|
|
|
|
os.path.dirname(os.path.realpath(upath(__file__))), 'common-passwords.txt.gz'
|
|
|
|
)
|
2015-03-08 22:07:57 +08:00
|
|
|
|
|
|
|
def __init__(self, password_list_path=DEFAULT_PASSWORD_LIST_PATH):
|
|
|
|
try:
|
2016-08-05 07:45:14 +08:00
|
|
|
with gzip.open(password_list_path) as f:
|
|
|
|
common_passwords_lines = f.read().decode('utf-8').splitlines()
|
2015-03-08 22:07:57 +08:00
|
|
|
except IOError:
|
2015-06-16 23:02:27 +08:00
|
|
|
with open(password_list_path) as f:
|
|
|
|
common_passwords_lines = f.readlines()
|
|
|
|
|
2015-03-08 22:07:57 +08:00
|
|
|
self.passwords = {p.strip() for p in common_passwords_lines}
|
|
|
|
|
|
|
|
def validate(self, password, user=None):
|
|
|
|
if password.lower().strip() in self.passwords:
|
2015-06-09 01:27:47 +08:00
|
|
|
raise ValidationError(
|
|
|
|
_("This password is too common."),
|
|
|
|
code='password_too_common',
|
|
|
|
)
|
2015-03-08 22:07:57 +08:00
|
|
|
|
|
|
|
def get_help_text(self):
|
|
|
|
return _("Your password can't be a commonly used password.")
|
|
|
|
|
|
|
|
|
|
|
|
class NumericPasswordValidator(object):
|
|
|
|
"""
|
|
|
|
Validate whether the password is alphanumeric.
|
|
|
|
"""
|
|
|
|
def validate(self, password, user=None):
|
|
|
|
if password.isdigit():
|
2015-06-09 01:27:47 +08:00
|
|
|
raise ValidationError(
|
|
|
|
_("This password is entirely numeric."),
|
|
|
|
code='password_entirely_numeric',
|
|
|
|
)
|
2015-03-08 22:07:57 +08:00
|
|
|
|
|
|
|
def get_help_text(self):
|
|
|
|
return _("Your password can't be entirely numeric.")
|