From dd921f8a1a2a009340624c0d40768fe664f39b28 Mon Sep 17 00:00:00 2001 From: Krrish Sehgal <133865424+krrish-sehgal@users.noreply.github.com> Date: Fri, 24 Jan 2025 13:06:27 +0530 Subject: [PATCH] reverting --- website/models.py | 10 --- website/views/company.py | 129 +++++++++++++++++++++++++++----------- website/views/core.py | 49 +++++++++++---- website/views/issue.py | 5 +- website/views/slackbot.py | 28 ++++++--- 5 files changed, 154 insertions(+), 67 deletions(-) diff --git a/website/models.py b/website/models.py index 8793a5ceb..e7a751240 100644 --- a/website/models.py +++ b/website/models.py @@ -88,13 +88,10 @@ def __str__(self): class SlackIntegration(models.Model): - integration = models.OneToOneField(Integration, on_delete=models.CASCADE, related_name="slack_integration") - bot_access_token = models.CharField(max_length=255, null=True, blank=True) # will be different for each workspace integration = models.OneToOneField(Integration, on_delete=models.CASCADE, related_name="slack_integration") bot_access_token = models.CharField(max_length=255, null=True, blank=True) # will be different for each workspace workspace_name = models.CharField(max_length=255, null=True, blank=True) default_channel_name = models.CharField(max_length=255, null=True, blank=True) # Default channel ID - default_channel_name = models.CharField(max_length=255, null=True, blank=True) # Default channel ID default_channel_id = models.CharField(max_length=255, null=True, blank=True) daily_updates = models.BooleanField(default=False) daily_update_time = models.IntegerField( @@ -109,12 +106,6 @@ class SlackIntegration(models.Model): blank=True, help_text="Custom welcome message for new members. Use Slack markdown formatting.", ) - # Add welcome message field - welcome_message = models.TextField( - null=True, - blank=True, - help_text="Custom welcome message for new members. Use Slack markdown formatting.", - ) def __str__(self): return f"Slack Integration for {self.integration.organization.name}" @@ -939,7 +930,6 @@ class Contribution(models.Model): description = models.TextField() repository = models.ForeignKey(Project, on_delete=models.CASCADE, null=True) contribution_type = models.CharField(max_length=20, choices=CONTRIBUTION_TYPES, default="commit") - contribution_type = models.CharField(max_length=20, choices=CONTRIBUTION_TYPES, default="commit") github_username = models.CharField(max_length=255, default="") github_id = models.CharField(max_length=100, null=True, blank=True) github_url = models.URLField(null=True, blank=True) diff --git a/website/views/company.py b/website/views/company.py index a26639ccd..b7a67e6a6 100644 --- a/website/views/company.py +++ b/website/views/company.py @@ -147,7 +147,9 @@ def post(self, request, *args, **kwargs): organization_url = data.get("organization_url", "") if user_domain in restricted_domain: - messages.error(request, "Login with organization email in order to create the organization.") + messages.error( + request, "Login with organization email in order to create the organization." + ) return redirect("/") if organization_name == "" or Organization.objects.filter(name=organization_name).exists(): @@ -163,7 +165,9 @@ def post(self, request, *args, **kwargs): organization_logo_file = organization_logo.name.split(".")[0] extension = organization_logo.name.split(".")[-1] organization_logo.name = f"{organization_logo_file[:99]}_{uuid.uuid4()}.{extension}" - logo_path = default_storage.save(f"organization_logos/{organization_logo.name}", organization_logo) + logo_path = default_storage.save( + f"organization_logos/{organization_logo.name}", organization_logo + ) else: logo_path = None @@ -209,16 +213,20 @@ class OrganizationDashboardAnalyticsView(View): months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] def get_general_info(self, organization): - total_organization_bugs = Issue.objects.filter(domain__organization__id=organization).count() + total_organization_bugs = Issue.objects.filter( + domain__organization__id=organization + ).count() total_bug_hunts = Hunt.objects.filter(domain__organization__id=organization).count() total_domains = Domain.objects.filter(organization__id=organization).count() # Step 1: Retrieve all hunt IDs associated with the specified organization - hunt_ids = Hunt.objects.filter(domain__organization__id=organization).values_list("id", flat=True) + hunt_ids = Hunt.objects.filter(domain__organization__id=organization).values_list( + "id", flat=True + ) # Step 2: Sum the rewarded values from issues that have a hunt_id in the hunt_ids list - total_money_distributed = Issue.objects.filter(hunt_id__in=hunt_ids).aggregate(total_money=Sum("rewarded"))[ - "total_money" - ] + total_money_distributed = Issue.objects.filter(hunt_id__in=hunt_ids).aggregate( + total_money=Sum("rewarded") + )["total_money"] total_money_distributed = 0 if total_money_distributed is None else total_money_distributed return { @@ -230,7 +238,9 @@ def get_general_info(self, organization): def get_bug_report_type_piechart_data(self, organization): bug_report_type = ( - Issue.objects.values("label").filter(domain__organization__id=organization).annotate(count=Count("label")) + Issue.objects.values("label") + .filter(domain__organization__id=organization) + .annotate(count=Count("label")) ) bug_report_type_labels = [] bug_report_type_data = [] @@ -248,7 +258,9 @@ def get_bug_report_type_piechart_data(self, organization): def get_reports_on_domain_piechart_data(self, organization): report_piechart = ( - Issue.objects.values("url").filter(domain__organization__id=organization).annotate(count=Count("url")) + Issue.objects.values("url") + .filter(domain__organization__id=organization) + .annotate(count=Count("url")) ) report_labels = [] @@ -340,17 +352,23 @@ def bug_rate_increase_descrease_weekly(self, organization, is_accepted_bugs=Fals if prev_week_issue_count == 0: percent_increase = this_week_issue_count * 100 else: - percent_increase = ((this_week_issue_count - prev_week_issue_count) / prev_week_issue_count) * 100 + percent_increase = ( + (this_week_issue_count - prev_week_issue_count) / prev_week_issue_count + ) * 100 return { "percent_increase": percent_increase, - "is_increasing": True if (this_week_issue_count - prev_week_issue_count) >= 0 else False, + "is_increasing": True + if (this_week_issue_count - prev_week_issue_count) >= 0 + else False, "this_week_issue_count": this_week_issue_count, } def get_spent_on_bugtypes(self, organization): spent_on_bugtypes = ( - Issue.objects.values("label").filter(domain__organization__id=organization).annotate(spent=Sum("rewarded")) + Issue.objects.values("label") + .filter(domain__organization__id=organization) + .annotate(spent=Sum("rewarded")) ) labels = list(self.labels.values()) data = [0 for label in labels] # make all labels spent 0 / init with 0 @@ -379,9 +397,13 @@ def get(self, request, id, *args, **kwargs): "total_info": self.get_general_info(id), "bug_report_type_piechart_data": self.get_bug_report_type_piechart_data(id), "reports_on_domain_piechart_data": self.get_reports_on_domain_piechart_data(id), - "get_current_year_monthly_reported_bar_data": self.get_current_year_monthly_reported_bar_data(id), + "get_current_year_monthly_reported_bar_data": self.get_current_year_monthly_reported_bar_data( + id + ), "bug_rate_increase_descrease_weekly": self.bug_rate_increase_descrease_weekly(id), - "accepted_bug_rate_increase_descrease_weekly": self.bug_rate_increase_descrease_weekly(id, True), + "accepted_bug_rate_increase_descrease_weekly": self.bug_rate_increase_descrease_weekly( + id, True + ), "spent_on_bugtypes": self.get_spent_on_bugtypes(id), } self.get_spent_on_bugtypes(id) @@ -471,7 +493,9 @@ def get(self, request, id, *args, **kwargs): } if sort_field in sort_mapping: - daily_status_reports = daily_status_reports.order_by(f"{sort_prefix}{sort_mapping[sort_field]}") + daily_status_reports = daily_status_reports.order_by( + f"{sort_prefix}{sort_mapping[sort_field]}" + ) context = { "organization": id, @@ -515,7 +539,11 @@ def get(self, request, id, *args, **kwargs): class OrganizationDashboardManageDomainsView(View): @validate_organization_user def get(self, request, id, *args, **kwargs): - domains = Domain.objects.values("id", "name", "url", "logo").filter(organization__id=id).order_by("modified") + domains = ( + Domain.objects.values("id", "name", "url", "logo") + .filter(organization__id=id) + .order_by("modified") + ) organizations = ( Organization.objects.values("name", "id") @@ -602,7 +630,9 @@ def post(self, request, id, *args, **kwargs): managers_list = request.POST.getlist("user") organization_obj = Organization.objects.get(id=id) - domain_exist = Domain.objects.filter(Q(name=domain_data["name"]) | Q(url=domain_data["url"])).exists() + domain_exist = Domain.objects.filter( + Q(name=domain_data["name"]) | Q(url=domain_data["url"]) + ).exists() if domain_exist: messages.error(request, "Domain name or url already exist.") @@ -633,7 +663,9 @@ def post(self, request, id, *args, **kwargs): for domain_manager_email in managers_list: manager_email_domain = domain_manager_email.split("@")[-1] if not domain.endswith(f".{manager_email_domain}") and domain != manager_email_domain: - messages.error(request, f"Manager: {domain_manager_email} does not match domain email.") + messages.error( + request, f"Manager: {domain_manager_email} does not match domain email." + ) return redirect("add_domain", id=id) if request.FILES.get("logo"): @@ -660,7 +692,10 @@ def post(self, request, id, *args, **kwargs): messages.error(request, "Facebook url should contain facebook.com") return redirect("add_domain", id=id) if domain_data["twitter"]: - if "twitter.com" not in domain_data["twitter"] and "x.com" not in domain_data["twitter"]: + if ( + "twitter.com" not in domain_data["twitter"] + and "x.com" not in domain_data["twitter"] + ): messages.error(request, "Twitter url should contain twitter.com or x.com") return redirect("add_domain", id=id) if domain_data["github"] and "github.com" not in domain_data["github"]: @@ -744,8 +779,13 @@ def put(self, request, id, *args, **kwargs): for domain_manager_email in managers_list: manager_email_domain = domain_manager_email.split("@")[-1] - if not domain_name.endswith(f".{manager_email_domain}") and domain_name != manager_email_domain: - messages.error(request, f"Manager: {domain_manager_email} does not match domain email.") + if ( + not domain_name.endswith(f".{manager_email_domain}") + and domain_name != manager_email_domain + ): + messages.error( + request, f"Manager: {domain_manager_email} does not match domain email." + ) return redirect("edit_domain", id=id, domain_id=domain_id) if request.FILES.get("logo"): @@ -768,7 +808,10 @@ def put(self, request, id, *args, **kwargs): messages.error(request, "Facebook url should contain facebook.com") return redirect("edit_domain", id=id, domain_id=domain_id) if domain_data["twitter"]: - if "twitter.com" not in domain_data["twitter"] and "x.com" not in domain_data["twitter"]: + if ( + "twitter.com" not in domain_data["twitter"] + and "x.com" not in domain_data["twitter"] + ): messages.error(request, "Twitter url should contain twitter.com or x.com") return redirect("edit_domain", id=id, domain_id=domain_id) if domain_data["github"] and "github.com" not in domain_data["github"]: @@ -893,7 +936,9 @@ def post(self, request, id, *args, **kwargs): if slack_integration: app = App(token=slack_integration.bot_access_token) if slack_data["default_channel"]: - slack_integration.default_channel_id = self.get_channel_id(app, slack_data["default_channel"]) + slack_integration.default_channel_id = self.get_channel_id( + app, slack_data["default_channel"] + ) slack_integration.default_channel_name = slack_data["default_channel"] slack_integration.daily_updates = bool(slack_data["daily_sizzle_timelogs_status"]) slack_integration.daily_update_time = slack_data["daily_sizzle_timelogs_hour"] @@ -1043,16 +1088,18 @@ def get(self, request, pk, *args, **kwargs): if not domain: raise Http404("Domain not found") - total_money_distributed = Issue.objects.filter(domain__id=domain["id"]).aggregate(total_money=Sum("rewarded"))[ - "total_money" - ] + total_money_distributed = Issue.objects.filter(domain__id=domain["id"]).aggregate( + total_money=Sum("rewarded") + )["total_money"] total_money_distributed = 0 if total_money_distributed is None else total_money_distributed # Query the database for the exact domain total_bug_reported = Issue.objects.filter(domain__id=domain["id"]).count() total_bug_accepted = Issue.objects.filter(domain__id=domain["id"], verified=True).count() - is_domain_manager = Domain.objects.filter(Q(id=domain["id"]) & Q(managers__in=[request.user])).exists() + is_domain_manager = Domain.objects.filter( + Q(id=domain["id"]) & Q(managers__in=[request.user]) + ).exists() if is_domain_manager: latest_issues = ( Issue.objects.values( @@ -1118,16 +1165,18 @@ def get(self, request, pk, *args, **kwargs): first_bug = Issue.objects.filter(domain__id=domain["id"]).order_by("created").first() last_bug = Issue.objects.filter(domain__id=domain["id"]).order_by("-created").first() - ongoing_bughunts = Hunt.objects.filter(domain__id=domain["id"]).annotate(total_prize=Sum("huntprize__value"))[ - :3 - ] + ongoing_bughunts = Hunt.objects.filter(domain__id=domain["id"]).annotate( + total_prize=Sum("huntprize__value") + )[:3] context = { **domain, "total_money_distributed": total_money_distributed, "total_bug_reported": total_bug_reported, "total_bug_accepted": total_bug_accepted, "latest_issues": cleaned_issues, - "monthly_activity_chart": json.dumps(self.get_current_year_monthly_reported_bar_data(domain["id"])), + "monthly_activity_chart": json.dumps( + self.get_current_year_monthly_reported_bar_data(domain["id"]) + ), "top_testers": top_testers, "first_bug": first_bug, "last_bug": last_bug, @@ -1319,7 +1368,9 @@ def get(self, request, pk, *args, **kwargs): # bughunt prizes rewards = HuntPrize.objects.filter(hunt_id=hunt_obj.id) - winners_count = {reward.id: Winner.objects.filter(prize_id=reward.id).count() for reward in rewards} + winners_count = { + reward.id: Winner.objects.filter(prize_id=reward.id).count() for reward in rewards + } # check winner have for this bughunt winners = Winner.objects.filter(hunt_id=hunt_obj.id).select_related("prize") @@ -1571,8 +1622,12 @@ def edit_prize(request, prize_id, organization_id): data = json.loads(request.body) prize.name = data.get("prize_name", prize.name) prize.value = data.get("cash_value", prize.value) - prize.no_of_eligible_projects = data.get("number_of_winning_projects", prize.no_of_eligible_projects) - prize.valid_submissions_eligible = data.get("every_valid_submissions", prize.valid_submissions_eligible) + prize.no_of_eligible_projects = data.get( + "number_of_winning_projects", prize.no_of_eligible_projects + ) + prize.valid_submissions_eligible = data.get( + "every_valid_submissions", prize.valid_submissions_eligible + ) prize.description = data.get("prize_description", prize.description) prize.save() @@ -1587,7 +1642,9 @@ def accept_bug(request, issue_id, reward_id=None): issue.verified = True issue.rewarded = 0 issue.save() - Winner(hunt_id=issue.hunt.id, prize_id=None, winner_id=issue.user.id, prize_amount=0).save() + Winner( + hunt_id=issue.hunt.id, prize_id=None, winner_id=issue.user.id, prize_amount=0 + ).save() else: reward = get_object_or_404(HuntPrize, id=reward_id) issue.verified = True @@ -1626,4 +1683,4 @@ def delete_manager(request, manager_id, domain_id): except Domain.DoesNotExist: return JsonResponse({"success": False, "message": "Domain not found."}) except User.DoesNotExist: - return JsonResponse({"success": False, "message": "User not found."}) + return JsonResponse({"success": False, "message": "User not found."}) \ No newline at end of file diff --git a/website/views/core.py b/website/views/core.py index b35558586..57f5b3465 100644 --- a/website/views/core.py +++ b/website/views/core.py @@ -48,7 +48,12 @@ UserProfile, Wallet, ) -from website.utils import analyze_pr_content, fetch_github_data, safe_redirect_allowed, save_analysis_report +from website.utils import ( + analyze_pr_content, + fetch_github_data, + safe_redirect_allowed, + save_analysis_report, +) # from website.bot import conversation_chain, is_api_key_valid, load_vector_store @@ -244,7 +249,10 @@ def check_status(request): # Database connection check if CHECK_DATABASE: print("Getting database connection count...") - if settings.DATABASES.get("default", {}).get("ENGINE") == "django.db.backends.postgresql": + if ( + settings.DATABASES.get("default", {}).get("ENGINE") + == "django.db.backends.postgresql" + ): with connection.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM pg_stat_activity WHERE state = 'active'") status_data["db_connection_count"] = cursor.fetchone()[0] @@ -354,13 +362,17 @@ def search(request, template="search.html"): context = { "query": query, "type": stype, - "projects": Project.objects.filter(Q(name__icontains=query) | Q(description__icontains=query)), + "projects": Project.objects.filter( + Q(name__icontains=query) | Q(description__icontains=query) + ), } elif stype == "repos": context = { "query": query, "type": stype, - "repos": Repo.objects.filter(Q(name__icontains=query) | Q(description__icontains=query)), + "repos": Repo.objects.filter( + Q(name__icontains=query) | Q(description__icontains=query) + ), } elif stype == "tags": tags = Tag.objects.filter(name__icontains=query) @@ -515,11 +527,15 @@ def vote_suggestions(request): voted = SuggestionVotes.objects.filter(user=user, suggestion=suggestion).delete() if up_vote: - voted = SuggestionVotes.objects.create(user=user, suggestion=suggestion, up_vote=True, down_vote=False) + voted = SuggestionVotes.objects.create( + user=user, suggestion=suggestion, up_vote=True, down_vote=False + ) suggestion.up_votes += 1 if down_vote: - voted = SuggestionVotes.objects.create(user=user, suggestion=suggestion, down_vote=True, up_vote=False) + voted = SuggestionVotes.objects.create( + user=user, suggestion=suggestion, down_vote=True, up_vote=False + ) suggestion.down_votes += 1 suggestion.save() @@ -545,8 +561,12 @@ def set_vote_status(request): except Suggestion.DoesNotExist: return JsonResponse({"success": False, "error": "Suggestion not found"}, status=404) - up_vote = SuggestionVotes.objects.filter(suggestion=suggestion, user=user, up_vote=True).exists() - down_vote = SuggestionVotes.objects.filter(suggestion=suggestion, user=user, down_vote=True).exists() + up_vote = SuggestionVotes.objects.filter( + suggestion=suggestion, user=user, up_vote=True + ).exists() + down_vote = SuggestionVotes.objects.filter( + suggestion=suggestion, user=user, down_vote=True + ).exists() response = {"up_vote": up_vote, "down_vote": down_vote} return JsonResponse(response) @@ -635,7 +655,9 @@ def dispatch(self, request, *args, **kwargs): def post(self, request, *args, **kwargs): data = request.FILES.get("image") - result = default_storage.save("uploads/" + self.kwargs["hash"] + ".png", ContentFile(data.read())) + result = default_storage.save( + "uploads/" + self.kwargs["hash"] + ".png", ContentFile(data.read()) + ) return JsonResponse({"status": result}) @@ -831,7 +853,12 @@ def submit_roadmap_pr(request): if "error" in pr_data or "error" in roadmap_data: return JsonResponse( - {"error": (f"Failed to fetch PR or roadmap data: " f"{pr_data.get('error', 'Unknown error')}")}, + { + "error": ( + f"Failed to fetch PR or roadmap data: " + f"{pr_data.get('error', 'Unknown error')}" + ) + }, status=500, ) @@ -857,4 +884,4 @@ def handler404(request, exception): def handler500(request, exception=None): - return render(request, "500.html", {}, status=500) + return render(request, "500.html", {}, status=500) \ No newline at end of file diff --git a/website/views/issue.py b/website/views/issue.py index c3c80e4f0..a8297db0f 100644 --- a/website/views/issue.py +++ b/website/views/issue.py @@ -1501,7 +1501,6 @@ def comment_on_content(request, content_pk): content_type = request.POST.get("content_type") content_type_obj = ContentType.objects.get(model=content_type) content = content_type_obj.get_object_for_this_type(pk=content_pk) - VALID_CONTENT_TYPES = ["issue", "post"] if request.method == "POST" and isinstance(request.user, User): @@ -1523,7 +1522,7 @@ def comment_on_content(request, content_pk): if parent_comment is None: messages.error(request, "Parent comment doesn't exist.") - return redirect(f"/{content_type}/{content_pk}") + return redirect("home") Comment.objects.create( parent=parent_comment, @@ -1652,4 +1651,4 @@ def flag_issue(request, issue_pk): def select_bid(request): - return render(request, "bid_selection.html") + return render(request, "bid_selection.html") \ No newline at end of file diff --git a/website/views/slackbot.py b/website/views/slackbot.py index ea52dc124..7f92b91f8 100644 --- a/website/views/slackbot.py +++ b/website/views/slackbot.py @@ -91,7 +91,11 @@ def handle_discover_command(ack, client, command): lang = (repo["language"] or "").lower() topics = [t.lower() for t in repo.get("topics", [])] - if search_term.lower() in name_desc or search_term.lower() in lang or search_term.lower() in topics: + if ( + search_term.lower() in name_desc + or search_term.lower() in lang + or search_term.lower() in topics + ): desc = repo["description"] or "No description provided." found_urls = url_pattern.findall(desc) @@ -141,19 +145,28 @@ def handle_discover_command(ack, client, command): if gh_response.status_code == 200: repos = gh_response.json() if not repos: - send_dm(client, command["user_id"], "No repositories found for OWASP-BLT.") + send_dm( + client, command["user_id"], "No repositories found for OWASP-BLT." + ) else: repo_list = [] for idx, repo in enumerate(repos, start=1): - desc = repo["description"] if repo["description"] else "No description provided." - repo_list.append(f"{idx}. <{repo['html_url']}|{repo['name']}> - {desc}") + desc = ( + repo["description"] + if repo["description"] + else "No description provided." + ) + repo_list.append( + f"{idx}. <{repo['html_url']}|{repo['name']}> - {desc}" + ) blocks = [ { "type": "section", "text": { "type": "mrkdwn", - "text": "Here are the OWASP BLT project repositories:\n" + "\n".join(repo_list), + "text": "Here are the OWASP BLT project repositories:\n" + + "\n".join(repo_list), }, }, { @@ -223,7 +236,8 @@ def handle_repository_selection(ack, body, client): send_dm(client, user_id, "No issues found for this repository.") else: issues_list = [ - f"- <{issue['html_url']}|{issue['title']}> (#{issue['number']})" for issue in issues[:5] + f"- <{issue['html_url']}|{issue['title']}> (#{issue['number']})" + for issue in issues[:5] ] issues_text = "Here are the latest issues:\n" + "\n".join(issues_list) send_dm(client, user_id, issues_text) @@ -391,4 +405,4 @@ def slack_commands(request): if request.content_type != "application/x-www-form-urlencoded": return JsonResponse({"error": "Invalid content type"}, status=415) return HttpResponse(handler.handle(request)) - return JsonResponse({"error": "Method not allowed"}, status=405) + return JsonResponse({"error": "Method not allowed"}, status=405) \ No newline at end of file