diff --git a/back/api/channels.js b/back/api/channels.js index 1b3e511..c5d6a1d 100644 --- a/back/api/channels.js +++ b/back/api/channels.js @@ -1,6 +1,6 @@ const express = require('express'); const jwt = require('jsonwebtoken'); -const { getConnection, getUser, getChannels, getChannel, addChannel, getMessages, addMessage, deleteMessage, getLastMessages } = require('../libs/mysql'); +const { getConnection, getChannels, getChannel, addChannel, getMessages, getMessage, addMessage, deleteMessage, getLastMessages } = require('../libs/mysql'); const { checkAuth } = require('../libs/middlewares'); const router = express.Router(); @@ -60,7 +60,7 @@ router.post('/:name/messages/send', async (req, res) => { res.send({ message: 'Message sent' }); }); -router.use('/:name/messages', checkAuth); +router.use('/:name/messages/delete', checkAuth); router.post('/:name/messages/delete', async (req, res) => { const { message_id } = req.body; const name = req.params.name; @@ -72,13 +72,19 @@ router.post('/:name/messages/delete', async (req, res) => { const connection = await getConnection(); + const message = await getMessage(connection, message_id); + if (!message[0]) { + connection.end(); + return res.status(400).send({ error: 'No message found' }); + } + const channel = await getChannel(connection, name); if (!channel[0]) { connection.end(); return res.status(400).send({ error: 'No channel found' }); } - if (user.id !== channel[0].owner_id && user.id !== message_id && user.admin !== 1) { + if (user.id !== channel[0].owner_id && user.id !== message.user_id && user.admin !== 1) { connection.end(); return res.status(401).send({ error: 'Unauthorized' }); } diff --git a/back/libs/mysql.js b/back/libs/mysql.js index 16a3262..b6d67e6 100644 --- a/back/libs/mysql.js +++ b/back/libs/mysql.js @@ -159,6 +159,25 @@ function getLastMessages(connection) { }); } +function getMessage(connection, message_id) { + return new Promise((resolve, reject) => { + connection.query( + `SELECT messages.id, user_id, username, content, date, channels.name AS channel_name + FROM messages + JOIN users ON messages.user_id = users.id + JOIN channels ON messages.channel_id = channels.id + WHERE messages.id = ?`, + [message_id], // Use parameterized query + (error, result) => { + if (error) { + reject(new Error(error)); + } + resolve(result); + } + ); + }); +} + function addMessage(connection, channel_id, user_id, message) { return new Promise((resolve, reject) => { connection.query( @@ -200,6 +219,7 @@ module.exports = { addChannel, getMessages, getLastMessages, + getMessage, addMessage, deleteMessage };