diff --git a/backend/controllers/transcript_controller.go b/backend/controllers/transcript_controller.go index dc6650db..3e6b6ab4 100644 --- a/backend/controllers/transcript_controller.go +++ b/backend/controllers/transcript_controller.go @@ -20,13 +20,9 @@ import ( // SubmitTranscriptsRequest represents the request to submit debate transcripts type SubmitTranscriptsRequest struct { - RoomID string `json:"roomId" binding:"required"` - Role string `json:"role" binding:"required"` - Transcripts map[string]string `json:"transcripts" binding:"required"` - OpponentRole string `json:"opponentRole"` - OpponentID string `json:"opponentId"` - OpponentEmail string `json:"opponentEmail"` - OpponentTranscripts map[string]string `json:"opponentTranscripts"` + RoomID string `json:"roomId" binding:"required"` + Role string `json:"role" binding:"required"` + Transcripts map[string]string `json:"transcripts" binding:"required"` } // SaveTranscriptRequest represents the request to save a debate transcript @@ -65,10 +61,6 @@ func SubmitTranscripts(c *gin.Context) { req.Role, email, req.Transcripts, - req.OpponentRole, - req.OpponentID, - req.OpponentEmail, - req.OpponentTranscripts, ) if err != nil { diff --git a/backend/services/transcriptservice.go b/backend/services/transcriptservice.go index bd65d42d..d8f267c9 100644 --- a/backend/services/transcriptservice.go +++ b/backend/services/transcriptservice.go @@ -55,10 +55,6 @@ func SubmitTranscripts( role string, email string, transcripts map[string]string, - opponentRole string, - opponentID string, - opponentEmail string, - opponentTranscripts map[string]string, ) (map[string]interface{}, error) { roomID = strings.ToLower(strings.TrimSpace(roomID)) if roomID == "" { @@ -142,26 +138,47 @@ func SubmitTranscripts( }, nil } } else { - if len(transcripts) > 0 { - if err := upsertTranscript(ctx, transcriptCollection, roomID, role, email, transcripts); err != nil { - return nil, err - } + if role != "for" && role != "against" { + return nil, fmt.Errorf("invalid debate role %q", role) } - if opponentRole != "" && len(opponentTranscripts) > 0 { - resolvedEmail := opponentEmail - if resolvedEmail == "" && opponentID != "" { - if lookup, lookupErr := getUserEmailByID(ctx, opponentID); lookupErr == nil { - resolvedEmail = lookup - } - } - if resolvedEmail == "" && opponentID != "" { - resolvedEmail = opponentID + // The opponent is resolved from the room, never from the request. Only the + // authenticated participant may submit their own side of the debate. + participants, err := loadRoomParticipants(ctx, roomID) + if err != nil { + return nil, err + } + caller, err := resolveRoomCaller(ctx, participants, email) + if err != nil { + return nil, err + } + if err := validateSubmittedRole(caller.Role, role); err != nil { + return nil, err + } + if err := validateTranscriptPhases(role, transcripts); err != nil { + return nil, err + } + opponent, err := resolveRoomOpponent(participants, caller) + if err != nil { + return nil, err + } + opponentEmail := opponent.Email + if opponentEmail == "" { + opponentEmail, err = getUserEmailByID(ctx, opponent.ID) + if err != nil { + return nil, fmt.Errorf("failed to resolve opponent identity: %w", err) } - if resolvedEmail != "" { - if err := upsertTranscript(ctx, transcriptCollection, roomID, opponentRole, resolvedEmail, opponentTranscripts); err != nil { - return nil, err - } + } + if opponentEmail == "" || strings.EqualFold(opponentEmail, email) { + return nil, errors.New("opponent must be a different room participant") + } + if err := verifyExistingSubmissions(ctx, transcriptCollection, roomID, role, email, opponentEmail); err != nil { + return nil, err + } + + if len(transcripts) > 0 { + if err := upsertTranscript(ctx, transcriptCollection, roomID, role, email, transcripts); err != nil { + return nil, err } } } @@ -566,6 +583,31 @@ func saveTeammateTranscripts( return nil } +func validateSubmittedRole(assignedRole, submittedRole string) error { + assignedRole = strings.ToLower(strings.TrimSpace(assignedRole)) + if assignedRole == "" { + return nil + } + if submittedRole != assignedRole { + return fmt.Errorf("role %q does not match your assigned side %q", submittedRole, assignedRole) + } + return nil +} + +func validateTranscriptPhases(role string, transcripts map[string]string) error { + allowed, ok := roleAllowedPhases[role] + if !ok { + return fmt.Errorf("invalid debate role %q", role) + } + for phase := range transcripts { + if allowed[phase] || phase == "topic" { + continue + } + return fmt.Errorf("phase %q is not allowed for role %q", phase, role) + } + return nil +} + var roleAllowedPhases = map[string]map[string]bool{ "for": { "openingFor": true, @@ -713,6 +755,102 @@ func mergeTeamTranscripts(submissions ...map[string]string) map[string]string { return merged } +type roomParticipant struct { + ID string `bson:"id"` + Email string `bson:"email,omitempty"` + Role string `bson:"role,omitempty"` +} + +func loadRoomParticipants(ctx context.Context, roomID string) ([]roomParticipant, error) { + if db.MongoDatabase == nil { + return nil, errors.New("database is not initialized") + } + var room struct { + Participants []roomParticipant `bson:"participants"` + } + if err := db.MongoDatabase.Collection("rooms").FindOne(ctx, bson.M{"_id": roomID}).Decode(&room); err != nil { + if errors.Is(err, mongo.ErrNoDocuments) { + return nil, errors.New("debate room not found") + } + return nil, fmt.Errorf("failed to load debate room: %w", err) + } + if len(room.Participants) == 0 { + return nil, errors.New("debate room has no participants") + } + return room.Participants, nil +} + +func resolveRoomCaller(ctx context.Context, participants []roomParticipant, email string) (roomParticipant, error) { + if db.MongoDatabase == nil { + return roomParticipant{}, errors.New("database is not initialized") + } + var user models.User + if err := findUserByIdentifier(ctx, db.MongoDatabase.Collection("users"), email, &user); err != nil { + return roomParticipant{}, errors.New("authenticated user is not registered") + } + for _, participant := range participants { + if participant.ID != "" && participant.ID == user.ID.Hex() { + return participant, nil + } + if participant.Email != "" && strings.EqualFold(participant.Email, user.Email) { + return participant, nil + } + } + return roomParticipant{}, errors.New("authenticated user is not a participant of this room") +} + +func sameRoomParticipant(a, b roomParticipant) bool { + if a.ID != "" && b.ID != "" { + return a.ID == b.ID + } + return a.Email != "" && b.Email != "" && strings.EqualFold(a.Email, b.Email) +} + +func resolveRoomOpponent(participants []roomParticipant, caller roomParticipant) (roomParticipant, error) { + var opponent roomParticipant + found := false + for _, participant := range participants { + if sameRoomParticipant(participant, caller) { + continue + } + if found { + return roomParticipant{}, errors.New("debate room must have exactly two participants") + } + opponent = participant + found = true + } + if !found { + return roomParticipant{}, errors.New("debate room has no opponent participant") + } + return opponent, nil +} + +func verifyExistingSubmissions(ctx context.Context, collection *mongo.Collection, roomID, role, email, opponentEmail string) error { + for _, existingRole := range []string{"for", "against"} { + var existing models.DebateTranscript + err := collection.FindOne(ctx, bson.M{"roomId": roomID, "role": existingRole}).Decode(&existing) + if errors.Is(err, mongo.ErrNoDocuments) { + continue + } + if err != nil { + return err + } + if existingRole == role { + if !strings.EqualFold(existing.Email, email) { + return errors.New("this side already has a submission from another participant") + } + continue + } + if strings.EqualFold(existing.Email, email) { + return errors.New("authenticated user already submitted the opposing side") + } + if !strings.EqualFold(existing.Email, opponentEmail) { + return errors.New("opposing side was submitted by a non-participant") + } + } + return nil +} + func getUserEmailByID(ctx context.Context, userID string) (string, error) { if userID == "" { return "", errors.New("empty user ID") diff --git a/backend/services/transcriptservice_test.go b/backend/services/transcriptservice_test.go index 27d7de5a..10a8cbef 100644 --- a/backend/services/transcriptservice_test.go +++ b/backend/services/transcriptservice_test.go @@ -153,3 +153,74 @@ func TestTeamDebateSubmittersFallBackToRosterForLegacyDebates(t *testing.T) { t.Fatalf("teamDebateSubmitters() = %v, want [legacy-member@example.com]", submitters) } } + +func TestResolveRoomOpponentUsesOnlyRoomParticipants(t *testing.T) { + caller := roomParticipant{ID: "user-1", Email: "caller@example.com"} + opponent := roomParticipant{ID: "user-2", Email: "opponent@example.com"} + + got, err := resolveRoomOpponent([]roomParticipant{caller, opponent}, caller) + if err != nil { + t.Fatalf("resolveRoomOpponent() error = %v", err) + } + if got.ID != opponent.ID { + t.Fatalf("resolveRoomOpponent() = %#v, want opponent %#v", got, opponent) + } +} + +func TestResolveRoomOpponentRejectsAmbiguousOrMissingParticipants(t *testing.T) { + caller := roomParticipant{ID: "user-1", Email: "caller@example.com"} + opponent := roomParticipant{ID: "user-2", Email: "opponent@example.com"} + third := roomParticipant{ID: "user-3", Email: "third@example.com"} + + if _, err := resolveRoomOpponent([]roomParticipant{caller}, caller); err == nil { + t.Fatal("expected an error when the room has no opponent") + } + if _, err := resolveRoomOpponent([]roomParticipant{caller, opponent, third}, caller); err == nil { + t.Fatal("expected an error when the room has more than two participants") + } +} + +func TestSameRoomParticipantMatchesByIDBeforeEmail(t *testing.T) { + a := roomParticipant{ID: "user-1", Email: "old@example.com"} + b := roomParticipant{ID: "user-1", Email: "new@example.com"} + if !sameRoomParticipant(a, b) { + t.Fatal("same user ID with a changed email should be the same participant") + } + c := roomParticipant{ID: "user-2", Email: "new@example.com"} + if sameRoomParticipant(b, c) { + t.Fatal("different user IDs should not match even when emails are equal") + } +} + +func TestValidateSubmittedRole(t *testing.T) { + if err := validateSubmittedRole("for", "for"); err != nil { + t.Fatalf("matching assigned role rejected: %v", err) + } + if err := validateSubmittedRole("against", "for"); err == nil { + t.Fatal("expected an error when the submitted role differs from the assigned side") + } + if err := validateSubmittedRole("", "for"); err != nil { + t.Fatalf("legacy rooms without a stored role should not be blocked: %v", err) + } +} + +func TestValidateTranscriptPhases(t *testing.T) { + ownPhases := map[string]string{ + "openingFor": "opening", + "crossForQuestion": "question", + "crossForAnswer": "answer", + "closingFor": "closing", + "topic": "metadata", + } + if err := validateTranscriptPhases("for", ownPhases); err != nil { + t.Fatalf("own-side phases rejected: %v", err) + } + + opponentPhase := map[string]string{"openingAgainst": "forged"} + if err := validateTranscriptPhases("for", opponentPhase); err == nil { + t.Fatal("expected opponent-side phases to be rejected") + } + if err := validateTranscriptPhases("unknown", ownPhases); err == nil { + t.Fatal("expected an unknown role to be rejected") + } +} diff --git a/backend/websocket/websocket.go b/backend/websocket/websocket.go index d106ed54..1917b75e 100644 --- a/backend/websocket/websocket.go +++ b/backend/websocket/websocket.go @@ -722,6 +722,35 @@ func handleLiveTranscript(room *Room, conn *websocket.Conn, message Message, cli } // handlePhaseChange handles phase changes +func persistRoomDebaterRoles(roomID string, room *Room) { + if db.MongoDatabase == nil { + return + } + + participants := make([]bson.M, 0, len(room.Clients)) + for _, client := range room.Clients { + if client.IsSpectator { + continue + } + participants = append(participants, bson.M{ + "id": client.UserID, + "email": client.Email, + "displayName": client.Username, + "role": client.Role, + }) + } + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if _, err := db.MongoDatabase.Collection("rooms").UpdateOne( + ctx, + bson.M{"_id": roomID}, + bson.M{"$set": bson.M{"participants": participants}}, + ); err != nil { + log.Printf("[ws] failed to persist debater roles: room=%s err=%v", roomID, err) + } +} + func handlePhaseChange(room *Room, conn *websocket.Conn, message Message, roomID string) { type muteUpdate struct { client *Client @@ -784,6 +813,7 @@ func handlePhaseChange(room *Room, conn *websocket.Conn, message Message, roomID room.DebaterRoles[client.UserID] = client.Role } } + persistRoomDebaterRoles(roomID, room) } currentTurn := debatePhaseRole(room.Phase) muteUpdates := make([]muteUpdate, 0, len(room.Clients)) diff --git a/frontend/src/Pages/OnlineDebateRoom.tsx b/frontend/src/Pages/OnlineDebateRoom.tsx index e8987294..9a74341a 100644 --- a/frontend/src/Pages/OnlineDebateRoom.tsx +++ b/frontend/src/Pages/OnlineDebateRoom.tsx @@ -616,21 +616,13 @@ const OnlineDebateRoom = (): JSX.Element => { [roomId, setPopup, setRatingSummary] ); - // Function to send transcripts to backend + // Function to send only the authenticated caller's side to the backend const sendTranscriptsToBackend = useCallback( async ( roomId: string, role: DebateRole, - transcripts: { [key in DebatePhase]?: string }, - opponentRole: DebateRole, - opponentId: string | null, - opponentEmail: string | null, - opponentTranscripts: { [key in DebatePhase]?: string } + transcripts: { [key in DebatePhase]?: string } ) => { - if (!isRoomOwner) { - return null; - } - const token = getAuthToken(); if (!token) { throw new Error("No auth token found. Please sign in again."); @@ -643,15 +635,7 @@ const OnlineDebateRoom = (): JSX.Element => { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, - body: JSON.stringify({ - roomId, - role, - transcripts, - opponentRole, - opponentId, - opponentEmail, - opponentTranscripts, - }), + body: JSON.stringify({ roomId, role, transcripts }), }); if (!response.ok) { @@ -699,10 +683,10 @@ const OnlineDebateRoom = (): JSX.Element => { return null; }, - [isRoomOwner, setPopup, setRatingSummary, startJudgmentPolling] + [setPopup, setRatingSummary, startJudgmentPolling] ); - // Log message history, collect transcripts, and send to backend + // Every participant submits their own side; the server resolves the opponent const logMessageHistory = useCallback(async () => { if (submissionStartedRef.current) { return; @@ -717,17 +701,6 @@ const OnlineDebateRoom = (): JSX.Element => { return; } - if (!isRoomOwner) { - submissionStartedRef.current = true; - setPopup({ - show: true, - message: "Waiting for debate judgment...", - isJudging: true, - }); - startJudgmentPolling(localRole); - return; - } - submissionStartedRef.current = true; const gatherTranscriptsForRole = (role: DebateRole) => { @@ -759,20 +732,7 @@ const OnlineDebateRoom = (): JSX.Element => { }, {} as { [key in DebatePhase]?: string }); }; - const ownerTranscripts = gatherTranscriptsForRole(localRole); - const opponentRole: DebateRole = localRole === "for" ? "against" : "for"; - const opponentTranscripts = gatherTranscriptsForRole(opponentRole); - - const opponentDetails = - opponentUser || - roomParticipants.find( - (participant) => participant.id !== currentUser?.id - ) || - null; - - const opponentId = opponentDetails?.id ?? null; - const opponentEmail = - (opponentDetails as UserDetails & { email?: string })?.email ?? null; + const ownTranscripts = gatherTranscriptsForRole(localRole); setRatingSummary(null); setPopup({ @@ -786,11 +746,7 @@ const OnlineDebateRoom = (): JSX.Element => { const judgment = await sendTranscriptsToBackend( roomId, localRole, - ownerTranscripts, - opponentRole, - opponentId, - opponentEmail, - opponentTranscripts + ownTranscripts ); if (judgment) { setJudgmentData(judgment); @@ -818,17 +774,7 @@ const OnlineDebateRoom = (): JSX.Element => { ); setPopup({ show: false, message: "" }); } - }, [ - localRole, - roomId, - isRoomOwner, - speechTranscripts, - opponentUser, - roomParticipants, - currentUser, - sendTranscriptsToBackend, - startJudgmentPolling, - ]); + }, [localRole, roomId, speechTranscripts, sendTranscriptsToBackend]); const handleConcede = useCallback(() => { setIsConcedeDialogOpen(false);