Skip to content

Commit

Permalink
deleting api product now use 2 validations and by user Id and product Id
Browse files Browse the repository at this point in the history
  • Loading branch information
Rober040992 committed Jan 14, 2025
1 parent b63bf42 commit 708aff7
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
14 changes: 14 additions & 0 deletions nodepop/controllers/api/apiProductController.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Product from "../../models/Product.js"
import createError from 'http-errors'
// iportamos el modelo del producto
// API CRUD METHODS

Expand Down Expand Up @@ -94,7 +95,20 @@ export async function apiProductUpdate(req, res, next) {
export async function apiProductDelete(req, res, next) {
try {
//recogemos del los parametros de la ruta
const apiUserId = req.apiUserID
const productId = req.params.productId

const product = await Product.findOne({ _id: productId }) //validar que el producto existe
if (!product) {
console.warn(`WARNING - el usuario ${apiUserId} está intentando eliminar un producto inexistente`)
return next(createError(404))
}

if (product.owner.toString() !== apiUserId) { //validar que le pertenece
console.warn(`WARNING - el usuario ${apiUserId} está intentando eliminar un producto de otro usuario`)
return next(createError(401))
}

// buscamos el product en la DB pasandole el filtro de el que vamos a borrar
await Product.deleteOne({ _id: productId })

Expand Down
2 changes: 1 addition & 1 deletion nodepop/controllers/productController.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export async function deleteProduct(req, res, next) {
}
//verificar que el owner coincide con el userId , si no lanzo un warn
if (product.owner.toString() !== userId) {
console.warn(`WARNING - el usuario ${userId} está intentando eliminar un agente de otro usuario`)
console.warn(`WARNING - el usuario ${userId} está intentando eliminar un producto de otro usuario`)
return next(createError(401, 'Not authorized'))
}

Expand Down

0 comments on commit 708aff7

Please sign in to comment.