Added liking and security measures

This commit is contained in:
Sven laptop
2026-07-31 15:11:57 +02:00
parent 494b583cbc
commit ab73eecfec
25 changed files with 1095 additions and 91 deletions
+72
View File
@@ -0,0 +1,72 @@
const express = require("express");
const router = express.Router();
const pool = require("../../db");
const { strictInput } = require("../../middleware/strict_input");
const { authenticateToken } = require("../../middleware/authenticate_token");
const { areFriends } = require("../relations/friend_graph");
const { likePost, unlikePost } = require("./post_graph");
async function getVisiblePostId(req) {
const postId = Number(req.query.id);
if (!Number.isInteger(postId) || postId <= 0) {
return { error: 400 };
}
const { rows } = await pool.query(
`SELECT p.id, p.author_id, people.private AS author_private
FROM posts p
LEFT JOIN people ON people.id = p.author_id
WHERE p.id = $1 AND p.active = true`,
[postId],
);
if (rows.length === 0) {
return { error: 404 };
}
const post = rows[0];
if (
post.author_private &&
Number(post.author_id) !== req.user.id &&
!(await areFriends(req.user.id, post.author_id))
) {
return { error: 404 };
}
return { postId: Number(post.id) };
}
async function handleLike(req, res, like) {
try {
const { postId, error } = await getVisiblePostId(req);
if (error === 400) return res.status(400).send("Invalid post id");
if (error === 404) return res.status(404).send("Post not found");
if (like) {
await likePost(req.user.id, postId);
return res.status(200).json({ message: "Post liked" });
}
await unlikePost(req.user.id, postId);
return res.status(200).json({ message: "Post unliked" });
} catch (err) {
console.error(like ? "like failed" : "unlike failed", {
message: err.message,
code: err.code,
detail: err.detail,
hint: err.hint,
});
return res.status(500).send("Request could not be completed");
}
}
router.post(
"/",
authenticateToken,
strictInput({ query: ["id"] }),
(req, res) => handleLike(req, res, true),
);
router.delete(
"/",
authenticateToken,
strictInput({ query: ["id"] }),
(req, res) => handleLike(req, res, false),
);
module.exports = router;