Added security policies to all endpoints and implemented file upload feature on posts
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
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 {
|
||||
handlePostUpload,
|
||||
imageLinkForFile,
|
||||
removeUploadedFile,
|
||||
} = require("../../middleware/post_upload");
|
||||
|
||||
async function create_post(req, res) {
|
||||
try {
|
||||
const { title, text } = req.body;
|
||||
const author_id = req.user.id;
|
||||
if (!title || !text) {
|
||||
await removeUploadedFile(req.file);
|
||||
return res.status(400).send("Title or text was not provided");
|
||||
} else {
|
||||
const imageLink = imageLinkForFile(req.file);
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
"INSERT INTO posts (title, text, author_id, image_link) VALUES ($1, $2, $3, $4) RETURNING id, title, text, author_id, image_link",
|
||||
[title, text, author_id, imageLink],
|
||||
);
|
||||
res.status(201).json(rows[0]);
|
||||
} catch (err) {
|
||||
await removeUploadedFile(req.file);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
} 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("Data was not pushed, request failed");
|
||||
}
|
||||
}
|
||||
|
||||
router.post(
|
||||
"/",
|
||||
authenticateToken,
|
||||
handlePostUpload,
|
||||
strictInput({ body: ["title", "text"], cleanupUploadedFile: true }),
|
||||
create_post,
|
||||
);
|
||||
module.exports = router;
|
||||
Reference in New Issue
Block a user