Skip to content

Commit

Permalink
#13 - Fix deleting local image on DELETE and UPDATE route
Browse files Browse the repository at this point in the history
  • Loading branch information
Flashback054 committed Dec 12, 2023
1 parent 68c4ce0 commit 5da40fb
Show file tree
Hide file tree
Showing 14 changed files with 54 additions and 14 deletions.
19 changes: 9 additions & 10 deletions backend/src/controllers/auth.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,8 +148,6 @@ exports.protect = async (req, res, next) => {
}
refreshToken = req.cookies.refreshToken;

console.log(accessToken, refreshToken);

// If there is no accessToken and no refreshToken, throw error
if (!accessToken && !refreshToken) {
throw new AppError(
Expand Down Expand Up @@ -189,6 +187,15 @@ exports.protect = async (req, res, next) => {
// 2.2) Verify refreshToken
try {
decoded = await verifyToken(refreshToken, process.env.REFRESH_SECRET);

// If refreshToken is valid, send new accessToken
const { accessToken, accessTokenOptions } = createAccessToken(
{
_id: decoded.id,
},
req
);
res.cookie("accessToken", accessToken, accessTokenOptions);
} catch (err) {
if (err instanceof jwt.TokenExpiredError) {
throw new AppError(
Expand Down Expand Up @@ -242,14 +249,6 @@ exports.protect = async (req, res, next) => {
// GRANT ACCESS TO PROTECTED ROUTE
req.user = currentUser;

if (sendNewAccessToken) {
const { accessToken, accessTokenOptions } = createAccessToken(
req.user,
req
);
res.cookie("accessToken", accessToken, accessTokenOptions);
}

return next();
};

Expand Down
26 changes: 23 additions & 3 deletions backend/src/controllers/controller.factory.js
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,8 @@ exports.getOne = (Model, options) => async (req, res, next) => {
};

exports.updateOne = (Model) => async (req, res, next) => {
const oldDoc = await Model.findById(req.params.id);

const doc = await Model.findByIdAndUpdate(req.params.id, req.body, {
new: true,
runValidators: true,
Expand All @@ -110,6 +112,26 @@ exports.updateOne = (Model) => async (req, res, next) => {
);
}

if (
oldDoc &&
oldDoc.image &&
oldDoc.image !== doc.image &&
!(
oldDoc.image.endsWith("default.jpg") ||
oldDoc.image.endsWith("default.png") ||
oldDoc.image.endsWith("default.jpeg")
)
) {
// Delete local image on /public/images/{Model.modelName.toLowerCase()}s/{doc.image}
const imagePath = path.join(__dirname, `../public${oldDoc.image}`);

fs.unlink(imagePath, (err) => {
if (err) {
console.error(err);
}
});
}

res.status(200).json({
status: "success",
data: doc,
Expand Down Expand Up @@ -137,13 +159,11 @@ exports.deleteOne = (Model) => async (req, res, next) => {
)
) {
// Delete local image on /public/images/{Model.modelName.toLowerCase()}s/{doc.image}

const imagePath = path.join(__dirname, `../public${doc.image}}`);
const imagePath = path.join(__dirname, `../public${doc.image}`);

fs.unlink(imagePath, (err) => {
if (err) {
console.error(err);
return;
}
});
}
Expand Down
20 changes: 20 additions & 0 deletions backend/src/controllers/user.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,26 @@ exports.resizeUserPhoto = async (req, res, next) => {
exports.updateMe = async (req, res, next) => {
if (req.file) req.body.image = req.file.filename;

// Check allowed fields (form data validation with zod is not working)
const allowedFields = ["name", "phone", "image"];
const receivedFields = Object.keys(req.body);
const notAllowedFields = receivedFields.filter(
(field) => !allowedFields.includes(field)
);
if (notAllowedFields.length > 0) {
throw new AppError(
400,
"BAD_REQUEST",
`Không thể cập nhật trường ${notAllowedFields.join(", ")}.`,
Object.assign(
{},
...notAllowedFields.map((field) => ({
[field]: `Không thể cập nhật trường ${field}.`,
}))
)
);
}

// Update user document
const user = await User.findByIdAndUpdate(req.user.id, req.body, {
new: true,
Expand Down
Binary file removed backend/src/public/images/products/banh-mi-pate.jpg
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 0 additions & 1 deletion backend/src/routes/auth.route.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ router.use(authController.protect);
router.get("/me", userController.getMe, userController.getUser);
router.patch(
"/me",
validateRequest(updateMeSchema),
userController.uploadUserPhoto,
userController.resizeUserPhoto,
userController.updateMe
Expand Down
2 changes: 2 additions & 0 deletions backend/src/routes/user.route.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const express = require("express");
const userController = require("../controllers/user.controller");
const authController = require("../controllers/auth.controller");
const multerUpload = require("../utils/multerUpload");
const sharp = require("sharp");

const orderRouter = require("./order.route");
const paymentRouter = require("./payment.route");
Expand Down

0 comments on commit 5da40fb

Please sign in to comment.