Added security policies to all endpoints and implemented file upload feature on posts

This commit is contained in:
Sven laptop
2026-07-24 23:25:31 +02:00
parent 9519a01ca0
commit 9e56f00c1e
19 changed files with 718 additions and 134 deletions
+56
View File
@@ -0,0 +1,56 @@
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 { uploadDirectory } = require("../../middleware/post_upload");
const path = require("path");
async function getPosts(req, res, ownOnly) {
try {
const query = ownOnly
? "SELECT id, title, text, author_id, image_link FROM posts WHERE author_id = $1"
: "SELECT id, title, text, author_id, image_link FROM posts";
const values = ownOnly ? [req.user.id] : [];
const { rows } = await pool.query(query, values);
res.status(200).json(rows);
} 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("Posts could not be retrieved, request failed");
}
}
router.get(
"/image/:filename",
authenticateToken,
strictInput(),
(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();
});
},
);
router.get(
"/me",
authenticateToken,
strictInput(),
(req, res) => getPosts(req, res, true),
);
router.get(
"/",
authenticateToken,
strictInput(),
(req, res) => getPosts(req, res, false),
);
module.exports = router;