Added liking and security measures
This commit is contained in:
@@ -8,6 +8,7 @@ const {
|
||||
imageLinkForFile,
|
||||
removeUploadedFile,
|
||||
} = require("../../middleware/post_upload");
|
||||
const driver = require("../../graph_db");
|
||||
|
||||
async function create_post(req, res) {
|
||||
try {
|
||||
@@ -23,7 +24,22 @@ async function create_post(req, res) {
|
||||
"WITH created AS (INSERT INTO posts (title, text, author_id, image_link) VALUES ($1, $2, $3, $4) RETURNING id, title, text, author_id, image_link, created_at) SELECT created.*, people.username AS author_username FROM created LEFT JOIN people ON people.id = created.author_id",
|
||||
[title, text, author_id, imageLink],
|
||||
);
|
||||
res.status(201).json(rows[0]);
|
||||
const post = rows[0];
|
||||
try {
|
||||
await driver.executeQuery(
|
||||
"CREATE (p:Post {db_id: $db_id, author_id: $author_id, created_at: datetime()})",
|
||||
{ db_id: Number(post.id), author_id: Number(post.author_id) },
|
||||
{ database: process.env.GRAPH_DB_NAME },
|
||||
);
|
||||
} catch (graphErr) {
|
||||
await pool.query("DELETE FROM posts WHERE id = $1", [post.id]).catch(() => {});
|
||||
throw graphErr;
|
||||
}
|
||||
res.status(201).json({
|
||||
...post,
|
||||
like_count: 0,
|
||||
liked_by_me: false,
|
||||
});
|
||||
} catch (err) {
|
||||
await removeUploadedFile(req.file);
|
||||
throw err;
|
||||
|
||||
@@ -4,18 +4,20 @@ const pool = require("../../db");
|
||||
const { strictInput } = require("../../middleware/strict_input");
|
||||
const { authenticateToken } = require("../../middleware/authenticate_token");
|
||||
const { removeImageLink } = require("../../middleware/post_upload");
|
||||
const { deletePostNode } = require("./post_graph");
|
||||
|
||||
async function delete_post(req, res) {
|
||||
try {
|
||||
const id = req.query.id;
|
||||
const result = await pool.query(
|
||||
"DELETE FROM posts WHERE id = $1 AND author_id = $2 RETURNING id, image_link",
|
||||
"UPDATE posts SET active = false WHERE id = $1 AND author_id = $2 RETURNING id, image_link",
|
||||
[id, req.user.id],
|
||||
);
|
||||
if (result.rowCount === 0) {
|
||||
return res.status(404).send("Post not found or does not belong to you");
|
||||
}
|
||||
await removeImageLink(result.rows[0].image_link);
|
||||
await deletePostNode(result.rows[0].id);
|
||||
res.status(200).json({
|
||||
message: "Post Deleted",
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@ const {
|
||||
removeImageLink,
|
||||
removeUploadedFile,
|
||||
} = require("../../middleware/post_upload");
|
||||
const { likeDataForPosts } = require("./post_graph");
|
||||
|
||||
async function editPost(req, res) {
|
||||
const id = req.query.id;
|
||||
@@ -33,7 +34,7 @@ async function editPost(req, res) {
|
||||
|
||||
try {
|
||||
const existing = await pool.query(
|
||||
"SELECT id, image_link FROM posts WHERE id = $1 AND author_id = $2",
|
||||
"SELECT id, image_link FROM posts WHERE id = $1 AND author_id = $2 AND active = true",
|
||||
[id, req.user.id],
|
||||
);
|
||||
if (existing.rowCount === 0) {
|
||||
@@ -53,12 +54,13 @@ async function editPost(req, res) {
|
||||
if (text !== undefined) addField("text", text);
|
||||
if (req.file) addField("image_link", imageLinkForFile(req.file));
|
||||
if (removeImage) addField("image_link", null);
|
||||
fields.push("edited_last = NOW()");
|
||||
values.push(id, req.user.id);
|
||||
|
||||
let updated;
|
||||
try {
|
||||
updated = await pool.query(
|
||||
`WITH updated AS (UPDATE posts SET ${fields.join(", ")} WHERE id = $${values.length - 1} AND author_id = $${values.length} RETURNING id, title, text, author_id, image_link, created_at) SELECT updated.*, people.username AS author_username FROM updated LEFT JOIN people ON people.id = updated.author_id`,
|
||||
`WITH updated AS (UPDATE posts SET ${fields.join(", ")} WHERE id = $${values.length - 1} AND author_id = $${values.length} RETURNING id, title, text, author_id, image_link, created_at, edited_last) SELECT updated.*, people.username AS author_username FROM updated LEFT JOIN people ON people.id = updated.author_id`,
|
||||
values,
|
||||
);
|
||||
} catch (err) {
|
||||
@@ -71,7 +73,14 @@ async function editPost(req, res) {
|
||||
console.error("old post image could not be removed", { message: err.message });
|
||||
});
|
||||
}
|
||||
return res.status(200).json(updated.rows[0]);
|
||||
const likeData = (await likeDataForPosts(req.user.id, [updated.rows[0].id])).get(
|
||||
Number(updated.rows[0].id),
|
||||
) ?? { like_count: 0, liked_by_me: false };
|
||||
return res.status(200).json({
|
||||
...updated.rows[0],
|
||||
like_count: likeData.like_count,
|
||||
liked_by_me: likeData.liked_by_me,
|
||||
});
|
||||
} catch (err) {
|
||||
await removeUploadedFile(req.file);
|
||||
console.error("database query failed", {
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
const express = require("express");
|
||||
const router = express.Router();
|
||||
const pool = require("../../db");
|
||||
const { strictInput } = require("../../middleware/strict_input");
|
||||
const { areFriends } = require("../relations/friend_graph");
|
||||
const { likeDataForPosts } = require("./post_graph");
|
||||
|
||||
async function getPostDetail(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const postId = Number(id);
|
||||
if (!Number.isInteger(postId) || postId <= 0) {
|
||||
return res.status(400).send("Invalid post id");
|
||||
}
|
||||
const { rows } = await pool.query(
|
||||
`SELECT p.id, p.title, p.text, p.author_id, people.username AS author_username, p.image_link, p.created_at, 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 res.status(404).send("Post not found");
|
||||
}
|
||||
const post = rows[0];
|
||||
if (
|
||||
post.author_private &&
|
||||
Number(post.author_id) !== req.user.id &&
|
||||
!(await areFriends(req.user.id, post.author_id))
|
||||
) {
|
||||
return res.status(404).send("Post not found");
|
||||
}
|
||||
const { author_private, ...publicPost } = post;
|
||||
const likeData = (await likeDataForPosts(req.user.id, [post.id])).get(
|
||||
Number(post.id),
|
||||
) ?? { like_count: 0, liked_by_me: false };
|
||||
return res
|
||||
.status(200)
|
||||
.json({
|
||||
...publicPost,
|
||||
comments: [],
|
||||
like_count: likeData.like_count,
|
||||
liked_by_me: likeData.liked_by_me,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("post detail query failed", {
|
||||
message: err.message,
|
||||
code: err.code,
|
||||
detail: err.detail,
|
||||
hint: err.hint,
|
||||
});
|
||||
return res.status(500).send("Post could not be retrieved, request failed");
|
||||
}
|
||||
}
|
||||
|
||||
router.get("/:id", strictInput(), getPostDetail);
|
||||
|
||||
module.exports = router;
|
||||
+102
-11
@@ -4,16 +4,80 @@ const pool = require("../../db");
|
||||
const { strictInput } = require("../../middleware/strict_input");
|
||||
const { authenticateToken } = require("../../middleware/authenticate_token");
|
||||
const { uploadDirectory } = require("../../middleware/post_upload");
|
||||
const { getFriendIdsAmong, areFriends } = require("../relations/friend_graph");
|
||||
const { likeDataForPosts } = require("./post_graph");
|
||||
const path = require("path");
|
||||
|
||||
function parsePagination(req) {
|
||||
const { limit: limitRaw, offset: offsetRaw } = req.query;
|
||||
if (limitRaw === undefined && offsetRaw === undefined) {
|
||||
return { limit: 20, offset: 0 };
|
||||
}
|
||||
const limit = limitRaw === undefined ? 20 : Number(limitRaw);
|
||||
const offset = offsetRaw === undefined ? 0 : Number(offsetRaw);
|
||||
if (!Number.isInteger(limit) || limit < 1 || limit > 100) {
|
||||
return { error: "limit must be an integer between 1 and 100" };
|
||||
}
|
||||
if (!Number.isInteger(offset) || offset < 0) {
|
||||
return { error: "offset must be a non-negative integer" };
|
||||
}
|
||||
return { limit, offset };
|
||||
}
|
||||
|
||||
async function getPosts(req, res, ownOnly) {
|
||||
const pagination = parsePagination(req);
|
||||
if (pagination.error) return res.status(400).send(pagination.error);
|
||||
|
||||
try {
|
||||
const query = ownOnly
|
||||
? "SELECT p.id, p.title, p.text, p.author_id, people.username AS author_username, p.image_link, p.created_at FROM posts p LEFT JOIN people ON people.id = p.author_id WHERE p.author_id = $1"
|
||||
: "SELECT p.id, p.title, p.text, p.author_id, people.username AS author_username, p.image_link, p.created_at FROM posts p LEFT JOIN people ON people.id = p.author_id";
|
||||
const values = ownOnly ? [req.user.id] : [];
|
||||
const values = [];
|
||||
const conditions = ["p.active = true"];
|
||||
|
||||
if (ownOnly) {
|
||||
conditions.push(`p.author_id = $${values.length + 1}`);
|
||||
values.push(req.user.id);
|
||||
} else {
|
||||
const visible = [`people.private = false`, `p.author_id = $${values.length + 1}`];
|
||||
values.push(req.user.id);
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`SELECT DISTINCT p.author_id FROM posts p
|
||||
JOIN people ON people.id = p.author_id
|
||||
WHERE p.active = true AND people.private = true`,
|
||||
);
|
||||
const privateAuthorIds = rows.map((row) => Number(row.author_id));
|
||||
if (privateAuthorIds.length > 0) {
|
||||
const friendIds = await getFriendIdsAmong(req.user.id, privateAuthorIds);
|
||||
if (friendIds.size > 0) {
|
||||
visible.push(`p.author_id = ANY($${values.length + 1})`);
|
||||
values.push([...friendIds]);
|
||||
}
|
||||
}
|
||||
|
||||
conditions.push(`(${visible.join(" OR ")})`);
|
||||
}
|
||||
|
||||
const where = conditions.join(" AND ");
|
||||
const query = `SELECT p.id, p.title, p.text, p.author_id, people.username AS author_username, p.image_link, p.created_at
|
||||
FROM posts p
|
||||
LEFT JOIN people ON people.id = p.author_id
|
||||
WHERE ${where}
|
||||
ORDER BY p.created_at DESC
|
||||
LIMIT $${values.length + 1} OFFSET $${values.length + 2}`;
|
||||
values.push(pagination.limit, pagination.offset);
|
||||
|
||||
const { rows } = await pool.query(query, values);
|
||||
res.status(200).json(rows);
|
||||
|
||||
const likeData = await likeDataForPosts(
|
||||
req.user.id,
|
||||
rows.map((row) => row.id),
|
||||
);
|
||||
const posts = rows.map((row) => ({
|
||||
...row,
|
||||
like_count: likeData.get(Number(row.id))?.like_count ?? 0,
|
||||
liked_by_me: likeData.get(Number(row.id))?.liked_by_me ?? false,
|
||||
}));
|
||||
|
||||
res.status(200).json(posts);
|
||||
} catch (err) {
|
||||
console.error("database query failed", {
|
||||
message: err.message,
|
||||
@@ -30,26 +94,53 @@ router.get(
|
||||
"/image/:filename",
|
||||
authenticateToken,
|
||||
strictInput(),
|
||||
(req, res) => {
|
||||
async (req, res) => {
|
||||
const filename = path.basename(req.params.filename);
|
||||
if (filename !== req.params.filename) return res.status(404).end();
|
||||
res.sendFile(filename, { root: uploadDirectory }, (err) => {
|
||||
if (err && !res.headersSent) res.status(err.statusCode === 404 ? 404 : 500).end();
|
||||
});
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT p.author_id, people.private AS author_private
|
||||
FROM posts p
|
||||
LEFT JOIN people ON people.id = p.author_id
|
||||
WHERE p.image_link = $1 AND p.active = true`,
|
||||
[`/posts/image/${filename}`],
|
||||
);
|
||||
if (rows.length === 0) return res.status(404).send("Image not found");
|
||||
const post = rows[0];
|
||||
if (
|
||||
post.author_private &&
|
||||
Number(post.author_id) !== req.user.id &&
|
||||
!(await areFriends(req.user.id, post.author_id))
|
||||
) {
|
||||
return res.status(404).send("Image not found");
|
||||
}
|
||||
res.set("Cache-Control", "private, no-store");
|
||||
res.sendFile(filename, { root: uploadDirectory }, (err) => {
|
||||
if (err && !res.headersSent) res.status(err.statusCode === 404 ? 404 : 500).end();
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("post image query failed", {
|
||||
message: err.message,
|
||||
code: err.code,
|
||||
detail: err.detail,
|
||||
hint: err.hint,
|
||||
});
|
||||
return res.status(500).send("Image could not be retrieved, request failed");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
router.get(
|
||||
"/me",
|
||||
authenticateToken,
|
||||
strictInput(),
|
||||
strictInput({ query: ["limit", "offset"] }),
|
||||
(req, res) => getPosts(req, res, true),
|
||||
);
|
||||
|
||||
router.get(
|
||||
"/",
|
||||
authenticateToken,
|
||||
strictInput(),
|
||||
strictInput({ query: ["limit", "offset"] }),
|
||||
(req, res) => getPosts(req, res, false),
|
||||
);
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -0,0 +1,72 @@
|
||||
const driver = require("../../graph_db");
|
||||
const { graphIdToNumber } = require("../relations/friend_graph");
|
||||
|
||||
const GRAPH = { database: process.env.GRAPH_DB_NAME };
|
||||
|
||||
async function likePost(userId, postId) {
|
||||
const { records } = await driver.executeQuery(
|
||||
`MATCH (me:Person {db_id: $me})
|
||||
MERGE (p:Post {db_id: $postId})
|
||||
MERGE (me)-[l:LIKES]->(p)
|
||||
SET l.created_at = coalesce(l.created_at, datetime())
|
||||
RETURN me`,
|
||||
{ me: Number(userId), postId: Number(postId) },
|
||||
GRAPH,
|
||||
);
|
||||
return records.length > 0;
|
||||
}
|
||||
|
||||
async function unlikePost(userId, postId) {
|
||||
await driver.executeQuery(
|
||||
`MATCH (me:Person {db_id: $me})-[l:LIKES]->(p:Post {db_id: $postId})
|
||||
DELETE l`,
|
||||
{ me: Number(userId), postId: Number(postId) },
|
||||
GRAPH,
|
||||
);
|
||||
}
|
||||
|
||||
async function likeDataForPosts(userId, postIds) {
|
||||
const ids = postIds.map(Number);
|
||||
if (ids.length === 0) return new Map();
|
||||
const { records } = await driver.executeQuery(
|
||||
`MATCH (p:Post) WHERE p.db_id IN $ids
|
||||
OPTIONAL MATCH (p)<-[l:LIKES]-(:Person)
|
||||
WITH p, count(l) AS like_count
|
||||
OPTIONAL MATCH (me:Person {db_id: $me})-[:LIKES]->(p)
|
||||
RETURN p.db_id AS id, like_count, count(me) > 0 AS liked_by_me`,
|
||||
{ ids, me: Number(userId) },
|
||||
GRAPH,
|
||||
);
|
||||
const result = new Map();
|
||||
for (const record of records) {
|
||||
result.set(graphIdToNumber(record.get("id")), {
|
||||
like_count: Number(record.get("like_count")),
|
||||
liked_by_me: Boolean(record.get("liked_by_me")),
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function deletePostNode(postId) {
|
||||
await driver.executeQuery(
|
||||
"MATCH (p:Post {db_id: $postId}) DETACH DELETE p",
|
||||
{ postId: Number(postId) },
|
||||
GRAPH,
|
||||
);
|
||||
}
|
||||
|
||||
async function deletePostsByAuthor(authorId) {
|
||||
await driver.executeQuery(
|
||||
"MATCH (p:Post {author_id: $authorId}) DETACH DELETE p",
|
||||
{ authorId: Number(authorId) },
|
||||
GRAPH,
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
likePost,
|
||||
unlikePost,
|
||||
likeDataForPosts,
|
||||
deletePostNode,
|
||||
deletePostsByAuthor,
|
||||
};
|
||||
Reference in New Issue
Block a user