Skip to content

Commit

Permalink
Avoid using __file__ at module level in django.contrib.auth.password_…
Browse files Browse the repository at this point in the history
…validation

The `CommonPasswordValidator`-class constant `DEFAULT_PASSWORD_LIST_PATH` is
used only in one place, the class's instance constructor. While the nature of
`DEFAULT_PASSWORD_LIST_PATH` is not documented, its existence is inside the docs
for the [constructor's signature]. I've changed `DEFAULT_PASSWORD_LIST_PATH`
from a class constant into an instance attribute. Another possibility is making
`DEFAULT_PASSWORD_LIST_PATH` be a `django.utils.functional.classproperty`.

[constructor's signature]: https://docs.djangoproject.com/en/3.1/topics/auth/passwords/#django.contrib.auth.password_validation.CommonPasswordValidator
  • Loading branch information
wkschwartz committed Jan 4, 2021
1 parent 07f46b7 commit 24aa80b
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion django/contrib/auth/password_validation.py
Expand Up @@ -167,9 +167,20 @@ class CommonPasswordValidator:
https://gist.github.com/roycewilliams/281ce539915a947a23db17137d91aeb7
The password list must be lowercased to match the comparison in validate().
"""
DEFAULT_PASSWORD_LIST_PATH = Path(__file__).resolve().parent / 'common-passwords.txt.gz'

@property
def DEFAULT_PASSWORD_LIST_PATH(self):
if not hasattr(self, "_DEFAULT_PASSWORD_LIST_PATH"):
self._DEFAULT_PASSWORD_LIST_PATH = Path(__file__).resolve().parent / 'common-passwords.txt.gz'
return self._DEFAULT_PASSWORD_LIST_PATH

@DEFAULT_PASSWORD_LIST_PATH.setter
def DEFAULT_PASSWORD_LIST_PATH(self, value):
self._DEFAULT_PASSWORD_LIST_PATH = value

def __init__(self, password_list_path=DEFAULT_PASSWORD_LIST_PATH):
if password_list_path is CommonPasswordValidator.DEFAULT_PASSWORD_LIST_PATH:
password_list_path = self.DEFAULT_PASSWORD_LIST_PATH
try:
with gzip.open(password_list_path, 'rt', encoding='utf-8') as f:
self.passwords = {x.strip() for x in f}
Expand Down

0 comments on commit 24aa80b

Please sign in to comment.