Skip to content

Commit 33d80a2

Browse files
pandafynemesifier
authored andcommitted
[fix] Prevent authentication without a username in UsersAuthenticationBackend
Some authentication backends (such as token-based or external identity providers) may invoke this backend without supplying a username. In such cases, the backend would previously continue and attempt to query the database with `None` as the username. This can lead to inefficient or broad queries that negatively impact performance, especially in large user tables.
1 parent 7da5bb3 commit 33d80a2

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

openwisp_users/backends.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@
1111

1212
class UsersAuthenticationBackend(ModelBackend):
1313
def authenticate(self, request, username=None, password=None, **kwargs):
14+
# Only proceed if a username is provided. Other auth backends may attempt
15+
# authentication without a username; returning early here avoids querying
16+
# the database with a `None` username, which can be inefficient.
17+
if not username:
18+
return
1419
for user in self.get_users(username):
1520
if user.check_password(password) and self.user_can_authenticate(user):
1621
return user

openwisp_users/tests/test_backends.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,3 +153,13 @@ def test_partial_phone_number(self):
153153
password="tester2",
154154
)
155155
self.assertEqual(auth_backend.get_users("911524370").count(), 0)
156+
157+
@mock.patch("openwisp_users.backends.UsersAuthenticationBackend.get_users")
158+
def test_user_auth_without_email(self, mocked_get_users):
159+
self._create_user(
160+
username="tester",
161+
password="tester",
162+
email=None,
163+
)
164+
self.client.login(username=None, password=None)
165+
mocked_get_users.assert_not_called()

0 commit comments

Comments
 (0)