Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
taugk committed Dec 15, 2023
1 parent 986633c commit c29e546
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 14 deletions.
27 changes: 19 additions & 8 deletions routes/authMiddleware.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const jwt = require("jsonwebtoken");
const { invalidatedTokens } = require("./auth");

const authenticateToken = (req, res, next) => {
const headerAuth = req.headers["authorization"];
Expand All @@ -8,16 +9,26 @@ const authenticateToken = (req, res, next) => {
return res.status(401).json({ message: "Unauthorized: Missing token" });
}

jwt.verify(token, process.env.SECRET_KEY, (err, user) => {
if (err) {
return res.status(403).json({ message: "Forbidden: Invalid token" });
try {
const decodedToken = jwt.verify(token, process.env.SECRET_KEY);
if (!decodedToken.id) {
return res
.status(401)
.json({ message: "Unauthorized: User not logged in" });
}

req.user = user;
if (invalidatedTokens && invalidatedTokens.has(token)) {
return res
.status(401)
.json({ message: "Unauthorized: Token invalidated" });
}

req.authData = decodedToken;
next();
});
} catch (error) {
console.error("Error decoding token:", error);
return res.status(401).json({ message: "Unauthorized: Invalid token" });
}
};

module.exports = {
authenticateToken,
};
module.exports = { authenticateToken };
11 changes: 5 additions & 6 deletions routes/postsRoutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -391,12 +391,15 @@ router.post(
categoryId,
isAvailable,
} = req.body;

try {
const tokenDecode = req.authData; // Use the decoded token from middleware
const categoryExists = await Category.findByPk(categoryId);

if (!categoryExists) {
return res.status(404).json({ message: "Category not found" });
}

let imageUrl = "";
if (req.file && req.file.cloudStoragePublicUrl) {
imageUrl = req.file.cloudStoragePublicUrl;
Expand Down Expand Up @@ -426,17 +429,13 @@ router.post(
userId: tokenDecode.id,
isAvailable: isAvailable || true,
});

res
.status(201)
.json({ message: "Post created successfully", post: newPost });
} catch (error) {
if (invalidatedTokens && invalidatedTokens.has(req.token)) {
return res
.status(401)
.json({ message: "Unauthorized: Token invalidated" });
}
console.error("Error creating post", error);
res.status(401).json({ message: "Unauthorized: Invalid token" });
res.status(500).json({ message: "Internal server error" });
}
}
);
Expand Down

0 comments on commit c29e546

Please sign in to comment.