Skip to content

Commit 65760b2

Browse files
committed
Simplify auth.authenticate
Greatly simplify the logic by using early returns.
1 parent 3ceacf5 commit 65760b2

File tree

1 file changed

+27
-32
lines changed

1 file changed

+27
-32
lines changed

python/nav/web/auth/__init__.py

+27-32
Original file line numberDiff line numberDiff line change
@@ -49,57 +49,52 @@ def authenticate(username, password):
4949
Returns account object if user was authenticated, else None.
5050
"""
5151
# FIXME Log stuff?
52-
auth = False
53-
account = None
5452

5553
# Try to find the account in the database. If it's not found we can try
5654
# LDAP.
5755
try:
5856
account = Account.objects.get(login__iexact=username)
5957
except Account.DoesNotExist:
6058
if ldap.available:
61-
user = ldap.authenticate(username, password)
59+
ldap_user = ldap.authenticate(username, password)
6260
# If we authenticated, store the user in database.
63-
if user:
61+
if ldap_user:
6462
account = Account(
65-
login=user.username, name=user.get_real_name(), ext_sync='ldap'
63+
login=ldap_user.username,
64+
name=ldap_user.get_real_name(),
65+
ext_sync='ldap',
6666
)
67-
account.set_password(password)
68-
account.save()
69-
_handle_ldap_admin_status(user, account)
67+
account = update_ldap_user(ldap_user, account, password)
7068
# We're authenticated now
71-
auth = True
69+
return account
70+
# No account, bail out
71+
return None
7272

73-
if account and account.locked:
73+
if account.locked:
7474
_logger.info("Locked user %s tried to log in", account.login)
75+
return None
7576

76-
if (
77-
account
78-
and account.ext_sync == 'ldap'
79-
and ldap.available
80-
and not auth
81-
and not account.locked
82-
):
77+
if account.ext_sync == 'ldap' and ldap.available:
8378
try:
84-
auth = ldap.authenticate(username, password)
79+
ldap_user = ldap.authenticate(username, password)
8580
except ldap.NoAnswerError:
86-
# Fallback to stored password if ldap is unavailable
87-
auth = False
81+
pass
8882
else:
89-
if auth:
90-
account.set_password(password)
91-
account.save()
92-
_handle_ldap_admin_status(auth, account)
93-
else:
94-
return
83+
if ldap_user:
84+
account = update_ldap_user(ldap_user, account, password)
85+
return account
86+
# Fallback to stored password if ldap is unavailable
9587

96-
if account and not auth:
97-
auth = account.check_password(password)
98-
99-
if auth and account:
88+
if account.check_password(password):
10089
return account
101-
else:
102-
return None
90+
return None
91+
92+
93+
def update_ldap_user(ldap_user, account, password):
94+
account.set_password(password)
95+
account.save()
96+
_handle_ldap_admin_status(ldap_user, account)
97+
return account
10398

10499

105100
def _handle_ldap_admin_status(ldap_user, nav_account):

0 commit comments

Comments
 (0)