Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@igennova
Copy link
Contributor

@igennova igennova commented Mar 26, 2025

FIxes : #4061

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a profanity check for user submissions to automatically screen and block inappropriate language in bug reports.
  • Chores

    • Updated project dependencies by adding better-profanity to enhance functionality and applied minor formatting improvements to maintain standard configuration practices.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 26, 2025

Walkthrough

The changes introduce a new dependency (better-profanity version ^0.6.1) to the project’s configuration in the pyproject.toml file, along with a minor formatting update. Additionally, the IssueCreate view in the bug reporting module now checks for profanity by aggregating text fields and using the profanity checking API. If profanity is detected, a block record is created, and the submission is prevented, thereby enforcing content moderation on bug reports.

Changes

File(s) Change Summary
pyproject.toml Added the better-profanity dependency with version ^0.6.1 to the [tool.poetry.dependencies] section; a newline was appended at the end of the file for proper formatting.
website/views/issue.py Updated the IssueCreate class in the form_valid method to combine description fields and check them for profanity using profanity.contains_profanity. Added new imports for profanity and the Blocked model. A Blocked record is created on detection.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant IssueCreate as IssueCreate View
    participant Profanity as Profanity Checker
    participant Blocked as Blocked Model

    User->>IssueCreate: Submit bug report with description
    IssueCreate->>IssueCreate: Combine text fields for checking
    IssueCreate->>Profanity: Check for profanity in combined text
    alt Profanity Detected
        Profanity-->>IssueCreate: Returns true
        IssueCreate->>Blocked: Create new Blocked record (IP, agent, reason)
        IssueCreate-->>User: Redirect with error message
    else No Profanity
        Profanity-->>IssueCreate: Returns false
        IssueCreate-->>User: Process form submission normally
    end
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
website/views/issue.py (2)

910-928: Well-implemented profanity check for bug reports.

The implementation effectively:

  1. Extracts text from both description fields
  2. Combines them for a comprehensive check
  3. Creates an enforcement record when profanity is detected
  4. Prevents form submission with an appropriate error message

This is a good security measure to prevent inappropriate content in bug reports.

Consider adding a small refactor to sanitize or normalize the text before checking for profanity:

 # Combine fields to check
-text_to_check = f"{description} {markdown_description}"
+text_to_check = f"{description} {markdown_description}".strip()

This would handle edge cases where whitespace might affect the profanity check.


929-929: Incomplete code comment.

There appears to be an incomplete or unnecessary comment starting with "# Pr" that doesn't provide any useful information.

Consider removing this incomplete comment or completing it with meaningful information:

-# Pr
+# Proceed with normal form validation
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f658670 and 3db086f.

