Skip to content

Commit

Permalink
Check attempts is truthy before int comparison
Browse files Browse the repository at this point in the history
closes #2617
  • Loading branch information
ukanga committed Jun 24, 2024
1 parent e0d1932 commit 037bfc0
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
12 changes: 8 additions & 4 deletions onadata/apps/api/tests/viewsets/test_connect_viewset.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
"""
Test /user API endpoint
"""
import json
from datetime import datetime, timedelta
from unittest.mock import patch

Expand Down Expand Up @@ -474,11 +475,14 @@ def test_login_attempts(self, send_account_lockout_email):
# cache value increments with subsequent attempts
response = view(request)
self.assertEqual(response.status_code, 401)
response.render()
self.assertEqual(
response.data["detail"],
"Invalid username/password. For security reasons, "
"after 8 more failed login attempts you'll have to "
"wait 30 minutes before trying again.",
json.loads(response.content.decode()),
{
"detail": "Invalid username/password. For security reasons, "
"after 8 more failed login attempts you'll have to "
"wait 30 minutes before trying again."
},
)
self.assertEqual(cache.get(safe_key(f"login_attempts-{request_ip}-bob")), 2)

Expand Down
6 changes: 4 additions & 2 deletions onadata/libs/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,9 @@ def login_attempts(request):
if attempts:
cache.incr(attempts_key)
attempts = cache.get(attempts_key)
if attempts >= getattr(settings, "MAX_LOGIN_ATTEMPTS", 10):
if attempts is not None and attempts >= getattr(
settings, "MAX_LOGIN_ATTEMPTS", 10
):
lockout_key = safe_key(f"{LOCKOUT_IP}{ip_address}-{username}")
lockout = cache.get(lockout_key)
if not lockout:
Expand All @@ -321,7 +323,7 @@ def login_attempts(request):
)
check_lockout(request)
return attempts
return attempts
return attempts if attempts is not None else 0

cache.set(attempts_key, 1)

Expand Down

0 comments on commit 037bfc0

Please sign in to comment.