Skip to content

OM-127: Agregando correcta autenticación - #43

Merged
Lianyang1234 merged 3 commits into
devfrom
OM-127
Mar 18, 2026
Merged

Lianyang1234 merged 3 commits into
devfrom
OM-127

Conversation

@CrisNAC

@CrisNAC CrisNAC commented Mar 18, 2026 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

Notas de Lanzamiento

  • Nueva Funcionalidad

    • Autenticación obligatoria para crear reseñas de productos.
  • Correcciones de Errores

    • Mensaje de autenticación más claro ("Token inválido o usuario no autenticado").
    • Manejo de errores mejorado: mensajes más precisos y diferenciados según error de cliente o de servidor.

@coderabbitai

coderabbitai Bot commented Mar 18, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Se añade el middleware de autenticación en la ruta POST /product-review y el controlador pasa a leer req.user.id_user; además se ajustan mensajes 401 y la lógica para elegir el mensaje y status en respuestas de error.

Changes

Cohort / File(s) Summary
Rutas de product-review
src/modules/users/product-review/product-review.routes.js
Se importa authenticate desde config/jwt.config.js y la ruta POST cambia a router.post("/", authenticate, createProductReview) para exigir autenticación.
Controlador de product-review
src/modules/users/product-review/product-review.controller.js
Se lee customerId desde req.user?.id_user; mensaje 401 actualizado a "Token inválido o usuario no autenticado"; se introduce safeMessage para errores y se usa status(error.status) sin forzar fallback previo.

Sequence Diagram(s)

sequenceDiagram
    participant Cliente as Cliente
    participant Router as Router (routes)
    participant Auth as Middleware authenticate
    participant Controller as ProductReviewController
    participant Service as createProductReviewService

    Cliente->>Router: POST /product-review (body, token)
    Router->>Auth: validar token (authenticate)
    Auth-->>Router: usuario validado / 401 rechazado
    Router->>Controller: createProductReview(req con user)
    Controller->>Service: createProductReviewService(payload, customerId)
    Service-->>Controller: resultado creado / error
    Controller-->>Cliente: 201 Created / error (status y safeMessage)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • Om 127 #37: Modifica el mismo controlador y las rutas de product-review (autenticación y lectura de req.user.id_user).

Suggested reviewers

  • leoAchu16

Poem

🐰

Brinco entre rutas y controlador,
el token pasa y el usuario hallé,
el id en su lugar ahora está,
mensajes claros al volver,
¡reseña creada, a saltar y celebrar! 🎉

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed El título es claro y específico, describe correctamente el cambio principal: la adición de autenticación en la ruta de creación de reseñas de productos.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch OM-127
📝 Coding Plan
  • Generate coding plan for human review comments

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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)
src/modules/users/product-review/product-review.controller.js (1)

9-9: Evitá loguear el objeto error completo.

En Line 9 conviene registrar sólo campos acotados (message/status) para reducir riesgo de exponer datos sensibles en logs.

🧹 Propuesta de logging más seguro
-    console.error("Error creando reseña:", error);
+    console.error("Error creando reseña", {
+      message: error?.message,
+      status: error?.status
+    });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/modules/users/product-review/product-review.controller.js` at line 9,
Replace the current full-object logging at the console.error call so you don't
dump the whole error object; instead extract and log only safe fields (e.g.
error.message and error.status or code) and any minimal contextual text (for
example in the product-review controller's error handler where you call
console.error("Error creando reseña:", error)). Update that site to log a
concise message and the selected fields only (or use your app logger like
logger.error with a message plus { status: error.status }) rather than the
entire error object.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/modules/users/product-review/product-review.controller.js`:
- Around line 10-12: Normalize error.status to the valid HTTP error range by
replacing the current Number.isInteger(error?.status) check with a defensive
check that ensures error?.status is an integer between 400 and 599 (inclusive),
otherwise fallback to 500; update the assignment to the status variable
(currently using error?.status) and keep the subsequent
res.status(status).json(...) behavior so the controller always returns a valid
4xx/5xx status.
- Line 5: El controller usa directamente const customerId = req.user.id_user;
sin validación defensiva; cambia a comprobar que req.user?.id_user existe antes
de usarlo (mirror a product.controller.js), y si falta devolver un 401 con un
mensaje claro (por ejemplo "Token inválido o usuario no autenticado"), dejando
el resto de la función sin cambios; busca la variable customerId en
product-review.controller.js y aplica la validación previa al uso para evitar
TypeError y mantener consistencia con product.controller.js.

---

Nitpick comments:
In `@src/modules/users/product-review/product-review.controller.js`:
- Line 9: Replace the current full-object logging at the console.error call so
you don't dump the whole error object; instead extract and log only safe fields
(e.g. error.message and error.status or code) and any minimal contextual text
(for example in the product-review controller's error handler where you call
console.error("Error creando reseña:", error)). Update that site to log a
concise message and the selected fields only (or use your app logger like
logger.error with a message plus { status: error.status }) rather than the
entire error object.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7a8e4ff9-28ac-4328-b712-6aa2f2a81c65

📥 Commits

Reviewing files that changed from the base of the PR and between 58bd0b4 and 39daf1b.

📒 Files selected for processing (2)
  • src/modules/users/product-review/product-review.controller.js
  • src/modules/users/product-review/product-review.routes.js

