add: added channel admins

This commit is contained in:
Lukian 2025-03-24 20:59:33 +01:00
parent 5d13a51f8e
commit 7dea3612af
6 changed files with 79 additions and 9 deletions

View file

@ -1,6 +1,6 @@
const express = require('express');
const jwt = require('jsonwebtoken');
const { getConnection, getUser, getChannels, getChannel, addChannel, getMessages, addMessage } = require('../libs/mysql');
const { getConnection, getUser, getChannels, getChannel, addChannel, getMessages, addMessage, deleteMessage } = require('../libs/mysql');
const router = express.Router();
@ -59,6 +59,34 @@ router.post('/:name/messages/send', async (req, res) => {
res.send({ message: 'Message sent' });
});
router.post('/:name/messages/delete', async (req, res) => {
const { token, message_id } = req.body;
const name = req.params.name;
const connection = await getConnection();
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const user = await getUser(connection, decoded.id);
if (!user[0]) {
connection.end();
return res.status(401).send({ error: 'Invalid token' });
}
const channel = await getChannel(connection, name);
if (!channel[0]) {
connection.end();
return res.status(400).send({ error: 'No channel found' });
}
if (user[0].id !== channel[0].owner_id && user[0].id !== message_id) {
connection.end();
return res.status(401).send({ error: 'Unauthorized' });
}
await deleteMessage(connection, message_id);
connection.end();
res.send({ message: 'Message deleted' });
});
router.post('/add', async (req, res) => {
const { name, description, token } = req.body;
const connection = await getConnection();
@ -81,7 +109,7 @@ router.post('/add', async (req, res) => {
return res.status(400).send({ error: 'Invalid channel name' });
}
await addChannel(connection, name, description);
await addChannel(connection, name, description, user[0].id);
connection.end();
res.send({ message: 'Channel added' });
});

View file

@ -79,10 +79,10 @@ function getChannel(connection, name) {
});
}
function addChannel(connection, name, description) {
function addChannel(connection, name, description, owner_id) {
return new Promise((resolve, reject) => {
connection.query(
`INSERT INTO channels (name, description) VALUES ('${name}', '${description}')`,
`INSERT INTO channels (name, description, owner_id) VALUES ('${name}', '${description}', ${owner_id})`,
(error, result) => {
if (error) {
reject(new Error(error));
@ -121,6 +121,20 @@ function addMessage(connection, channel_id, user_id, message) {
});
}
function deleteMessage(connection, message_id) {
return new Promise((resolve, reject) => {
connection.query(
`DELETE FROM messages WHERE id = ${message_id}`,
(error, result) => {
if (error) {
reject(new Error(error));
}
resolve(result);
}
);
});
}
module.exports = {
getConnection,
getUser,
@ -130,5 +144,6 @@ module.exports = {
getChannel,
addChannel,
getMessages,
addMessage
addMessage,
deleteMessage
};

View file

@ -12,7 +12,7 @@ createRoot(document.getElementById('root')!).render(
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/:name" element={<Channel />} />
<Route path="/c/:name" element={<Channel />} />
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
<Route path="/create-channel" element={<CreateChannel />} />

View file

@ -1,6 +1,6 @@
import { useParams, Link } from "react-router-dom";
import React, { useEffect, useState } from "react";
import { Channel_type, Messages } from "../types";
import { Channel_type, Messages, User } from "../types";
import axios from "axios";
export default function Channel() {
@ -8,6 +8,7 @@ export default function Channel() {
const [channel, setChannel] = useState<Channel_type>();
const [messages, setMessages] = useState<Messages>();
const [token, setToken] = useState<string>("");
const [user, setUser] = useState<User>();
const [message, setMessage] = useState<string>("");
const [maxMessageToShown, setMaxMessageToShown] = useState<number>(10);
@ -29,9 +30,31 @@ export default function Channel() {
});
}
function deleteMessage(message_id: number) {
axios
.post(`/api/channels/${name}/messages/delete`, { token, message_id })
.then(() => {
axios
.get(`/api/channels/${name}/messages`)
.then((res) => {
setMessages(res.data);
}
);
})
.catch((err) => {
console.error(err.response.data.message);
});
}
useEffect(() => {
const localToken = localStorage.getItem("token");
if (localToken) setToken(localToken);
if (localToken) {
setToken(localToken);
axios.post("/api/auth/me", { token: localToken }).then((res) => {
setUser(res.data);
}
);
}
axios.get(`/api/channels/${name}`).then((res) => {
setChannel(res.data);
});
@ -72,6 +95,9 @@ export default function Channel() {
{messages.slice(0, maxMessageToShown).map((message) => (
<li key={message.id}>
<p>{message.username}: {message.content}</p>
{(user?.id === message.user_id || user?.id === channel.owner_id) && (
<button onClick={() => {deleteMessage(message.id)}}>Delete</button>
)}
</li>
))}
</ul>

View file

@ -48,7 +48,7 @@ export default function Home() {
<ul>
{channels?.map((channel) => (
<li key={channel.id}>
<Link to={`/${channel.name}`}>{channel.name}</Link>
<Link to={`/c/${channel.name}`}>{channel.name}</Link>
</li>
))}
</ul>

View file

@ -2,6 +2,7 @@ export type Channel_type ={
id: number,
name: string
description: string
owner_id: number
}
export type Channels = Channel_type[]