summaryrefslogtreecommitdiff
path: root/passlib/ext
diff options
context:
space:
mode:
authorEli Collins <elic@assurancetechnologies.com>2015-07-22 13:17:33 -0400
committerEli Collins <elic@assurancetechnologies.com>2015-07-22 13:17:33 -0400
commitf3dae73a09335aafb52e3636f1554be6462b53e5 (patch)
treecd32afcc0ee7f8fdb0e7ad9a726ee8708a9fb252 /passlib/ext
parent7ac268ac66f8d991c74adfa5eada56886c0452e1 (diff)
downloadpasslib-f3dae73a09335aafb52e3636f1554be6462b53e5.tar.gz
passlib.ext.django cleanups
* stripped out support for django 1.4/1.5; removes a TON of edge cases we no longer need. * added formal MIN_DJANGO_VERSION constant, moved version check to models._apply() so test cases don't throw error if older django is present. * monkeypatcher now supports passed wrapped function as first argument, simplifies imports & calls w/in models.py
Diffstat (limited to 'passlib/ext')
-rw-r--r--passlib/ext/django/models.py56
-rw-r--r--passlib/ext/django/utils.py28
2 files changed, 37 insertions, 47 deletions
diff --git a/passlib/ext/django/models.py b/passlib/ext/django/models.py
index cab355b..9ef4188 100644
--- a/passlib/ext/django/models.py
+++ b/passlib/ext/django/models.py
@@ -12,7 +12,7 @@ from django.conf import settings
from passlib.context import CryptContext
from passlib.exc import ExpectedTypeError
from passlib.ext.django.utils import _PatchManager, hasher_to_passlib_name, \
- get_passlib_hasher, get_preset_config
+ get_passlib_hasher, get_preset_config, MIN_DJANGO_VERSION
from passlib.utils.compat import unicode
# local
__all__ = ["password_context"]
@@ -50,41 +50,24 @@ def _apply_patch():
assumes the caller will configure the object.
"""
#
- # setup constants
+ # setup environment & patch-paths
#
+ if VERSION < MIN_DJANGO_VERSION:
+ raise RuntimeError("passlib.ext.django requires django >= %s" % (MIN_DJANGO_VERSION,))
+
log.debug("preparing to monkeypatch 'django.contrib.auth' ...")
global _patched
assert not _patched, "monkeypatching already applied"
+
HASHERS_PATH = "django.contrib.auth.hashers"
MODELS_PATH = "django.contrib.auth.models"
USER_PATH = MODELS_PATH + ":User"
FORMS_PATH = "django.contrib.auth.forms"
#
- # import UNUSABLE_PASSWORD and is_password_usable() helpers
+ # import some helpers from hashers module
#
- assert VERSION >= (1,4), "sanity check, should have been caught by passlib.ext.django.utils"
- if VERSION < (1,6):
- from django.contrib.auth.hashers import UNUSABLE_PASSWORD, is_password_usable
-
- # NOTE: 1.4 .. 1.5 - empty passwords not valid.
- def is_valid_secret(secret):
- return bool(secret)
-
- def make_unusable_password():
- return UNUSABLE_PASSWORD
- else:
- from django.contrib.auth.hashers import is_password_usable, make_password
-
- # 1.6 - empty passwords valid again
- def is_valid_secret(secret):
- return secret is not None
-
- def make_unusable_password():
- return make_password(None)
-
- # django 1.4.6+ uses a separate hasher for "sha1$$digest" hashes
- has_unsalted_sha1 = (VERSION >= (1,4,6))
+ from django.contrib.auth.hashers import is_password_usable
#
# patch ``User.set_password() & ``User.check_password()`` to use
@@ -95,18 +78,18 @@ def _apply_patch():
@_manager.monkeypatch(USER_PATH)
def set_password(user, password):
"""passlib replacement for User.set_password()"""
- if is_valid_secret(password):
+ if password is None:
+ user.set_unusable_password()
+ else:
# NOTE: pulls _get_category from module globals
cat = _get_category(user)
user.password = password_context.encrypt(password, category=cat)
- else:
- user.set_unusable_password()
@_manager.monkeypatch(USER_PATH)
def check_password(user, password):
"""passlib replacement for User.check_password()"""
hash = user.password
- if not is_valid_secret(password) or not is_password_usable(hash):
+ if password is None or not is_password_usable(hash):
return False
# NOTE: pulls _get_category from module globals
cat = _get_category(user)
@@ -127,7 +110,7 @@ def _apply_patch():
"""passlib replacement for check_password()"""
# XXX: this currently ignores "preferred" keyword, since its purpose
# was for hash migration, and that's handled by the context.
- if not is_valid_secret(password) or not is_password_usable(encoded):
+ if password is None or not is_password_usable(encoded):
return False
ok = password_context.verify(password, encoded)
if ok and setter and password_context.needs_update(encoded):
@@ -138,12 +121,12 @@ def _apply_patch():
# patch the other functions defined in the ``hashers`` module, as well
# as any other known locations where they're imported within ``contrib.auth``
#
- @_manager.monkeypatch(HASHERS_PATH)
- @_manager.monkeypatch(MODELS_PATH)
- def make_password(password, salt=None, hasher="default"):
+ @_manager.monkeypatch(HASHERS_PATH, wrap=True)
+ @_manager.monkeypatch(MODELS_PATH, wrap=True)
+ def make_password(__wrapped__, password, salt=None, hasher="default"):
"""passlib replacement for make_password()"""
- if not is_valid_secret(password):
- return make_unusable_password()
+ if password is None:
+ return __wrapped__(None)
if hasher == "default":
scheme = None
else:
@@ -186,8 +169,7 @@ def _apply_patch():
handler = password_context.identify(encoded, resolve=True,
required=True)
algorithm = None
- if (has_unsalted_sha1 and handler.name == "django_salted_sha1" and
- encoded.startswith("sha1$$")):
+ if handler.name == "django_salted_sha1" and encoded.startswith("sha1$$"):
# django 1.4.6+ uses a separate hasher for "sha1$$digest" hashes,
# but passlib just reuses the "sha1$salt$digest" handler.
# we want to resolve to correct django hasher.
diff --git a/passlib/ext/django/utils.py b/passlib/ext/django/utils.py
index a3132fd..8e70a51 100644
--- a/passlib/ext/django/utils.py
+++ b/passlib/ext/django/utils.py
@@ -3,6 +3,7 @@
# imports
#=============================================================================
# core
+from functools import update_wrapper
import logging; log = logging.getLogger(__name__)
from weakref import WeakKeyDictionary
from warnings import warn
@@ -13,9 +14,6 @@ try:
except ImportError:
log.debug("django installation not found")
DJANGO_VERSION = ()
-else:
- if DJANGO_VERSION < (1,4):
- raise RuntimeError("passlib.ext.django requires django >= 1.4 (as of passlib 1.7)")
# pkg
from passlib.context import CryptContext
from passlib.exc import PasslibRuntimeWarning
@@ -24,10 +22,15 @@ from passlib.utils import classproperty
from passlib.utils.compat import get_method_function, iteritems, OrderedDict
# local
__all__ = [
+ "DJANGO_VERSION",
+ "MIN_DJANGO_VERSION",
"get_preset_config",
"get_passlib_hasher",
]
+#: minimum version supported by passlib.ext.django
+MIN_DJANGO_VERSION = (1, 6)
+
#=============================================================================
# default policies
#=============================================================================
@@ -58,10 +61,7 @@ def get_preset_config(name):
if not DJANGO_VERSION:
raise ValueError("can't resolve django-default preset, "
"django not installed")
- if DJANGO_VERSION < (1,6):
- name = "django-1.4"
- else:
- name = "django-1.6"
+ name = "django-1.6"
if name == "passlib-default":
return PASSLIB_DEFAULT
try:
@@ -435,7 +435,7 @@ class _PatchManager(object):
else:
setattr(obj, attr, value)
- def patch(self, path, value):
+ def patch(self, path, value, wrap=False):
"""monkeypatch object+attr at <path> to have <value>, stores original"""
assert value != _UNSET
current = self._get_path(path)
@@ -449,6 +449,14 @@ class _PatchManager(object):
if not self._is_same_value(current, expected):
warn("overridding resource another library has patched: %r"
% path, PasslibRuntimeWarning)
+ if wrap:
+ assert callable(value)
+ wrapped = orig
+ wrapped_by = value
+ def wrapper(*args, **kwds):
+ return wrapped_by(wrapped, *args, **kwds)
+ update_wrapper(wrapper, value)
+ value = wrapper
self._set_path(path, value)
self._state[path] = (orig, value)
@@ -457,13 +465,13 @@ class _PatchManager(object):
## for path, value in iteritems(kwds):
## self.patch(path, value)
- def monkeypatch(self, parent, name=None, enable=True):
+ def monkeypatch(self, parent, name=None, enable=True, wrap=False):
"""function decorator which patches function of same name in <parent>"""
def builder(func):
if enable:
sep = "." if ":" in parent else ":"
path = parent + sep + (name or func.__name__)
- self.patch(path, func)
+ self.patch(path, func, wrap=wrap)
return func
return builder