Skip to content

Commit

Permalink
Simplify auth.authenticate
Browse files Browse the repository at this point in the history
Greatly simplify the logic by using early returns.
  • Loading branch information
hmpf committed Nov 13, 2023
1 parent 7d71130 commit 0b86755
Showing 1 changed file with 28 additions and 32 deletions.
60 changes: 28 additions & 32 deletions python/nav/web/auth/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,57 +49,53 @@ 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.
try:
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):
Expand Down

0 comments on commit 0b86755

Please sign in to comment.