import {body, param} from "express-validator"; import {getClient} from "../utils/database.js"; import jwt from "jsonwebtoken"; export const Channel = { id: param("id").notEmpty().isNumeric().trim(), name: body("name").notEmpty().isAlphanumeric("fr-FR", { ignore: " _-" }).trim(), description: body("description").optional({values: "falsy"}).isLength({ max: 500 }).trim(), owner: body("owner").notEmpty().isNumeric().trim().withMessage("bad owner"), } export const ChannelCreate = { name: body("name").notEmpty().isAlphanumeric("fr-FR", { ignore: " _-" }).trim(), description: body("description").optional({values: "falsy"}).isLength({ max: 500 }).trim(), owner: body("owner").notEmpty().isNumeric().trim(), } export async function doUserHaveChannel(req, res, next) { const client = await getClient(); const logger = req.body.logger; const query = `SELECT id FROM channels WHERE owner = ${req.body.owner}`; const result = await client.query(query); if (result.rows[0]) { logger.write("failed because user already has a channel", 400); res.status(400).json({error: "User already own a channel"}) } else { next() } } export async function doChannelNameExists(req, res, next) { const client = await getClient(); const logger = req.body.logger; const query = `SELECT * FROM channels WHERE name = '${req.body.name}'`; const result = await client.query(query); if (result.rows[0]) { logger.write("failed because channel name already exist", 400) res.status(400).json({error: "Channel name already used"}) } else { next() } } export async function doChannelExists(req, res, next) { const client = await getClient(); const logger = req.body.logger; const query = `SELECT id FROM channels WHERE id = '${req.params.id}'`; const result = await client.query(query); if (result.rows[0]) { next() } else { logger.write("failed to retrieve channel because it doesn't exist", 404); res.status(404).json({error: "Not Found"}) } } export async function doChannelExistBody(req, res, next) { const client = await getClient(); const logger = req.body.logger; const query = `SELECT id FROM channels WHERE id = ${req.body.channel}`; const result = await client.query(query); if (result.rows[0]) { next() } else { logger.write("failed to retrieve channel because it doesn't exist", 404); res.status(404).json({error: "Not Found"}) } } export async function isOwner(req, res, next) { const id = req.params.id; const token = req.headers.authorization.split(" ")[1]; const claims = jwt.decode(token); const logger = req.body.logger; const client = await getClient(); const query = `SELECT id, owner FROM channels WHERE id = ${id}`; const result = await client.query(query); const channel = result.rows[0]; if (channel.owner != claims.id) { logger.write("failed because user do not own the channel", 403); res.status(403).json({error: "You're not the owner of the channel"}) } else { next() } }