Comment thread src/modules/users/product-review/product-review.controller.js Outdated
Comment thread src/modules/users/product-review/product-review.controller.js Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (1)
src/modules/users/product-review/product-review.controller.js (1)

5-5: Evitá dejar comentarios de revisión en código productivo.

Los comentarios Revisión 1/2 parecen temporales del proceso de PR; te sugiero reemplazarlos por comentarios funcionales o removerlos.

Also applies to: 16-16

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/modules/users/product-review/product-review.controller.js` at line 5,
Remove the temporary PR review comments "Revisión 1" and "Revisión 2" from
product-review.controller.js and either delete them or replace them with
concise, functional comments explaining intent (e.g., why extra defensive
validation is present) so production code contains only meaningful
documentation; search for the exact strings "Revisión 1" and "Revisión 2" in the
file and update the surrounding comment to reference the relevant function or
validation logic instead of keeping PR artifacts.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/modules/users/product-review/product-review.controller.js`:
- Around line 23-25: The response builder in the product-review controller
currently uses error.message directly for 4xx responses, which can be undefined;
update the return in the res.status(status).json(...) path to provide a fallback
string when error.message is falsy (e.g., use a default like "Solicitud
inválida" or "Error del cliente" or derive one from status) so that clients
always receive a useful message; locate the code using the variables/status and
res.status(...) in product-review.controller.js and change the message
expression to include this fallback.

---

Nitpick comments:
In `@src/modules/users/product-review/product-review.controller.js`:
- Line 5: Remove the temporary PR review comments "Revisión 1" and "Revisión 2"
from product-review.controller.js and either delete them or replace them with
concise, functional comments explaining intent (e.g., why extra defensive
validation is present) so production code contains only meaningful
documentation; search for the exact strings "Revisión 1" and "Revisión 2" in the
file and update the surrounding comment to reference the relevant function or
validation logic instead of keeping PR artifacts.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ce90e788-efc6-44a7-804e-d9717234aabd

📥 Commits

Reviewing files that changed from the base of the PR and between 39daf1b and 8d03ee6.

📒 Files selected for processing (1)
  • src/modules/users/product-review/product-review.controller.js

Comment thread src/modules/users/product-review/product-review.controller.js Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

♻️ Duplicate comments (1)
src/modules/users/product-review/product-review.controller.js (1)

16-24: ⚠️ Potential issue | 🟠 Major

Normalizá error.status antes de usarlo en res.status.

En Line 17-23 se usa error.status directo. Si llega undefined, null o un valor fuera de 4xx/5xx, el handler puede fallar o responder con status inválido. Esto además reintroduce un punto ya reportado antes.

🔧 Ajuste propuesto
-    const safeMessage =
-      error.status < 500 && typeof error?.message === "string" && error.message.trim()
-        ? error.message
-        : error.status < 500
-          ? "Solicitud inválida"
-          : "Error interno del servidor";
+    const status =
+      Number.isInteger(error?.status) && error.status >= 400 && error.status < 600
+        ? error.status
+        : 500;
+
+    const safeMessage =
+      status < 500 && typeof error?.message === "string" && error.message.trim()
+        ? error.message
+        : status < 500
+          ? "Solicitud inválida"
+          : "Error interno del servidor";
 
-    return res.status(error.status).json({
+    return res.status(status).json({
       message: safeMessage
     });
En Express 5.x, ¿qué ocurre cuando `res.status(...)` recibe `undefined`, `null` o un código fuera del rango HTTP válido?
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/modules/users/product-review/product-review.controller.js` around lines
16 - 24, The handler uses error.status directly (seen in safeMessage and
res.status) which can be undefined, null or out-of-range; normalize it first
(e.g., compute a validatedStatus variable by coercing to a number, defaulting to
500 for missing/invalid values, and clamping to the 4xx/5xx range) and use that
validatedStatus in the safeMessage logic and the res.status call (referencing
safeMessage, error.status and res.status in the controller). Ensure the logic
still treats <500 as client errors when appropriate but uses the validatedStatus
value for both message selection and response status to avoid sending invalid
HTTP codes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@src/modules/users/product-review/product-review.controller.js`:
- Around line 16-24: The handler uses error.status directly (seen in safeMessage
and res.status) which can be undefined, null or out-of-range; normalize it first
(e.g., compute a validatedStatus variable by coercing to a number, defaulting to
500 for missing/invalid values, and clamping to the 4xx/5xx range) and use that
validatedStatus in the safeMessage logic and the res.status call (referencing
safeMessage, error.status and res.status in the controller). Ensure the logic
still treats <500 as client errors when appropriate but uses the validatedStatus
value for both message selection and response status to avoid sending invalid
HTTP codes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2de41be4-5c07-4b5a-9c30-8d9c1fdb7be6

📥 Commits

Reviewing files that changed from the base of the PR and between 8d03ee6 and 560e420.

📒 Files selected for processing (1)
  • src/modules/users/product-review/product-review.controller.js

@Lianyang1234 Lianyang1234 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM!

@Lianyang1234
Lianyang1234 merged commit 066dd57 into dev Mar 18, 2026
1 of 2 checks passed
@Andoumeda
Andoumeda deleted the OM-127 branch March 26, 2026 18:24
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.

2 participants