refactoring: improve reusability by encapsulating access to app_settings in methods

If you want to inherit from our base backend or password hasher you
don't need to depend upon our way of handling settings.
This commit is contained in:
Benjamin Dauvergne 2014-08-09 20:08:34 +02:00
parent 2cb06046b8
commit 8ea791cf98
2 changed files with 17 additions and 6 deletions

View File

@ -34,13 +34,17 @@ class KerberosBackend(ModelBackend):
user.is_superuser = True
user.save()
def should_create_user(self):
'''Should we create users for new principals ?'''
return app_settings.BACKEND_CREATE
def lookup_user(self, principal):
'''Find the user model linked to this principal'''
User = get_user_model()
username_field = getattr(User, 'USERNAME_FIELD', 'username')
username = self.username_from_principal(principal)
kwargs = {username_field: username}
if app_settings.BACKEND_CREATE:
if self.should_create_user():
user, created = User.objects.get_or_create(**kwargs)
if created:
user.set_unusable_password()

View File

@ -14,18 +14,25 @@ class KerberosHasher(BasePasswordHasher):
match a given Kerberos identity'''
algorithm = 'kerberos'
def default_realm(self):
'''Default realm for usernames without a realm'''
return app_settings.DEFAULT_REALM
def service_principal(self):
if not app_settings.SERVICE_PRINCIPAL:
raise ImproperlyConfigured('Kerberos pseudo password hasher needs '
'the setting KERBEROS_SERVICE_PRINCIPAL to be '
'set')
return app_settings.SERVICE_PRINCIPAL
def verify(self, password, encoded):
algorithm, principal = encoded.split('$', 2)
assert algorithm == self.algorithm
principal = force_bytes(principal)
password = force_bytes(password)
if not app_settings.SERVICE_PRINCIPAL:
raise ImproperlyConfigured('Kerberos pseudo password hasher needs '
'the setting KERBEROS_SERVICE_PRINCIPAL to be '
'set')
try:
return kerberos.checkPassword(principal, password,
app_settings.SERVICE_PRINCIPAL)
self.service_principal(), self.default_realm())
except kerberos.KrbError, e:
logging.getLogger(__name__).error('password validation'
'for principal %r failed %s', principal, e)