📒 Files selected for processing (2)
  • pyproject.toml (2 hunks)
  • website/views/issue.py (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Run Tests
🔇 Additional comments (3)
pyproject.toml (1)

70-70:

Details

✅ Verification successful

New dependency added for profanity checking.

Adding the better-profanity package will enable profanity filtering capabilities for bug reports as implemented in the IssueCreate.form_valid method.

Let's verify if this version is the latest:


🌐 Web query:

What is the latest version of better-profanity python package?

💡 Result:

The latest version of the better-profanity Python package is 0.7.0, released on November 2, 2020[1][6]. This version remains current as of March 2025 based on available documentation.

Key details:

  • Supports Unicode character handling and leetspeak detection[1][3]
  • Compatible with Python 3.4+ and PyPy3[1][6]
  • Features include customizable censoring characters, profanity presence checks, and wordlist modifications[1][3][9]

The package continues to be maintained on GitHub with open issues and contributions still being accepted[9].

Citations:


Verified Dependency Version: better-profanity 0.7.0 is Current

  • The dependency addition in pyproject.toml (line 70) with better-profanity = "^0.7.0" is correct since version 0.7.0 is confirmed as the latest release.
  • This package is now correctly set up to provide profanity filtering in the IssueCreate.form_valid method.
website/views/issue.py (2)

16-16: Successfully imported the profanity module.

Properly importing the profanity module from the better-profanity package for content moderation.


63-63: Successfully imported the Blocked model.

Correctly imported the Blocked model to track instances of profanity detection.

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 26, 2025
coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 26, 2025
@igennova
Copy link
Contributor Author

@CodeRabbit full review it

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 26, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Get the diff for the PR to understand the exact changes
git diff --staged

# Check the complete content of the modified files
echo "===== pyproject.toml ====="
cat pyproject.toml
echo ""
echo "===== website/views/issue.py ====="
cat website/views/issue.py
echo ""

# Look for the Blocked model to understand its structure
echo "===== Looking for Blocked model implementation ====="
rg -A 10 "class Blocked" --type py

# Check for existing profanity checking mechanisms
echo "===== Checking for existing profanity handling ====="
rg "profanity" --type py

Length of output: 68355


🏁 Script executed:

#!/bin/bash
# Look for the Blocked model implementation to understand its structure
echo "===== Looking for Blocked model implementation ====="
rg "class Blocked" --type py -A 10

# Check for existing profanity handling in the codebase
echo "===== Checking for existing profanity handling ====="
rg "profanity" --type py

# Check if there are any tests for profanity detection
echo "===== Checking for profanity tests ====="
fd test --type f | xargs rg "profanity|inappropriate|Blocked"

Length of output: 1829


@igennova I've completed a full review of your PR that adds profanity checking to bug reports. Here's my assessment:

Overall Assessment

This is a well-implemented feature that adds important content moderation capabilities to the bug reporting system.

Positive Aspects

  • Good use of the better-profanity library for detection
  • Appropriately combines content from both description fields for thorough checking
  • Properly utilizes the existing Blocked model to record moderation actions
  • Clear error message to inform users why their submission was blocked
  • Minimal and focused changes that integrate well with the existing code

Suggestions for Improvement

  1. Add Tests: Consider adding unit tests to verify the profanity detection works correctly with various inputs
  2. Enhanced User Experience: The current implementation blocks the submission entirely. You might consider:
    • Highlighting which parts contain inappropriate language
    • Allowing users to edit and resubmit rather than forcing them to start over
  3. Configurability: You could make the feature more configurable by:
    • Adding settings to control sensitivity levels
    • Creating an allowlist for terms that might be false positives

Technical Implementation

The implementation correctly:

  • Extracts text from form fields
  • Combines them for comprehensive checking
  • Creates appropriate blocking records
  • Prevents form submission with clear feedback

Overall, this is a valuable addition to the project that will help maintain content quality. The changes look good to merge, with the test coverage being the main area that could be enhanced in the future.

@igennova
Copy link
Contributor Author

/giphy amazing

@github-actions
Copy link
Contributor

Giphy GIF

Copy link
Collaborator

@DonnieBLT DonnieBLT left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please change the version as suggested by the developers

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
website/views/issue.py (2)

926-928: Consider improving the error message for better user experience.

The current error message "Have a nice day." doesn't inform users about why their submission was rejected. A more informative message would improve user experience and reduce confusion.

-            messages.error(self.request, "Have a nice day.")
+            messages.error(self.request, "Your submission contains inappropriate language. Please revise your content and try again.")

910-928: Consider enhancing the profanity filter implementation for better usability.

The current implementation blocks submissions entirely when profanity is detected. Consider these enhancements to improve user experience:

  1. Highlight problematic terms instead of rejecting outright
  2. Add configuration options for sensitivity levels
  3. Create an allowlist for false positives
  4. Track repeat offenders with escalating responses

A more robust implementation could use a configuration file to control sensitivity and maintain allowlists:

# Example configuration-based approach
from django.conf import settings

# Get configuration from settings
PROFANITY_SETTINGS = getattr(settings, 'PROFANITY_SETTINGS', {
    'censored_words': [],     # Additional words to censor
    'allowed_words': [],      # Words to exclude from censoring
    'action_level': 'block',  # Options: 'warn', 'highlight', 'block'
    'max_warnings': 3,        # Number of warnings before blocking
})

# Configure profanity filter
profanity.load_censor_words(whitelist=PROFANITY_SETTINGS['allowed_words'])
for word in PROFANITY_SETTINGS['censored_words']:
    profanity.add_censor_word(word)

# Later in the code
if profanity.contains_profanity(text_to_check):
    if PROFANITY_SETTINGS['action_level'] == 'block':
        # Current implementation
    elif PROFANITY_SETTINGS['action_level'] == 'highlight':
        # Return with highlighted text
        censored_text = profanity.censor(text_to_check)
        # Show user the censored text and allow editing
    elif PROFANITY_SETTINGS['action_level'] == 'warn':
        # Track warnings for this user
        # Block if exceeded max_warnings
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3db086f and 47b650b.

⛔ Files ignored due to path filters (1)
  • poetry.lock is excluded by !**/*.lock
📒 Files selected for processing (1)
  • website/views/issue.py (3 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
website/views/issue.py (1)
website/models.py (1)
  • Blocked (1200-1210)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Run Tests
🔇 Additional comments (4)
website/views/issue.py (4)

16-16: Good addition of the profanity filter dependency.

The better-profanity package is a solid choice for implementing content moderation, providing good performance and flexibility for profanity detection.


63-63: Properly imported the Blocked model.

The Blocked model imported here is correctly used later in the code to log moderation actions, ensuring consistent use of the existing infrastructure.


910-915: Well-designed text collection for profanity checking.

Combining both the description and markdown_description fields ensures thorough profanity checking across all user-provided content in the bug report.


917-924: Good implementation of the profanity check and blocking.

The implementation correctly uses the profanity check API and creates a block record with appropriate details when profanity is detected. It records the reporter's IP, reason for block, and user agent string, which is helpful for monitoring abuse patterns.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
website/views/issue.py (1)

910-928: 🛠️ Refactor suggestion

Add unit tests for the profanity checking functionality.

This important content moderation feature lacks test coverage. Consider adding tests to verify profanity detection works as expected with various inputs including edge cases.

Here's a suggested structure for tests:

# In tests.py or a dedicated test file
from django.test import TestCase, RequestFactory
from django.contrib.messages.storage.fallback import FallbackStorage
from django.contrib.auth.models import User
from website.models import Blocked
from website.views.issue import IssueCreate
from unittest.mock import patch

class ProfanityCheckTest(TestCase):
    def setUp(self):
        self.factory = RequestFactory()
        self.user = User.objects.create_user(username='testuser', email='[email protected]', password='testpass')
        
    def test_profanity_detection_blocks_submission(self):
        # Create a request with profanity in the description
        request = self.factory.post('/report/', {
            'description': 'This contains a bad word like sh*t',
            'markdown_description': 'More details',
            # Add other required form fields
        })
        request.user = self.user
        request.META['HTTP_USER_AGENT'] = 'Test User Agent'
        
        # Set up messages framework
        setattr(request, 'session', 'session')
        messages = FallbackStorage(request)
        setattr(request, '_messages', messages)
        
        # Create the view and call form_valid
        view = IssueCreate()
        view.request = request
        
        # Mock the form with cleaned_data
        form = mock.MagicMock()
        form.cleaned_data = {
            'description': 'This contains a bad word like sh*t',
            'markdown_description': 'More details',
        }
        
        # Call form_valid and check the result
        response = view.form_valid(form)
        
        # Verify that a Blocked entry was created
        self.assertEqual(Blocked.objects.count(), 1)
        blocked = Blocked.objects.first()
        self.assertEqual(blocked.reason_for_block, 'Inappropriate language in bug report')
        
        # Verify the user was redirected
        self.assertEqual(response.status_code, 302)
        self.assertEqual(response.url, '/')
🧹 Nitpick comments (3)
website/views/issue.py (3)

926-927: Consider providing a more informative error message.

The generic message "Have a nice day" doesn't inform users why their submission was blocked. A more descriptive message would help users understand the issue and modify their submission accordingly.

-            messages.error(self.request, "Have a nice day.")
+            messages.error(self.request, "Your submission contains inappropriate language. Please revise your content and try again.")

910-928: Consider enhancing user experience with warning instead of blocking.

Currently, the implementation blocks submissions completely when profanity is detected. Consider enhancing the user experience by highlighting the inappropriate content and allowing users to edit their submission instead of forcing them to start over.

Example implementation:

     # Check for profanity
     if profanity.contains_profanity(text_to_check):
+        # Log the attempt without blocking
         Blocked.objects.create(
             address=reporter_ip,
             reason_for_block="Inappropriate language in bug report",
             user_agent_string=self.request.META.get("HTTP_USER_AGENT", ""),
             count=1,
         )

-        # Prevent form submission
-        messages.error(self.request, "Have a nice day.")
-        return HttpResponseRedirect("/")
+        # Instead of blocking, warn and return to form
+        messages.warning(self.request, "Your submission contains inappropriate language. Please revise and submit again.")
+        return render(self.request, "report.html", {
+            "form": form,
+            "captcha_form": CaptchaForm(self.request.POST),
+            "has_profanity": True,
+            "submitted_data": form.cleaned_data
+        })

910-928: Consider adding configurability for profanity checking.

The current implementation uses default settings for profanity detection. Consider adding configuration options to:

  1. Control the sensitivity level
  2. Create an allowlist for false positives
  3. Allow admin toggling of the feature

This could be implemented using Django settings or a dedicated configuration model:

# In settings.py
PROFANITY_CHECK_ENABLED = True
PROFANITY_SENSITIVITY = 0.8  # 0-1 scale
PROFANITY_ALLOWLIST = ['spam', 'analysis']  # Words that might trigger false positives

# Then in the view
if settings.PROFANITY_CHECK_ENABLED:
    # Configure profanity filter
    profanity.load_censor_words()
    for word in settings.PROFANITY_ALLOWLIST:
        profanity.whitelist_words([word])
    
    # Then check as normal
    if profanity.contains_profanity(text_to_check):
        # Handle profanity...
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2b425d7 and f60e4a4.

📒 Files selected for processing (1)
  • website/views/issue.py (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Run Tests
  • GitHub Check: docker-test
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (4)
website/views/issue.py (4)

16-16: Appropriate library imported for profanity detection.

The better-profanity library is properly imported and will be used for checking inappropriate language in bug reports.


63-63: Required model imported for blocking functionality.

The Blocked model is correctly added to the imports list, which will be used to record instances of blocked submissions due to profanity.


910-915: Effective extraction and combination of text fields for profanity checking.

The implementation properly retrieves both the description and markdown_description fields and combines them into a single string for comprehensive profanity checking. This ensures all user-submitted content is properly moderated.


917-924: Good implementation of profanity detection and blocking.

The code correctly uses the profanity detection library and creates a proper blocking record with meaningful information (reporter IP, reason, user agent, count).

@igennova
Copy link
Contributor Author

@CodeRabbit Now check and tell me is it correct?

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 27, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Get the actual changes in this PR
echo "===== PR CHANGES ====="
git diff HEAD~1 HEAD

# Look at the full implementation of the modified files
echo "===== FULL IMPLEMENTATION OF MODIFIED FILES ====="
echo "pyproject.toml:"
cat pyproject.toml

echo "\nwebsite/views/issue.py:"
cat website/views/issue.py

# Check how the Blocked model is used elsewhere
echo "===== BLOCKED MODEL USAGE ====="
rg "Blocked" --type py | grep -v "class Blocked"

# Check if there are any existing tests for similar functionality
echo "===== RELATED TESTS ====="
fd "test" --type f | xargs rg "form_valid|Blocked"

Length of output: 68610


@igennova Yes, your implementation of profanity checking for bug reports is correct and well-integrated into the existing codebase. The code:
  1. Properly extracts text from both description fields
  2. Combines them for comprehensive checking
  3. Correctly uses the better-profanity library's detection method
  4. Creates appropriate records in the Blocked model
  5. Prevents form submission when profanity is detected

The implementation is straightforward yet effective. It follows the application's existing patterns and integrates naturally with the form validation flow.

If you wanted to enhance this feature in the future, you could consider:

  • Providing more specific feedback to users
  • Adding configurable sensitivity settings
  • Creating an allowlist for false positives
  • Adding unit tests

But for the current PR, your implementation is correct and ready to merge.

@igennova igennova requested a review from DonnieBLT March 27, 2025 06:11
@DonnieBLT DonnieBLT enabled auto-merge (squash) March 27, 2025 06:12
@DonnieBLT
Copy link
Collaborator

/giphy thumbs up please resolve conversations

@github-actions
Copy link
Contributor

Giphy GIF

@DonnieBLT DonnieBLT merged commit a3c4c89 into OWASP-BLT:main Mar 27, 2025
15 checks passed
mahii-17 pushed a commit to mahii-17/BLT that referenced this pull request Mar 27, 2025
* done

* done

* Update website/views/issue.py

* Update website/views/issue.py

* done

* done

---------

Co-authored-by: DonnieBLT <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

No Profanity Check for Bug Reporting

2 participants