AUTHORIZATION FRO /listings

 A MIDDLEWARE IS CREATED TO VERIFY AUTHORIZATION AND IT IS ADDED TO EDIT AND DELETE ROUTE.

module.exports.isOwner =async (req, res, next) => {
  let { id } = req.params;
  let listing = await Listing.findById(id);
  if (!listing.owner._id.equals(res.locals.currUser._id)) {
    req.flash("error", "You do not have access to perform this task!");
    return res.redirect(`/listings/${id}`);
  }
  next();
};





// EDIT ROUTE
router.get(
  "/:id/edit",
  isLoggedIn,
  isOwner,
  wrapAsync(async (req, res) => {
    let { id } = req.params;
    const listing = await Listing.findById(id);
    if (!listing) {
      req.flash("error", "Listing requested doesn't exist!");
      res.redirect("/listings");
    }
    res.render("listings/edit.ejs", { listing });
  })
);
// UPDATE ROUTE
router.put(
  "/:id",
  isLoggedIn,
  isOwner,
  ValidateListing,
  wrapAsync(async (req, res) => {
    if (!req.body.listing) {
      throw new ExpressError(400, "send valid data!");
    }
    let { id } = req.params;
    await Listing.findByIdAndUpdate(id, { ...req.body.listing });
    req.flash("success", "Updated Successful!");

    res.redirect(`/listings/${id}`);
  })
);

// DELETE ROUTE
router.delete(
  "/:id",
  isLoggedIn,
  isOwner,
  wrapAsync(async (req, res) => {
    let { id } = req.params;
    let deletedList = await Listing.findByIdAndDelete(id);
    console.log(deletedList);
    req.flash("success", "Listing Deleted!");

    res.redirect("/listings");
  })
);



Comments