From 0b867555b53fa03f5521b98e4ded917f707f6060 Mon Sep 17 00:00:00 2001 From: Hanne Moa Date: Fri, 10 Nov 2023 11:19:15 +0100 Subject: [PATCH] Simplify auth.authenticate Greatly simplify the logic by using early returns. --- python/nav/web/auth/__init__.py | 60 +++++++++++++++------------------ 1 file changed, 28 insertions(+), 32 deletions(-) diff --git a/python/nav/web/auth/__init__.py b/python/nav/web/auth/__init__.py index 142a0d4e5f..887e0b8686 100644 --- a/python/nav/web/auth/__init__.py +++ b/python/nav/web/auth/__init__.py @@ -49,8 +49,6 @@ def authenticate(username, password): Returns account object if user was authenticated, else None. """ # FIXME Log stuff? - auth = False - account = None # Try to find the account in the database. If it's not found we can try # LDAP. @@ -58,48 +56,46 @@ def authenticate(username, password): account = Account.objects.get(login__iexact=username) except Account.DoesNotExist: if ldap.available: - user = ldap.authenticate(username, password) + ldap_user = ldap.authenticate(username, password) # If we authenticated, store the user in database. - if user: + if ldap_user: account = Account( - login=user.username, name=user.get_real_name(), ext_sync='ldap' + login=ldap_user.username, + name=ldap_user.get_real_name(), + ext_sync='ldap', ) - account.set_password(password) - account.save() - _handle_ldap_admin_status(user, account) + account = update_ldap_user(ldap_user, account, password) # We're authenticated now - auth = True + return account + # No account, bail out + return None - if account and account.locked: + if account.locked: _logger.info("Locked user %s tried to log in", account.login) + return None - if ( - account - and account.ext_sync == 'ldap' - and ldap.available - and not auth - and not account.locked - ): + if account.ext_sync == 'ldap' and ldap.available: try: - auth = ldap.authenticate(username, password) + ldap_user = ldap.authenticate(username, password) except ldap.NoAnswerError: - # Fallback to stored password if ldap is unavailable - auth = False + pass else: - if auth: - account.set_password(password) - account.save() - _handle_ldap_admin_status(auth, account) - else: - return + if ldap_user: + account = update_ldap_user(ldap_user, account, password) + return account + return None + # Fallback to stored password if ldap is unavailable - if account and not auth: - auth = account.check_password(password) - - if auth and account: + if account.check_password(password): return account - else: - return None + return None + + +def update_ldap_user(ldap_user, account, password): + account.set_password(password) + account.save() + _handle_ldap_admin_status(ldap_user, account) + return account def _handle_ldap_admin_status(ldap_user, nav_account):