fix: fixed message deleting

This commit is contained in:
Lukian 2025-04-03 12:39:33 +02:00
parent 15b2c5df19
commit 2f54840785
2 changed files with 29 additions and 3 deletions

View file

@ -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' });
}

View file

@ -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
};