import {body, param} from "express-validator"; import {getClient} from "../utils/database.js"; import jwt from "jsonwebtoken"; export const Comment = { id: param("id").notEmpty().isNumeric().trim(), content: body("content").notEmpty().trim(), video: body("video").notEmpty().isNumeric().trim(), } export const CommentCreate = { content: body("content").notEmpty().trim(), video: body("video").notEmpty().isNumeric().trim(), } export async function doCommentExists(req, res, next) { const id = req.params.id; const logger = req.body.logger; const client = await getClient(); try { const query = `SELECT * FROM comments WHERE id = $1`; const result = await client.query(query, [id]); if (result.rows.length === 0) { logger.write("comment not found", 404); res.status(404).json({error: "comment not found"}); return } next() } finally { client.release(); } } export async function isAuthor(req, res, next) { const id = req.params.id; const token = req.headers.authorization.split(" ")[1]; const claims = jwt.decode(token); const userId = claims.id; const logger = req.body.logger; const client = await getClient(); try { const query = `SELECT * FROM comments WHERE id = $1`; const result = await client.query(query, [id]); if (userId !== result.rows[0].author) { logger.write("is not author of the comment", 403); res.status(403).json({error: "You do not have permission"}); return } next() } finally { client.release(); } }