From d9bd3f44dc60d862099c64906a2b903f0ca8f7be Mon Sep 17 00:00:00 2001 From: Inko-z Date: Thu, 2 Apr 2026 16:58:52 -0600 Subject: [PATCH 1/3] Added route to update event information --- .../src/controllers/event_controller.ts | 157 ++++++++++++++++++ shatter-backend/src/routes/event_routes.ts | 4 +- 2 files changed, 159 insertions(+), 2 deletions(-) diff --git a/shatter-backend/src/controllers/event_controller.ts b/shatter-backend/src/controllers/event_controller.ts index 9c817b5..6f44c09 100644 --- a/shatter-backend/src/controllers/event_controller.ts +++ b/shatter-backend/src/controllers/event_controller.ts @@ -11,6 +11,8 @@ import { User } from "../models/user_model.js"; import { ParticipantConnection } from "../models/participant_connection_model.js"; import { Bingo } from "../models/bingo_model.js"; import { Types } from "mongoose"; +import mongoose from "mongoose"; + /** * Create a participant with automatic name suffix on collision. @@ -683,4 +685,159 @@ export async function deleteEvent(req: Request, res: Response) { console.error("DELETE EVENT ERROR:", err); return res.status(500).json({ success: false, error: err.message }); } +} + + +/** + * PUT /api/events/:eventId + * Update an event (host only) + * + * @param req.params.eventId - Event ID to update (required) + * @param req.user.userId - Authenticated user ID (from access token) + * + * @param req.body.name - Updated event name (optional) + * @param req.body.description - Updated event description (optional) + * @param req.body.startDate - Updated event start date (optional) + * @param req.body.endDate - Updated event end date (optional) + * @param req.body.maxParticipant - Updated maximum number of participants (optional) + * @param req.body.currentState - Updated current state of the event (optional) + * @param req.body.gameType - Updated game type of the event (optional) + * + * + * @returns 200 on success + * @returns 400 if event is completed + * @returns 403 if user is not the host + * @returns 404 if event not found + */ +type UpdateEventBody = { + name?: string; + description?: string; + startDate?: string | Date; + endDate?: string | Date; + maxParticipant?: number; + currentState?: "Upcoming" | "In Progress" | "Completed"; + gameType?: "Name Bingo"; + eventImg?: string; +}; + +export async function updateEvent(req: Request<{ eventId: string }, {}, UpdateEventBody>, res: Response) { + try { + const { eventId } = req.params; + const userId = req.user?.userId; + + if (!eventId) { + return res.status(400).json({ + success: false, + error: "Missing eventId", + }); + } + + if (!userId) { + return res.status(401).json({ + success: false, + error: "Unauthorized: missing authenticated user", + }); + } + + if (!mongoose.Types.ObjectId.isValid(eventId)) { + return res.status(400).json({ + success: false, + error: "Invalid eventId", + }); + } + + const event = await Event.findById(eventId); + + if (!event) { + return res.status(404).json({ + success: false, + error: "Event not found", + }); + } + + // Verify authenticated user is the creator/host + if (event.createdBy.toString() !== userId.toString()) { + return res.status(403).json({ + success: false, + error: "Forbidden: only the event creator can update this event", + }); + } + + if (event.currentState === "Completed") { + return res.status(400).json({ + success: false, + error: "Cannot update a completed event", + }); + } + + const { + name, + description, + startDate, + endDate, + maxParticipant, + currentState, + gameType, + eventImg, + } = req.body; + + const updateData: Partial<{ + name: string; + description: string; + startDate: Date; + endDate: Date; + maxParticipant: number; + currentState: "Upcoming" | "In Progress" | "Completed"; + gameType: "Name Bingo"; + eventImg?: string; + }> = {}; + + if (name !== undefined) updateData.name = name; + if (description !== undefined) updateData.description = description; + if (startDate !== undefined) updateData.startDate = new Date(startDate); + if (endDate !== undefined) updateData.endDate = new Date(endDate); + if (maxParticipant !== undefined) updateData.maxParticipant = maxParticipant; + if (currentState !== undefined) updateData.currentState = currentState; + if (gameType !== undefined) updateData.gameType = gameType; + if (eventImg !== undefined) updateData.eventImg = eventImg; + + if (Object.keys(updateData).length === 0) { + return res.status(400).json({ + success: false, + error: "No fields provided to update", + }); + } + + // Optional extra guard for dates here too + const finalStartDate = updateData.startDate ?? event.startDate; + const finalEndDate = updateData.endDate ?? event.endDate; + + if (finalEndDate <= finalStartDate) { + return res.status(400).json({ + success: false, + error: "endDate must be after startDate", + }); + } + + const updatedEvent = await Event.findByIdAndUpdate( + eventId, + { $set: updateData }, + { + new: true, + runValidators: true, + } + ); + + return res.status(200).json({ + success: true, + message: "Event updated successfully", + data: updatedEvent, + }); + } catch (err: any) { + console.error("UPDATE EVENT ERROR:", err); + return res.status(500).json({ + success: false, + error: err.message || "Internal server error", + }); + } } \ No newline at end of file diff --git a/shatter-backend/src/routes/event_routes.ts b/shatter-backend/src/routes/event_routes.ts index 814c1db..424ffb0 100644 --- a/shatter-backend/src/routes/event_routes.ts +++ b/shatter-backend/src/routes/event_routes.ts @@ -1,5 +1,5 @@ import { Router } from 'express'; -import { createEvent, getEventByJoinCode, getEventById, joinEventAsUser, joinEventAsGuest, getEventsByUserId, updateEventStatus, leaveEvent, deleteEvent } from '../controllers/event_controller.js'; +import { createEvent, getEventByJoinCode, getEventById, joinEventAsUser, joinEventAsGuest, getEventsByUserId, updateEventStatus, leaveEvent, deleteEvent, updateEvent } from '../controllers/event_controller.js'; import { authMiddleware } from '../middleware/auth_middleware.js'; const router = Router(); @@ -14,6 +14,6 @@ router.post("/:eventId/join/guest", joinEventAsGuest); router.post("/:eventId/leave", authMiddleware, leaveEvent); router.delete("/:eventId", authMiddleware, deleteEvent); router.get("/createdEvents/user/:userId", authMiddleware, getEventsByUserId); - +router.put("/update/:eventId", authMiddleware, updateEvent); export default router; \ No newline at end of file From ac1c835613cc87341498b58d0fff8f1199a781eb Mon Sep 17 00:00:00 2001 From: Inko-z Date: Thu, 2 Apr 2026 17:40:42 -0600 Subject: [PATCH 2/3] Added route Documentation --- shatter-backend/docs/API_REFERENCE.md | 81 +++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/shatter-backend/docs/API_REFERENCE.md b/shatter-backend/docs/API_REFERENCE.md index 68cfa63..3ab3f79 100644 --- a/shatter-backend/docs/API_REFERENCE.md +++ b/shatter-backend/docs/API_REFERENCE.md @@ -38,6 +38,7 @@ - [POST `/api/events/:eventId/leave`](#post-apieventseventidleave) - [DELETE `/api/events/:eventId`](#delete-apieventseventid) - [GET `/api/events/createdEvents/user/:userId`](#get-apieventscreatedeventsuseruserid) + - [PUT `/api/events/update/:eventId`](#put-apieventsupdateeventid) - [Bingo (`/api/bingo`)](#bingo-apibingo) - [POST `/api/bingo/createBingo`](#post-apibingocreatebingo) - [GET `/api/bingo/getBingo/:eventId`](#get-apibingogetbingoeventid) @@ -981,6 +982,86 @@ Get all events created by a specific user. | Status | Error | |--------|-------| | 404 | `"No events found for this user"` | +--- +### PUT `/api/events/update/:eventId` + +Update an existing event (host only). Only the fields provided in the request body will be updated. + +- **Auth:** Protected (Bearer Token required) + +--- + +**URL Params:** + +| Param | Type | Required | +|-----------|----------|----------| +| `eventId` | ObjectId | Yes | + +--- + +**Request Body (all fields optional):** + +| Field | Type | Description | +|------------------|----------|------------------------------------------| +| `name` | string | Updated event name | +| `description` | string | Updated event description | +| `startDate` | Date | Updated start date (ISO string) | +| `endDate` | Date | Updated end date (ISO string) | +| `maxParticipant` | number | Updated max number of participants | +| `currentState` | string | `"Upcoming" \| "In Progress" \| "Completed"` | +| `gameType` | string | `"Name Bingo"` | +| `eventImg` | string | URL of event image | + +--- + +**Success Response (200):** + +```json +{ + "success": true, + "message": "Event updated successfully", + "data": { + "_id": "665a...", + "name": "Updated Event Name", + "description": "New description", + "startDate": "2026-05-01T10:00:00.000Z", + "endDate": "2026-05-02T10:00:00.000Z", + "maxParticipant": 50, + "currentState": "Upcoming", + "gameType": "Name Bingo", + "createdBy": "664f..." + } +} +``` + +--- + +**Error Responses:** + +| Status | Error | +|--------|-------| +| 400 | `"Missing eventId"` | +| 400 | `"Invalid eventId"` | +| 400 | `"No fields provided to update"` | +| 400 | `"Invalid startDate"` | +| 400 | `"Invalid endDate"` | +| 400 | `"endDate must be after startDate"` | +| 400 | `"maxParticipant must be a positive number"` | +| 400 | `"Invalid currentState"` | +| 400 | `"Invalid gameType"` | +| 400 | `"Cannot update a completed event"` | +| 401 | `"Unauthorized"` | +| 403 | `"Only the event creator can update this event"` | +| 404 | `"Event not found"` | + +--- + +**Notes:** + +- Only the event creator (`createdBy`) can update the event. +- Fields not included in the request body will remain unchanged. +- `startDate` and `endDate` must be valid dates, and `endDate` must be after `startDate`. +- Validation is enforced both at the request level and database level. --- From 468e1324e5213dc2d25029c9e89a72a9e9499a8e Mon Sep 17 00:00:00 2001 From: rxmox Date: Thu, 2 Apr 2026 19:02:01 -0600 Subject: [PATCH 3/3] Add input validation and fix route for update event endpoint - Remove currentState from allowed update fields to prevent bypassing the state machine and missing Pusher real-time events - Add type and value validation for all fields (null, wrong types, empty strings, invalid dates, negative maxParticipant) - Change route from /update/:eventId to /:eventId to match codebase conventions - Remove duplicate mongoose import - Sync API documentation with actual error messages and behavior --- shatter-backend/docs/API_REFERENCE.md | 29 ++--- .../src/controllers/event_controller.ts | 104 ++++++++++++++---- shatter-backend/src/routes/event_routes.ts | 4 +- 3 files changed, 98 insertions(+), 39 deletions(-) diff --git a/shatter-backend/docs/API_REFERENCE.md b/shatter-backend/docs/API_REFERENCE.md index 3ab3f79..082a2ed 100644 --- a/shatter-backend/docs/API_REFERENCE.md +++ b/shatter-backend/docs/API_REFERENCE.md @@ -38,7 +38,7 @@ - [POST `/api/events/:eventId/leave`](#post-apieventseventidleave) - [DELETE `/api/events/:eventId`](#delete-apieventseventid) - [GET `/api/events/createdEvents/user/:userId`](#get-apieventscreatedeventsuseruserid) - - [PUT `/api/events/update/:eventId`](#put-apieventsupdateeventid) + - [PUT `/api/events/:eventId`](#put-apieventseventid) - [Bingo (`/api/bingo`)](#bingo-apibingo) - [POST `/api/bingo/createBingo`](#post-apibingocreatebingo) - [GET `/api/bingo/getBingo/:eventId`](#get-apibingogetbingoeventid) @@ -983,9 +983,9 @@ Get all events created by a specific user. |--------|-------| | 404 | `"No events found for this user"` | --- -### PUT `/api/events/update/:eventId` +### PUT `/api/events/:eventId` -Update an existing event (host only). Only the fields provided in the request body will be updated. +Update an existing event's basic information (host only). Only the fields provided in the request body will be updated. To change event status, use `PUT /api/events/:eventId/status` instead. - **Auth:** Protected (Bearer Token required) @@ -1003,12 +1003,11 @@ Update an existing event (host only). Only the fields provided in the request bo | Field | Type | Description | |------------------|----------|------------------------------------------| -| `name` | string | Updated event name | -| `description` | string | Updated event description | +| `name` | string | Updated event name (cannot be empty) | +| `description` | string | Updated event description (cannot be empty) | | `startDate` | Date | Updated start date (ISO string) | | `endDate` | Date | Updated end date (ISO string) | -| `maxParticipant` | number | Updated max number of participants | -| `currentState` | string | `"Upcoming" \| "In Progress" \| "Completed"` | +| `maxParticipant` | number | Updated max participants (positive integer, >= current count) | | `gameType` | string | `"Name Bingo"` | | `eventImg` | string | URL of event image | @@ -1043,14 +1042,17 @@ Update an existing event (host only). Only the fields provided in the request bo | 400 | `"Missing eventId"` | | 400 | `"Invalid eventId"` | | 400 | `"No fields provided to update"` | +| 400 | `"Name must be a non-empty string"` | +| 400 | `"Description must be a non-empty string"` | | 400 | `"Invalid startDate"` | | 400 | `"Invalid endDate"` | | 400 | `"endDate must be after startDate"` | -| 400 | `"maxParticipant must be a positive number"` | -| 400 | `"Invalid currentState"` | -| 400 | `"Invalid gameType"` | +| 400 | `"maxParticipant must be a positive integer"` | +| 400 | `"maxParticipant cannot be less than the current number of participants ({count})"` | +| 400 | `"Invalid gameType. Must be one of: Name Bingo"` | +| 400 | `"eventImg must be a string"` | | 400 | `"Cannot update a completed event"` | -| 401 | `"Unauthorized"` | +| 401 | `"Unauthorized: missing authenticated user"` | | 403 | `"Only the event creator can update this event"` | | 404 | `"Event not found"` | @@ -1060,8 +1062,9 @@ Update an existing event (host only). Only the fields provided in the request bo - Only the event creator (`createdBy`) can update the event. - Fields not included in the request body will remain unchanged. -- `startDate` and `endDate` must be valid dates, and `endDate` must be after `startDate`. -- Validation is enforced both at the request level and database level. +- `currentState` cannot be changed through this endpoint — use `PUT /api/events/:eventId/status`. +- `startDate` and `endDate` must be valid ISO date strings, and `endDate` must be after `startDate`. +- `maxParticipant` cannot be set below the current number of participants in the event. --- diff --git a/shatter-backend/src/controllers/event_controller.ts b/shatter-backend/src/controllers/event_controller.ts index 6f44c09..561cc57 100644 --- a/shatter-backend/src/controllers/event_controller.ts +++ b/shatter-backend/src/controllers/event_controller.ts @@ -11,8 +11,6 @@ import { User } from "../models/user_model.js"; import { ParticipantConnection } from "../models/participant_connection_model.js"; import { Bingo } from "../models/bingo_model.js"; import { Types } from "mongoose"; -import mongoose from "mongoose"; - /** * Create a participant with automatic name suffix on collision. @@ -690,22 +688,22 @@ export async function deleteEvent(req: Request, res: Response) { /** * PUT /api/events/:eventId - * Update an event (host only) + * Update an event's basic information (host only). + * Does NOT allow changing currentState — use PUT /:eventId/status for that. * * @param req.params.eventId - Event ID to update (required) * @param req.user.userId - Authenticated user ID (from access token) - * + * * @param req.body.name - Updated event name (optional) * @param req.body.description - Updated event description (optional) * @param req.body.startDate - Updated event start date (optional) * @param req.body.endDate - Updated event end date (optional) * @param req.body.maxParticipant - Updated maximum number of participants (optional) - * @param req.body.currentState - Updated current state of the event (optional) * @param req.body.gameType - Updated game type of the event (optional) - * - * + * @param req.body.eventImg - Updated event image URL (optional) + * * @returns 200 on success - * @returns 400 if event is completed + * @returns 400 if event is completed or validation fails * @returns 403 if user is not the host * @returns 404 if event not found */ @@ -715,7 +713,6 @@ type UpdateEventBody = { startDate?: string | Date; endDate?: string | Date; maxParticipant?: number; - currentState?: "Upcoming" | "In Progress" | "Completed"; gameType?: "Name Bingo"; eventImg?: string; }; @@ -739,7 +736,7 @@ export async function updateEvent(req: Request<{ eventId: string }, {}, UpdateEv }); } - if (!mongoose.Types.ObjectId.isValid(eventId)) { + if (!Types.ObjectId.isValid(eventId)) { return res.status(400).json({ success: false, error: "Invalid eventId", @@ -759,7 +756,7 @@ export async function updateEvent(req: Request<{ eventId: string }, {}, UpdateEv if (event.createdBy.toString() !== userId.toString()) { return res.status(403).json({ success: false, - error: "Forbidden: only the event creator can update this event", + error: "Only the event creator can update this event", }); } @@ -776,7 +773,6 @@ export async function updateEvent(req: Request<{ eventId: string }, {}, UpdateEv startDate, endDate, maxParticipant, - currentState, gameType, eventImg, } = req.body; @@ -787,19 +783,79 @@ export async function updateEvent(req: Request<{ eventId: string }, {}, UpdateEv startDate: Date; endDate: Date; maxParticipant: number; - currentState: "Upcoming" | "In Progress" | "Completed"; gameType: "Name Bingo"; - eventImg?: string; + eventImg: string; }> = {}; - if (name !== undefined) updateData.name = name; - if (description !== undefined) updateData.description = description; - if (startDate !== undefined) updateData.startDate = new Date(startDate); - if (endDate !== undefined) updateData.endDate = new Date(endDate); - if (maxParticipant !== undefined) updateData.maxParticipant = maxParticipant; - if (currentState !== undefined) updateData.currentState = currentState; - if (gameType !== undefined) updateData.gameType = gameType; - if (eventImg !== undefined) updateData.eventImg = eventImg; + // Validate and set name + if (name !== undefined) { + if (typeof name !== "string" || !name.trim()) { + return res.status(400).json({ success: false, error: "Name must be a non-empty string" }); + } + updateData.name = name; + } + + // Validate and set description + if (description !== undefined) { + if (typeof description !== "string" || !description.trim()) { + return res.status(400).json({ success: false, error: "Description must be a non-empty string" }); + } + updateData.description = description; + } + + // Validate and set startDate + if (startDate !== undefined) { + if (startDate === null || typeof startDate === "boolean") { + return res.status(400).json({ success: false, error: "Invalid startDate" }); + } + const parsed = new Date(startDate); + if (isNaN(parsed.getTime())) { + return res.status(400).json({ success: false, error: "Invalid startDate" }); + } + updateData.startDate = parsed; + } + + // Validate and set endDate + if (endDate !== undefined) { + if (endDate === null || typeof endDate === "boolean") { + return res.status(400).json({ success: false, error: "Invalid endDate" }); + } + const parsed = new Date(endDate); + if (isNaN(parsed.getTime())) { + return res.status(400).json({ success: false, error: "Invalid endDate" }); + } + updateData.endDate = parsed; + } + + // Validate and set maxParticipant + if (maxParticipant !== undefined) { + if (maxParticipant === null || !Number.isInteger(maxParticipant) || maxParticipant <= 0) { + return res.status(400).json({ success: false, error: "maxParticipant must be a positive integer" }); + } + if (maxParticipant < event.participantIds.length) { + return res.status(400).json({ + success: false, + error: `maxParticipant cannot be less than the current number of participants (${event.participantIds.length})`, + }); + } + updateData.maxParticipant = maxParticipant; + } + + // Validate and set gameType + if (gameType !== undefined) { + const validGameTypes = ["Name Bingo"]; + if (typeof gameType !== "string" || !validGameTypes.includes(gameType)) { + return res.status(400).json({ success: false, error: `Invalid gameType. Must be one of: ${validGameTypes.join(", ")}` }); + } + updateData.gameType = gameType; + } + + if (eventImg !== undefined) { + if (typeof eventImg !== "string") { + return res.status(400).json({ success: false, error: "eventImg must be a string" }); + } + updateData.eventImg = eventImg; + } if (Object.keys(updateData).length === 0) { return res.status(400).json({ @@ -808,7 +864,7 @@ export async function updateEvent(req: Request<{ eventId: string }, {}, UpdateEv }); } - // Optional extra guard for dates here too + // Validate date ordering (compare updated dates against existing ones) const finalStartDate = updateData.startDate ?? event.startDate; const finalEndDate = updateData.endDate ?? event.endDate; @@ -840,4 +896,4 @@ export async function updateEvent(req: Request<{ eventId: string }, {}, UpdateEv error: err.message || "Internal server error", }); } -} \ No newline at end of file +} diff --git a/shatter-backend/src/routes/event_routes.ts b/shatter-backend/src/routes/event_routes.ts index 424ffb0..6d3e447 100644 --- a/shatter-backend/src/routes/event_routes.ts +++ b/shatter-backend/src/routes/event_routes.ts @@ -14,6 +14,6 @@ router.post("/:eventId/join/guest", joinEventAsGuest); router.post("/:eventId/leave", authMiddleware, leaveEvent); router.delete("/:eventId", authMiddleware, deleteEvent); router.get("/createdEvents/user/:userId", authMiddleware, getEventsByUserId); -router.put("/update/:eventId", authMiddleware, updateEvent); +router.put("/:eventId", authMiddleware, updateEvent); -export default router; \ No newline at end of file +export default router;