Skip to content

Conversation

@Shriyansh21-ai
Copy link

@Shriyansh21-ai Shriyansh21-ai commented Nov 25, 2025

This pull request includes several frontend updates to improve layout consistency and component behavior.
No major functionality was changed—these are mostly structural and minor UI adjustments.

Changes Made

Refactored frontend layout for better organization

Updated component structure and improved readability

Minor styling fixes and alignment improvements

Cleaned up unnecessary code artifacts

✅ Note

Small frontend errors or warnings are not critical and do not affect core functionality. They can be refined in later passes.

Summary by CodeRabbit

  • Bug Fixes

    • Removed camera toggle functionality from team debate rooms, which may cause camera controls to become unavailable.
  • Refactor

    • Updated WebSocket handlers for debate spectator functionality.
    • Reorganized dependency declarations for improved package management.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Nov 25, 2025

Walkthrough

The changes introduce a new WebSocket handler for team-based debate connections in the backend, update the server to route debates through this handler, promote Casbin dependencies to direct declarations in go.mod, and remove the toggleCamera function from the frontend's TeamDebateRoom component.

Changes

Cohort / File(s) Summary
Backend WebSocket Handler
backend/websocket/team_debate_handler.go
Adds new TeamDebateWebsocketHandler function that extracts debate, team, and user identifiers from Gin context, upgrades the connection, constructs a TeamDebateClient, registers it with the hub, and initiates read/write pumps.
Backend Server Configuration & Dependencies
backend/cmd/server/main.go, backend/go.mod
Updates Debates spectator route to use new websocket.TeamDebateWebsocketHandler. Promotes github.com/casbin/casbin/v2 and github.com/casbin/mongodb-adapter/v3 from indirect to direct dependencies.
Frontend WebSocket Handler
frontend/src/Pages/TeamDebateRoom.tsx
Removes toggleCamera function that previously toggled the local video track's enabled state and updated camera UI state.

Sequence Diagram

sequenceDiagram
    participant Client as Client Request
    participant Handler as TeamDebateWebsocketHandler
    participant Gin as Gin Context
    participant Upgrader as WebSocket Upgrader
    participant Hub as Debate Hub
    participant Client_obj as TeamDebateClient

    Client->>Handler: Request with debateID, teamId, userId, isTeam1
    Handler->>Gin: Extract parameters from context
    Gin-->>Handler: Parsed IDs & boolean
    Handler->>Upgrader: Upgrade HTTP to WebSocket
    Upgrader-->>Handler: WebSocket connection
    Handler->>Client_obj: Construct TeamDebateClient
    Handler->>Hub: Register client
    Hub-->>Handler: Client registered
    Handler->>Client_obj: Start read pump
    Handler->>Client_obj: Start write pump
    Client_obj-->>Client: WebSocket established
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

  • Focus areas for review:
    • Verify that toggleCamera removal in frontend/src/Pages/TeamDebateRoom.tsx is not still being invoked by any UI event handlers; its removal could cause runtime errors if references remain.
    • Confirm that the new TeamDebateWebsocketHandler correctly extracts and validates all query parameters (debateID, teamId, userId, isTeam1) and handles conversion to MongoDB ObjectIDs safely.
    • Ensure Casbin dependencies are correctly promoted from indirect to direct and no other modules depend on them being indirect.

Poem

🐰 A new debate handler hops into place,
Team voices echo through WebSocket space,
Dependencies tidied, toggling removed,
The backend's refined, the frontend improved!
Hop hop, review done! 🎯

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title references removing a duplicate toggleCamera function and cleaning up TeamDebateRoom, which aligns with the frontend changes where toggleCamera was removed.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

📝 Customizable high-level summaries are now available in beta!

You can now customize how CodeRabbit generates the high-level summary in your pull requests — including its content, structure, tone, and formatting.

  • Provide your own instructions using the high_level_summary_instructions setting.
  • Format the summary however you like (bullet lists, tables, multi-section layouts, contributor stats, etc.).
  • Use high_level_summary_in_walkthrough to move the summary from the description to the walkthrough section.

Example instruction:

"Divide the high-level summary into five sections:

  1. 📝 Description — Summarize the main change in 50–60 words, explaining what was done.
  2. 📓 References — List relevant issues, discussions, documentation, or related PRs.
  3. 📦 Dependencies & Requirements — Mention any new/updated dependencies, environment variable changes, or configuration updates.
  4. 📊 Contributor Summary — Include a Markdown table showing contributions:
    | Contributor | Lines Added | Lines Removed | Files Changed |
  5. ✔️ Additional Notes — Add any extra reviewer context.
    Keep each section concise (under 200 words) and use bullet or numbered lists for clarity."

Note: This feature is currently in beta for Pro-tier users, and pricing will be announced later.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@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: 2

