Added liking and security measures
This commit is contained in:
@@ -18,6 +18,9 @@ const {
|
||||
removeUploadedProfileFile,
|
||||
uploadDirectory,
|
||||
} = require("../../middleware/post_upload");
|
||||
const { areFriends } = require("../relations/friend_graph");
|
||||
const { authLimiter } = require("../../middleware/rate_limit");
|
||||
const { deletePostsByAuthor } = require("../posts/post_graph");
|
||||
|
||||
const scrypt = promisify(crypto.scrypt);
|
||||
|
||||
@@ -49,16 +52,43 @@ function resolveProfileId(req) {
|
||||
return id;
|
||||
}
|
||||
|
||||
function isPositiveInteger(value) {
|
||||
const id = Number(value);
|
||||
return Number.isInteger(id) && id > 0;
|
||||
}
|
||||
|
||||
function limitedProfile(profile) {
|
||||
return {
|
||||
id: profile.id,
|
||||
name: profile.name,
|
||||
username: profile.username,
|
||||
};
|
||||
}
|
||||
|
||||
async function getProfile(req, res) {
|
||||
const id = resolveProfileId(req);
|
||||
|
||||
if (id !== req.user.id && !isPositiveInteger(id)) {
|
||||
return res.status(400).send("Invalid profile id");
|
||||
}
|
||||
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
"SELECT id, name, username, profile_link FROM people WHERE id = $1",
|
||||
"SELECT id, name, username, profile_link, private FROM people WHERE id = $1",
|
||||
[id],
|
||||
);
|
||||
if (rows.length === 0) return res.status(404).send("Profile not found");
|
||||
return res.status(200).json(rows[0]);
|
||||
|
||||
const profile = rows[0];
|
||||
const targetId = Number(id);
|
||||
if (
|
||||
profile.private &&
|
||||
targetId !== req.user.id &&
|
||||
!(await areFriends(req.user.id, targetId))
|
||||
) {
|
||||
return res.status(200).json(limitedProfile(profile));
|
||||
}
|
||||
return res.status(200).json(profile);
|
||||
} catch (err) {
|
||||
console.error("profile query failed", {
|
||||
message: err.message,
|
||||
@@ -132,6 +162,7 @@ async function updateProfile(req, res) {
|
||||
if (update.name !== undefined) addField("name", update.name);
|
||||
if (update.username !== undefined) addField("username", update.username);
|
||||
if (update.email !== undefined) addField("email", update.email);
|
||||
if (update.private !== undefined) addField("private", update.private);
|
||||
if (update.password !== undefined) {
|
||||
addField("password", await hashPassword(update.password));
|
||||
}
|
||||
@@ -142,7 +173,7 @@ async function updateProfile(req, res) {
|
||||
let rows;
|
||||
try {
|
||||
({ rows } = await pool.query(
|
||||
`UPDATE people SET ${fields.join(", ")} WHERE id = $${values.length} RETURNING id, name, username, profile_link`,
|
||||
`UPDATE people SET ${fields.join(", ")} WHERE id = $${values.length} RETURNING id, name, username, profile_link, private`,
|
||||
values,
|
||||
));
|
||||
} catch (err) {
|
||||
@@ -156,6 +187,11 @@ async function updateProfile(req, res) {
|
||||
});
|
||||
}
|
||||
|
||||
if (update.password !== undefined) {
|
||||
await pool.query("UPDATE people SET token_version = token_version + 1 WHERE id = $1", [req.user.id]);
|
||||
await pool.query("DELETE FROM sessions WHERE user_id = $1", [req.user.id]);
|
||||
}
|
||||
|
||||
if (update.name !== undefined || update.username !== undefined) {
|
||||
await driver.executeQuery(
|
||||
"MATCH (p:Person {db_id: $db_id}) SET p.name = $name, p.username = $username",
|
||||
@@ -207,9 +243,11 @@ async function deleteAccount(req, res) {
|
||||
}
|
||||
await removeImageLink(existing.rows[0].profile_link);
|
||||
|
||||
await pool.query("DELETE FROM posts WHERE author_id = $1", [req.user.id]);
|
||||
await pool.query("DELETE FROM sessions WHERE user_id = $1", [req.user.id]);
|
||||
await pool.query("UPDATE posts SET active = false WHERE author_id = $1", [req.user.id]);
|
||||
await pool.query("DELETE FROM people WHERE id = $1", [req.user.id]);
|
||||
|
||||
await deletePostsByAuthor(req.user.id);
|
||||
await driver.executeQuery(
|
||||
"MATCH (p:Person {db_id: $db_id}) DETACH DELETE p",
|
||||
{ db_id: req.user.id },
|
||||
@@ -237,12 +275,36 @@ async function deleteAccount(req, res) {
|
||||
router.get(
|
||||
"/image/:filename",
|
||||
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 id, private FROM people WHERE profile_link = $1",
|
||||
[`/profiles/image/${filename}`],
|
||||
);
|
||||
if (rows.length === 0) return res.status(404).send("Image not found");
|
||||
const profile = rows[0];
|
||||
if (
|
||||
profile.private &&
|
||||
Number(profile.id) !== req.user.id &&
|
||||
!(await areFriends(req.user.id, profile.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("profile 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");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -252,7 +314,7 @@ router.put(
|
||||
"/me",
|
||||
handleProfileUpload,
|
||||
strictInput({
|
||||
body: ["name", "username", "email", "password", "current_password", "remove_image"],
|
||||
body: ["name", "username", "email", "password", "current_password", "remove_image", "private"],
|
||||
cleanupUploadedFile: true,
|
||||
}),
|
||||
sanitizeProfileUpdate,
|
||||
@@ -260,6 +322,7 @@ router.put(
|
||||
);
|
||||
router.delete(
|
||||
"/me",
|
||||
authLimiter,
|
||||
strictInput({ body: ["password"] }),
|
||||
sanitizeAccountDelete,
|
||||
deleteAccount,
|
||||
|
||||
@@ -9,15 +9,20 @@ const { signToken } = require('../../middleware/authenticate_token');
|
||||
|
||||
const scrypt = promisify(crypto.scrypt);
|
||||
|
||||
// Fixed salt for unknown emails: the scrypt work is still performed so the
|
||||
// response time does not reveal whether the email address exists.
|
||||
const DUMMY_SALT = '00000000000000000000000000000000';
|
||||
|
||||
async function login(req, res) {
|
||||
try {
|
||||
const { email, password } = req.loginInput;
|
||||
const { rows } = await pool.query(
|
||||
'SELECT id, password FROM people WHERE email = $1',
|
||||
'SELECT id, password, token_version FROM people WHERE email = $1',
|
||||
[email]
|
||||
);
|
||||
|
||||
if (rows.length === 0) {
|
||||
await scrypt(password, DUMMY_SALT, 64);
|
||||
res.status(401).send('Invalid email or password');
|
||||
return;
|
||||
}
|
||||
@@ -34,7 +39,17 @@ async function login(req, res) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { token, expiresAt } = signToken(rows[0].id);
|
||||
const sessionId = crypto.randomUUID();
|
||||
const deviceName = (req.headers['user-agent'] || 'unknown').slice(0, 255);
|
||||
await pool.query(
|
||||
'INSERT INTO sessions (id, user_id, device_name) VALUES ($1, $2, $3)',
|
||||
[sessionId, rows[0].id, deviceName],
|
||||
);
|
||||
|
||||
const { token, expiresAt } = signToken(rows[0].id, {
|
||||
jti: sessionId,
|
||||
tokenVersion: rows[0].token_version,
|
||||
});
|
||||
res.cookie('fc_session_token', token, {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
const express = require("express");
|
||||
const router = express.Router();
|
||||
const pool = require("../../db");
|
||||
const { strictInput } = require("../../middleware/strict_input");
|
||||
|
||||
async function logout(req, res) {
|
||||
try {
|
||||
if (req.user.session_id) {
|
||||
await pool.query(
|
||||
"DELETE FROM sessions WHERE id = $1 AND user_id = $2",
|
||||
[req.user.session_id, req.user.id],
|
||||
);
|
||||
}
|
||||
res.clearCookie("fc_session_token", {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: "Strict",
|
||||
path: "/",
|
||||
});
|
||||
return res.status(200).json({ message: "Logged out" });
|
||||
} catch (err) {
|
||||
console.error("logout failed", { message: err.message, code: err.code });
|
||||
return res.status(500).send("Logout failed, request could not be completed");
|
||||
}
|
||||
}
|
||||
|
||||
router.post("/", strictInput(), logout);
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,79 @@
|
||||
const express = require("express");
|
||||
const router = express.Router();
|
||||
const pool = require("../../db");
|
||||
const { strictInput } = require("../../middleware/strict_input");
|
||||
|
||||
async function listSessions(req, res) {
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT id, device_name, created_at, last_used_at
|
||||
FROM sessions
|
||||
WHERE user_id = $1
|
||||
ORDER BY last_used_at DESC`,
|
||||
[req.user.id],
|
||||
);
|
||||
const sessions = rows.map((s) => ({
|
||||
...s,
|
||||
current: s.id === req.user.session_id,
|
||||
}));
|
||||
return res.status(200).json(sessions);
|
||||
} catch (err) {
|
||||
console.error("list sessions failed", {
|
||||
message: err.message,
|
||||
code: err.code,
|
||||
});
|
||||
return res.status(500).send("Sessions could not be retrieved, request failed");
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSession(req, res) {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
const uuidPattern =
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
if (!uuidPattern.test(id)) {
|
||||
return res.status(400).send("Invalid session id");
|
||||
}
|
||||
const result = await pool.query(
|
||||
"DELETE FROM sessions WHERE id = $1 AND user_id = $2 RETURNING id",
|
||||
[id, req.user.id],
|
||||
);
|
||||
if (result.rowCount === 0) {
|
||||
return res.status(404).send("Session not found or does not belong to you");
|
||||
}
|
||||
return res.status(200).json({ message: "Session deleted" });
|
||||
} catch (err) {
|
||||
console.error("delete session failed", {
|
||||
message: err.message,
|
||||
code: err.code,
|
||||
});
|
||||
return res.status(500).send("Session could not be deleted, request failed");
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteOtherSessions(req, res) {
|
||||
if (!req.user.session_id) {
|
||||
return res
|
||||
.status(400)
|
||||
.send("Current session could not be identified, please log in again");
|
||||
}
|
||||
try {
|
||||
await pool.query(
|
||||
"DELETE FROM sessions WHERE user_id = $1 AND id != $2",
|
||||
[req.user.id, req.user.session_id],
|
||||
);
|
||||
return res.status(200).json({ message: "Other sessions deleted" });
|
||||
} catch (err) {
|
||||
console.error("delete other sessions failed", {
|
||||
message: err.message,
|
||||
code: err.code,
|
||||
});
|
||||
return res.status(500).send("Sessions could not be deleted, request failed");
|
||||
}
|
||||
}
|
||||
|
||||
router.get("/", strictInput(), listSessions);
|
||||
router.delete("/", strictInput(), deleteOtherSessions);
|
||||
router.delete("/:id", strictInput(), deleteSession);
|
||||
|
||||
module.exports = router;
|
||||
@@ -62,6 +62,17 @@ async function create_people(req, res) {
|
||||
const person = req.person;
|
||||
let db_id;
|
||||
|
||||
const existing = await pool
|
||||
.query('SELECT 1 FROM people WHERE username = $1 OR email = $2 LIMIT 1', [
|
||||
person.username,
|
||||
person.email,
|
||||
])
|
||||
.catch(() => null);
|
||||
if (existing && existing.rowCount > 0) {
|
||||
res.status(409).send('Username or email is already in use');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
db_id = await insert_db(
|
||||
person.name,
|
||||
@@ -71,6 +82,10 @@ async function create_people(req, res) {
|
||||
);
|
||||
}
|
||||
catch (err) {
|
||||
if (err.code === '23505') {
|
||||
res.status(409).send('Username or email is already in use');
|
||||
return;
|
||||
}
|
||||
res.status(500).send('Data was not pushed to database, request failed');
|
||||
return;
|
||||
}
|
||||
@@ -80,6 +95,9 @@ async function create_people(req, res) {
|
||||
res.status(201).json({ id: db_id });
|
||||
}
|
||||
catch (err) {
|
||||
// Compensate the SQL insert so the user does not exist in one database
|
||||
// but not the other.
|
||||
await pool.query('DELETE FROM people WHERE id = $1', [db_id]).catch(() => {});
|
||||
res.status(500).send('Data was not pushed to graph database, request failed');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
@@ -1,32 +0,0 @@
|
||||
const express = require("express");
|
||||
const router = express.Router();
|
||||
var driver = require("../../graph_db");
|
||||
const { strictInput } = require('../../middleware/strict_input');
|
||||
|
||||
async function create_friendship(req, res) {
|
||||
try {
|
||||
const me = req.query.me;
|
||||
const them = req.query.them;
|
||||
if (String(req.user.id) !== String(me)) {
|
||||
return res.status(403).send("You can only create relationships as yourself");
|
||||
}
|
||||
const { records } = await driver.executeQuery(
|
||||
"MATCH (m:Person {db_id: $me}) MATCH (t:Person {db_id: $them}) CREATE (m)-[:FRIENDS_WITH]-> (t) CREATE (t)-[:FRIENDS_WITH]-> (m)",
|
||||
{ me: me, them: them },
|
||||
{ database: process.env.GRAPH_DB_NAME },
|
||||
);
|
||||
res.status(200).send("Relationship has been created");
|
||||
} catch (err) {
|
||||
console.error("database query failed", {
|
||||
message: err.message,
|
||||
code: err.code,
|
||||
detail: err.detail,
|
||||
hint: err.hint,
|
||||
stack: err.stack,
|
||||
});
|
||||
res.status(500).send("Relationship was not created, request failed");
|
||||
}
|
||||
}
|
||||
|
||||
router.post("/", strictInput({ query: ['me', 'them'] }), create_friendship);
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,241 @@
|
||||
const express = require("express");
|
||||
const router = express.Router();
|
||||
const pool = require("../../db");
|
||||
const driver = require("../../graph_db");
|
||||
const { strictInput } = require("../../middleware/strict_input");
|
||||
const { authenticateToken } = require("../../middleware/authenticate_token");
|
||||
const { graphIdToNumber } = require("./friend_graph");
|
||||
|
||||
const GRAPH = { database: process.env.GRAPH_DB_NAME };
|
||||
|
||||
function validId(value) {
|
||||
return Number.isInteger(value) && value > 0;
|
||||
}
|
||||
|
||||
async function personIdsFromGraph(records) {
|
||||
return records.map((record) => graphIdToNumber(record.get("id")));
|
||||
}
|
||||
|
||||
async function personDetails(ids) {
|
||||
if (ids.length === 0) return [];
|
||||
const { rows } = await pool.query(
|
||||
"SELECT id, name, username, profile_link, private FROM people WHERE id = ANY($1) ORDER BY name",
|
||||
[ids],
|
||||
);
|
||||
return rows;
|
||||
}
|
||||
|
||||
async function sendRequest(req, res) {
|
||||
const me = Number(req.user.id);
|
||||
const to = Number(req.query.to);
|
||||
if (!validId(to)) {
|
||||
return res.status(400).send("Invalid user id");
|
||||
}
|
||||
if (me === to) {
|
||||
return res.status(400).send("You cannot send a friend request to yourself");
|
||||
}
|
||||
|
||||
try {
|
||||
const target = await pool.query("SELECT id FROM people WHERE id = $1", [to]);
|
||||
if (target.rowCount === 0) {
|
||||
return res.status(404).send("User not found");
|
||||
}
|
||||
|
||||
const result = await driver.executeQuery(
|
||||
`MATCH (me:Person {db_id: $me}), (them:Person {db_id: $them})
|
||||
WHERE NOT EXISTS((me)-[:FRIENDS_WITH]-(them))
|
||||
AND NOT EXISTS((me)-[:REQUESTED]->(them))
|
||||
AND NOT EXISTS((them)-[:REQUESTED]->(me))
|
||||
CREATE (me)-[:REQUESTED {created_at: datetime()}]->(them)
|
||||
RETURN me`,
|
||||
{ me, them: to },
|
||||
GRAPH,
|
||||
);
|
||||
if (result.records.length === 0) {
|
||||
return res.status(409).send("Request already exists or you are already friends");
|
||||
}
|
||||
return res.status(200).json({ message: "Friend request sent" });
|
||||
} catch (err) {
|
||||
console.error("friend request failed", {
|
||||
message: err.message,
|
||||
code: err.code,
|
||||
detail: err.detail,
|
||||
hint: err.hint,
|
||||
});
|
||||
return res.status(500).send("Friend request was not sent, request failed");
|
||||
}
|
||||
}
|
||||
|
||||
async function acceptRequest(req, res) {
|
||||
const me = Number(req.user.id);
|
||||
const from = Number(req.query.from);
|
||||
if (!validId(from)) {
|
||||
return res.status(400).send("Invalid user id");
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await driver.executeQuery(
|
||||
`MATCH (f:Person {db_id: $from})-[r:REQUESTED]->(me:Person {db_id: $me})
|
||||
DELETE r
|
||||
CREATE (f)-[:FRIENDS_WITH]->(me)
|
||||
CREATE (me)-[:FRIENDS_WITH]->(f)
|
||||
RETURN f`,
|
||||
{ me, from },
|
||||
GRAPH,
|
||||
);
|
||||
if (result.records.length === 0) {
|
||||
return res.status(404).send("No pending friend request from this user");
|
||||
}
|
||||
return res.status(200).json({ message: "Friend request accepted" });
|
||||
} catch (err) {
|
||||
console.error("friend request accept failed", {
|
||||
message: err.message,
|
||||
code: err.code,
|
||||
detail: err.detail,
|
||||
hint: err.hint,
|
||||
});
|
||||
return res.status(500).send("Friend request was not accepted, request failed");
|
||||
}
|
||||
}
|
||||
|
||||
async function declineRequest(req, res) {
|
||||
const me = Number(req.user.id);
|
||||
const from = Number(req.query.from);
|
||||
if (!validId(from)) {
|
||||
return res.status(400).send("Invalid user id");
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await driver.executeQuery(
|
||||
`MATCH (f:Person {db_id: $from})-[r:REQUESTED]->(me:Person {db_id: $me})
|
||||
DELETE r
|
||||
RETURN f`,
|
||||
{ me, from },
|
||||
GRAPH,
|
||||
);
|
||||
if (result.records.length === 0) {
|
||||
return res.status(404).send("No pending friend request from this user");
|
||||
}
|
||||
return res.status(200).json({ message: "Friend request declined" });
|
||||
} catch (err) {
|
||||
console.error("friend request decline failed", {
|
||||
message: err.message,
|
||||
code: err.code,
|
||||
detail: err.detail,
|
||||
hint: err.hint,
|
||||
});
|
||||
return res.status(500).send("Friend request was not declined, request failed");
|
||||
}
|
||||
}
|
||||
|
||||
async function cancelRequest(req, res) {
|
||||
const me = Number(req.user.id);
|
||||
const to = Number(req.query.to);
|
||||
if (!validId(to)) {
|
||||
return res.status(400).send("Invalid user id");
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await driver.executeQuery(
|
||||
`MATCH (me:Person {db_id: $me})-[r:REQUESTED]->(t:Person {db_id: $to})
|
||||
DELETE r
|
||||
RETURN t`,
|
||||
{ me, to },
|
||||
GRAPH,
|
||||
);
|
||||
if (result.records.length === 0) {
|
||||
return res.status(404).send("No pending friend request to this user");
|
||||
}
|
||||
return res.status(200).json({ message: "Friend request cancelled" });
|
||||
} catch (err) {
|
||||
console.error("friend request cancel failed", {
|
||||
message: err.message,
|
||||
code: err.code,
|
||||
detail: err.detail,
|
||||
hint: err.hint,
|
||||
});
|
||||
return res.status(500).send("Friend request was not cancelled, request failed");
|
||||
}
|
||||
}
|
||||
|
||||
async function listFriends(req, res) {
|
||||
try {
|
||||
const { records } = await driver.executeQuery(
|
||||
"MATCH (me:Person {db_id: $me})-[:FRIENDS_WITH]-(f:Person) RETURN f.db_id AS id",
|
||||
{ me: Number(req.user.id) },
|
||||
GRAPH,
|
||||
);
|
||||
const ids = await personIdsFromGraph(records);
|
||||
const friends = await personDetails(ids);
|
||||
return res.status(200).json(friends);
|
||||
} catch (err) {
|
||||
console.error("list friends failed", {
|
||||
message: err.message,
|
||||
code: err.code,
|
||||
detail: err.detail,
|
||||
hint: err.hint,
|
||||
});
|
||||
return res.status(500).send("Friends could not be retrieved, request failed");
|
||||
}
|
||||
}
|
||||
|
||||
async function listRequests(req, res) {
|
||||
try {
|
||||
const { records } = await driver.executeQuery(
|
||||
"MATCH (f:Person)-[:REQUESTED]->(me:Person {db_id: $me}) RETURN f.db_id AS id",
|
||||
{ me: Number(req.user.id) },
|
||||
GRAPH,
|
||||
);
|
||||
const ids = await personIdsFromGraph(records);
|
||||
const requesters = await personDetails(ids);
|
||||
return res.status(200).json(requesters);
|
||||
} catch (err) {
|
||||
console.error("list friend requests failed", {
|
||||
message: err.message,
|
||||
code: err.code,
|
||||
detail: err.detail,
|
||||
hint: err.hint,
|
||||
});
|
||||
return res.status(500).send("Friend requests could not be retrieved, request failed");
|
||||
}
|
||||
}
|
||||
|
||||
async function removeFriend(req, res) {
|
||||
const me = Number(req.user.id);
|
||||
const id = Number(req.query.id);
|
||||
if (!validId(id)) {
|
||||
return res.status(400).send("Invalid user id");
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await driver.executeQuery(
|
||||
`MATCH (me:Person {db_id: $me})-[r:FRIENDS_WITH]-(f:Person {db_id: $id})
|
||||
DELETE r
|
||||
RETURN f`,
|
||||
{ me, id },
|
||||
GRAPH,
|
||||
);
|
||||
if (result.records.length === 0) {
|
||||
return res.status(404).send("Friend not found or not in your friend list");
|
||||
}
|
||||
return res.status(200).json({ message: "Friend removed" });
|
||||
} catch (err) {
|
||||
console.error("friend removal failed", {
|
||||
message: err.message,
|
||||
code: err.code,
|
||||
detail: err.detail,
|
||||
hint: err.hint,
|
||||
});
|
||||
return res.status(500).send("Friend could not be removed, request failed");
|
||||
}
|
||||
}
|
||||
|
||||
router.get("/", authenticateToken, strictInput(), listFriends);
|
||||
router.get("/requests", authenticateToken, strictInput(), listRequests);
|
||||
router.post("/request", authenticateToken, strictInput({ query: ["to"] }), sendRequest);
|
||||
router.post("/accept", authenticateToken, strictInput({ query: ["from"] }), acceptRequest);
|
||||
router.post("/decline", authenticateToken, strictInput({ query: ["from"] }), declineRequest);
|
||||
router.post("/cancel", authenticateToken, strictInput({ query: ["to"] }), cancelRequest);
|
||||
router.delete("/remove", authenticateToken, strictInput({ query: ["id"] }), removeFriend);
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,39 @@
|
||||
const driver = require("../../graph_db");
|
||||
|
||||
function graphIdToNumber(value) {
|
||||
if (typeof value === "number") return value;
|
||||
if (value && typeof value.toNumber === "function") return value.toNumber();
|
||||
return Number(value);
|
||||
}
|
||||
|
||||
function graphParams(userId) {
|
||||
return { db_id: Number(userId) };
|
||||
}
|
||||
|
||||
async function getFriendIds(userId) {
|
||||
const { records } = await driver.executeQuery(
|
||||
"MATCH (me:Person {db_id: $db_id})-[:FRIENDS_WITH]-(f:Person) RETURN f.db_id AS id",
|
||||
graphParams(userId),
|
||||
{ database: process.env.GRAPH_DB_NAME },
|
||||
);
|
||||
return new Set(records.map((record) => graphIdToNumber(record.get("id"))));
|
||||
}
|
||||
|
||||
async function getFriendIdsAmong(userId, ids) {
|
||||
if (ids.length === 0) return new Set();
|
||||
const { records } = await driver.executeQuery(
|
||||
`MATCH (me:Person {db_id: $db_id})-[:FRIENDS_WITH]-(f:Person)
|
||||
WHERE f.db_id IN $ids
|
||||
RETURN f.db_id AS id`,
|
||||
{ ...graphParams(userId), ids: ids.map(Number) },
|
||||
{ database: process.env.GRAPH_DB_NAME },
|
||||
);
|
||||
return new Set(records.map((record) => graphIdToNumber(record.get("id"))));
|
||||
}
|
||||
|
||||
async function areFriends(userId, otherId) {
|
||||
const friendIds = await getFriendIdsAmong(userId, [otherId]);
|
||||
return friendIds.has(Number(otherId));
|
||||
}
|
||||
|
||||
module.exports = { getFriendIds, getFriendIdsAmong, areFriends, graphIdToNumber };
|
||||
Reference in New Issue
Block a user