2019-10-07 14:33:48 +00:00
|
|
|
"""user field matcher models"""
|
|
|
|
import re
|
|
|
|
|
|
|
|
from django.db import models
|
|
|
|
from django.utils.translation import gettext as _
|
|
|
|
from structlog import get_logger
|
|
|
|
|
2020-05-16 16:07:00 +00:00
|
|
|
from passbook.policies.models import Policy
|
2020-02-20 12:52:05 +00:00
|
|
|
from passbook.policies.types import PolicyRequest, PolicyResult
|
2019-10-07 14:33:48 +00:00
|
|
|
|
|
|
|
LOGGER = get_logger()
|
|
|
|
|
|
|
|
|
|
|
|
class PasswordPolicy(Policy):
|
|
|
|
"""Policy to make sure passwords have certain properties"""
|
|
|
|
|
2020-07-10 18:43:35 +00:00
|
|
|
password_field = models.TextField(
|
|
|
|
default="password",
|
|
|
|
help_text=_(
|
|
|
|
"Field key to check, field keys defined in Prompt stages are available."
|
|
|
|
),
|
|
|
|
)
|
|
|
|
|
2019-10-07 14:33:48 +00:00
|
|
|
amount_uppercase = models.IntegerField(default=0)
|
|
|
|
amount_lowercase = models.IntegerField(default=0)
|
|
|
|
amount_symbols = models.IntegerField(default=0)
|
|
|
|
length_min = models.IntegerField(default=0)
|
|
|
|
symbol_charset = models.TextField(default=r"!\"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ ")
|
|
|
|
error_message = models.TextField()
|
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
form = "passbook.policies.password.forms.PasswordPolicyForm"
|
2019-10-07 14:33:48 +00:00
|
|
|
|
|
|
|
def passes(self, request: PolicyRequest) -> PolicyResult:
|
2020-07-10 18:43:35 +00:00
|
|
|
if self.password_field not in request.context:
|
|
|
|
LOGGER.warning(
|
|
|
|
"Password field not set in Policy Request",
|
|
|
|
field=self.password_field,
|
|
|
|
fields=request.context.keys(),
|
|
|
|
)
|
|
|
|
password = request.context[self.password_field]
|
2019-10-07 14:33:48 +00:00
|
|
|
|
2020-07-10 18:43:35 +00:00
|
|
|
filter_regex = []
|
2019-10-07 14:33:48 +00:00
|
|
|
if self.amount_lowercase > 0:
|
2020-07-10 18:43:35 +00:00
|
|
|
filter_regex.append(r"[a-z]{%d,}" % self.amount_lowercase)
|
2019-10-07 14:33:48 +00:00
|
|
|
if self.amount_uppercase > 0:
|
2020-07-10 18:43:35 +00:00
|
|
|
filter_regex.append(r"[A-Z]{%d,}" % self.amount_uppercase)
|
2019-10-07 14:33:48 +00:00
|
|
|
if self.amount_symbols > 0:
|
2020-07-10 18:43:35 +00:00
|
|
|
filter_regex.append(
|
|
|
|
r"[%s]{%d,}" % (self.symbol_charset, self.amount_symbols)
|
|
|
|
)
|
|
|
|
full_regex = "|".join(filter_regex)
|
|
|
|
LOGGER.debug("Built regex", regexp=full_regex)
|
|
|
|
result = bool(re.compile(full_regex).match(password))
|
|
|
|
|
|
|
|
result = result and len(password) >= self.length_min
|
|
|
|
|
2019-10-07 14:33:48 +00:00
|
|
|
if not result:
|
|
|
|
return PolicyResult(result, self.error_message)
|
|
|
|
return PolicyResult(result)
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
verbose_name = _("Password Policy")
|
|
|
|
verbose_name_plural = _("Password Policies")
|