🧹 Nitpick comments (1)
backend/websocket/team_debate_handler.go (1)

257-260: Add logging for WebSocket upgrade failures.

The handler silently returns when the WebSocket upgrade fails, making debugging connection issues difficult.

Apply this diff to add error logging:

     conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
     if err != nil {
+        log.Printf("Failed to upgrade WebSocket connection for debate %s: %v", debateIDHex, err)
         return
     }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d4dcff6 and cdcc399.

⛔ Files ignored due to path filters (2)
  • backend/go.sum is excluded by !**/*.sum
  • frontend/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (4)
  • backend/cmd/server/main.go (2 hunks)
  • backend/go.mod (1 hunks)
  • backend/websocket/team_debate_handler.go (2 hunks)
  • frontend/src/Pages/TeamDebateRoom.tsx (0 hunks)
💤 Files with no reviewable changes (1)
  • frontend/src/Pages/TeamDebateRoom.tsx
🧰 Additional context used
🧬 Code graph analysis (1)
backend/cmd/server/main.go (1)
backend/websocket/team_debate_handler.go (1)
  • TeamDebateWebsocketHandler (247-275)
🔇 Additional comments (2)
backend/go.mod (1)

8-9: I'll search for the latest versions of these Casbin dependencies to verify they are current.

Based on my verification:

Security advisories status verified: No known vulnerabilities found.

The latest version of casbin/casbin/v2 was published November 14, 2025, and both v2.132.0 and v3.7.0 of the mongodb-adapter are valid Go module versions with no known CVEs. Both v3 and v4 versions of the mongodb-adapter remain documented and supported, so using v3.7.0 is acceptable.

The dependencies are current and free from known vulnerabilities.

backend/cmd/server/main.go (1)

150-151: The review comment is based on incorrect analysis of the handler implementation.

The TeamDebateWebsocketHandler extracts userId and teamId as query parameters, but these parameters are optional. When missing, c.Query() returns an empty string, which primitive.ObjectIDFromHex() silently converts to a zero ObjectID without validation. The client is then registered with zero IDs regardless. There is no requirement check for these fields.

The code therefore already supports anonymous spectators exactly as the comment states. Spectators can connect without providing userId or teamId query parameters, and the handler will accept the connection with zero-value ObjectIDs.

While there is a minor code quality concern (the anonymous access model could be more explicit rather than implicit via empty/zero IDs), the endpoint's functionality aligns with its documented behavior.

Likely an incorrect or invalid review comment.

Comment on lines +247 to +275
func TeamDebateWebsocketHandler(c *gin.Context) {
debateIDHex := c.Param("debateID")
teamIDHex := c.Query("teamId")
userIDHex := c.Query("userId")
isTeam1 := c.Query("isTeam1") == "true"

debateID, _ := primitive.ObjectIDFromHex(debateIDHex)
teamID, _ := primitive.ObjectIDFromHex(teamIDHex)
userID, _ := primitive.ObjectIDFromHex(userIDHex)

conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
return
}

client := &TeamDebateClient{
conn: conn,
send: make(chan []byte, 256),
debateID: debateID,
teamID: teamID,
userID: userID,
isTeam1: isTeam1,
}

teamDebateHub.register <- client

go client.writePump()
go client.readPump()
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Add authentication and authorization checks.

The handler doesn't verify that the requesting user has permission to join the debate or that they belong to the specified team. This could allow:

  • Unauthorized users to join debates
  • Users to impersonate other users by providing different userId parameters
  • Users to access debates they shouldn't be able to see

Consider implementing one of these approaches:

  1. Add JWT authentication: Extract and validate the user's JWT token, then verify the token's user ID matches the userId parameter.

  2. Verify team membership: Query the database to confirm the user belongs to the specified team and that team is participating in the debate.

  3. Apply AuthMiddleware: If the route should be protected, register it within an authenticated route group in main.go.

Example authorization check:

func TeamDebateWebsocketHandler(c *gin.Context) {
    // ... existing parameter extraction and validation ...
    
    // Verify user belongs to the team
    teamCollection := db.GetCollection("teams")
    var team models.Team
    err := teamCollection.FindOne(nil, bson.M{
        "_id": teamID,
        "members": bson.M{"$elemMatch": bson.M{"user_id": userID}},
    }).Decode(&team)
    if err != nil {
        c.JSON(403, gin.H{"error": "User is not a member of the specified team"})
        return
    }
    
    // Verify team is part of the debate
    debateCollection := db.GetCollection("team_debates")
    var debate models.TeamDebate
    err = debateCollection.FindOne(nil, bson.M{
        "_id": debateID,
        "$or": []bson.M{
            {"team1_id": teamID},
            {"team2_id": teamID},
        },
    }).Decode(&debate)
    if err != nil {
        c.JSON(403, gin.H{"error": "Team is not participating in this debate"})
        return
    }
    
    // ... rest of handler ...
}
🤖 Prompt for AI Agents
In backend/websocket/team_debate_handler.go around lines 247-275, the handler
upgrades to a websocket without authenticating or authorizing the requester; fix
by (1) validating and parsing the authenticated user (e.g., extract/verify JWT
or require the route to be behind AuthMiddleware) and ensure the token's user ID
matches the userId query parameter, (2) check the parsed ObjectIDs for errors
and return 400 on invalid IDs before attempting an upgrade, (3) query the DB to
verify the user is a member of the specified team, and (4) confirm that the team
is a participant in the given debate; if any check fails, return an appropriate
4xx response and do not call upgrader.Upgrade or register the client.

Comment on lines +248 to +255
debateIDHex := c.Param("debateID")
teamIDHex := c.Query("teamId")
userIDHex := c.Query("userId")
isTeam1 := c.Query("isTeam1") == "true"

debateID, _ := primitive.ObjectIDFromHex(debateIDHex)
teamID, _ := primitive.ObjectIDFromHex(teamIDHex)
userID, _ := primitive.ObjectIDFromHex(userIDHex)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Add input validation and error handling for required parameters.

The handler extracts query parameters and converts them to ObjectIDs without validation or error handling. This creates several risks:

  1. Missing required parameters (teamId, userId) will result in empty strings being parsed, creating zero-value ObjectIDs
  2. Invalid ObjectID hex strings will silently fail conversion, also resulting in zero-value ObjectIDs
  3. Zero-value ObjectIDs could cause incorrect database lookups or matches with unintended documents

Apply this diff to add proper validation and error handling:

 func TeamDebateWebsocketHandler(c *gin.Context) {
     debateIDHex := c.Param("debateID")
     teamIDHex := c.Query("teamId")
     userIDHex := c.Query("userId")
     isTeam1 := c.Query("isTeam1") == "true"
+
+    // Validate required parameters
+    if debateIDHex == "" || teamIDHex == "" || userIDHex == "" {
+        c.JSON(400, gin.H{"error": "Missing required parameters: debateID, teamId, and userId"})
+        return
+    }
 
-    debateID, _ := primitive.ObjectIDFromHex(debateIDHex)
-    teamID, _ := primitive.ObjectIDFromHex(teamIDHex)
-    userID, _ := primitive.ObjectIDFromHex(userIDHex)
+    debateID, err := primitive.ObjectIDFromHex(debateIDHex)
+    if err != nil {
+        c.JSON(400, gin.H{"error": "Invalid debateID format"})
+        return
+    }
+    
+    teamID, err := primitive.ObjectIDFromHex(teamIDHex)
+    if err != nil {
+        c.JSON(400, gin.H{"error": "Invalid teamId format"})
+        return
+    }
+    
+    userID, err := primitive.ObjectIDFromHex(userIDHex)
+    if err != nil {
+        c.JSON(400, gin.H{"error": "Invalid userId format"})
+        return
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
debateIDHex := c.Param("debateID")
teamIDHex := c.Query("teamId")
userIDHex := c.Query("userId")
isTeam1 := c.Query("isTeam1") == "true"
debateID, _ := primitive.ObjectIDFromHex(debateIDHex)
teamID, _ := primitive.ObjectIDFromHex(teamIDHex)
userID, _ := primitive.ObjectIDFromHex(userIDHex)
debateIDHex := c.Param("debateID")
teamIDHex := c.Query("teamId")
userIDHex := c.Query("userId")
isTeam1 := c.Query("isTeam1") == "true"
// Validate required parameters
if debateIDHex == "" || teamIDHex == "" || userIDHex == "" {
c.JSON(400, gin.H{"error": "Missing required parameters: debateID, teamId, and userId"})
return
}
debateID, err := primitive.ObjectIDFromHex(debateIDHex)
if err != nil {
c.JSON(400, gin.H{"error": "Invalid debateID format"})
return
}
teamID, err := primitive.ObjectIDFromHex(teamIDHex)
if err != nil {
c.JSON(400, gin.H{"error": "Invalid teamId format"})
return
}
userID, err := primitive.ObjectIDFromHex(userIDHex)
if err != nil {
c.JSON(400, gin.H{"error": "Invalid userId format"})
return
}
🤖 Prompt for AI Agents
In backend/websocket/team_debate_handler.go around lines 248 to 255, the handler
currently converts params to ObjectIDs without validation causing zero-value IDs
on missing/invalid input; update the code to: verify debateID, teamId and userId
are present (non-empty), call primitive.ObjectIDFromHex for each and check the
returned error, and if any conversion fails return a 400 response (with a clear
message indicating which param is missing/invalid) instead of proceeding; do not
use the zero-value ObjectIDs for DB lookups and keep isTeam1 parsed from the
query with a safe default.

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.

1 participant