Skip to content

Commit

Permalink
Ajustes para controle de login. #1450
Browse files Browse the repository at this point in the history
  • Loading branch information
viniciusandrade committed May 2, 2024
1 parent 5440513 commit c016bf4
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
4 changes: 2 additions & 2 deletions bireme/fi-admin/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@
# maintenance mode
'utils.middleware.MaintenanceModeMiddleware',
# secure login from brute force attack
#'utils.middleware.BruteForceProtectionMiddleware',
'utils.middleware.BruteForceProtectionMiddleware',
]


Expand Down Expand Up @@ -326,7 +326,7 @@
EMAIL_HOST_PASSWORD = os.environ.get("EMAIL_HOST_PASSWORD")
EMAIL_FROM = os.environ.get("EMAIL_FROM")

BRUTE_FORCE_THRESHOLD = int(os.environ.get("BRUTE_FORCE_THRESHOLD", 3)) # Number of failed login attempts
BRUTE_FORCE_THRESHOLD = int(os.environ.get("BRUTE_FORCE_THRESHOLD", 5)) # Number of failed login attempts
BRUTE_FORCE_TIMEOUT = int(os.environ.get("BRUTE_FORCE_TIMEOUT", 300)) # Lock the user out for X seconds

# form actions
Expand Down
20 changes: 16 additions & 4 deletions bireme/utils/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,30 @@ def __call__(self, request):
if request.path == settings.LOGIN_URL and request.method == "POST":

# Get the IP address of the client
ip_address = request.META.get("REMOTE_ADDR")
# If request is using proxy extract IP from FORWARDED list
x_forward_for = request.META.get('HTTP_X_FORWARDED_FOR', None)
if x_forward_for:
ip_address = x_forward_for.split(',')[0]
else:
ip_address = request.META.get('REMOTE_ADDR')

# debug
print(ip_address)

# Increment the failed login attempt count for this IP address
cache_key = f"login_attempts:{ip_address}"

login_attempts = cache.get(cache_key, 0)

# Save attemp in cache
cache.set(cache_key, login_attempts + 1, timeout=settings.BRUTE_FORCE_TIMEOUT)
# debug
print(login_attempts + 1)

# Save attemp in cache if user is not being redirect to app main page (login OK - status 302)
if response.status_code != 302:
cache.set(cache_key, login_attempts + 1, timeout=settings.BRUTE_FORCE_TIMEOUT)

# If the login attempts exceed the threshold, block further attempts
if login_attempts >= settings.BRUTE_FORCE_THRESHOLD:
if login_attempts > settings.BRUTE_FORCE_THRESHOLD:
time_to_wait = settings.BRUTE_FORCE_TIMEOUT // 60
return HttpResponseForbidden(
f"Too many login attempts. Please try again later after {time_to_wait} minutes."
Expand Down

0 comments on commit c016bf4

Please sign in to comment.