Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Project(Task) : Implement Rate Limiting for Issue Creation #1791

Merged
merged 8 commits into from
Feb 17, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions blt/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,12 +193,14 @@

# SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'

# CACHES = {
# 'default': {
# 'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
# 'LOCATION': 'cache_table',
# }
# }
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'django_cache',
},
}


REST_AUTH = {
'SESSION_LOGIN': False
}
Expand Down
17 changes: 17 additions & 0 deletions website/management/commands/create_cachetable.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from django.core.management.base import BaseCommand
from django.core.management import call_command
from django.db import connection

class Command(BaseCommand):
help = 'Creates the cache table if it does not exist'

def handle(self, *args, **options):
table_name = 'django_cache'
table_exists = table_name in connection.introspection.table_names()

if table_exists:
self.stdout.write(self.style.SUCCESS(f"'{table_name}' table already exists."))
else:
# Create the cache table
call_command('createcachetable')
self.stdout.write(self.style.SUCCESS(f"'{table_name}' table created."))
24 changes: 24 additions & 0 deletions website/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
from django.http import HttpRequest
from django.core.cache import cache
from django.utils.timezone import now
from django.http import HttpResponseForbidden

def is_valid_https_url(url):
validate = URLValidator(schemes=['https']) # Only allow HTTPS URLs
Expand Down Expand Up @@ -607,6 +610,16 @@ def process_issue(self, user, obj, created, domain, tokenauth=False, score=3):
)

return HttpResponseRedirect("/")


def get_client_ip(request):
"""Extract the client's IP address from the request."""
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip

class IssueCreate(IssueBaseCreate, CreateView):
model = Issue
Expand Down Expand Up @@ -717,6 +730,14 @@ def post(self, request, *args, **kwargs):
return super().post(request, *args, **kwargs)

def form_valid(self, form):
user_or_ip = self.request.user.get_username() if self.request.user.is_authenticated else get_client_ip(self.request)
limit = 50 if self.request.user.is_authenticated else 30 # Your set limits
cache_key = f"issue_create_{user_or_ip}_{now().date()}"
issue_count = cache.get(cache_key, 0)

if issue_count >= limit:
messages.error(self.request, "You have reached your issue creation limit for today.")
return HttpResponseRedirect("/report/")

@atomic
def create_issue(self,form):
Expand Down Expand Up @@ -870,16 +891,19 @@ def create_issue(self,form):
self.request.session["created"] = domain_exists
self.request.session["domain"] = domain.id
login_url = reverse("account_login")
cache.set(cache_key, issue_count + 1, 86400) # Increment the count
messages.success(self.request, "Bug added!")
return HttpResponseRedirect("{}?next={}".format(login_url, redirect_url))

if tokenauth:
self.process_issue(
User.objects.get(id=token.user_id), obj, domain_exists, domain, True
)
cache.set(cache_key, issue_count + 1, 86400) # Increment the count
return JsonResponse("Created", safe=False)
else:
self.process_issue(self.request.user, obj, domain_exists, domain)
cache.set(cache_key, issue_count + 1, 86400) # Increment the count
return HttpResponseRedirect(redirect_url + "/")

return create_issue(self,form)
Expand Down
Loading