add: added an auth middleware to simplify code

This commit is contained in:
Lukian 2025-04-03 12:30:17 +02:00
parent c34df6609c
commit e0efe57f5c
9 changed files with 104 additions and 70 deletions

View file

@ -2,6 +2,7 @@ const express = require('express');
const sha256 = require("sha256"); const sha256 = require("sha256");
const jwt = require('jsonwebtoken'); const jwt = require('jsonwebtoken');
const { getConnection, getUserByUsername, addUser, getUser } = require('../libs/mysql'); const { getConnection, getUserByUsername, addUser, getUser } = require('../libs/mysql');
const { checkAuth } = require('../libs/middlewares');
const router = express.Router(); const router = express.Router();
@ -52,27 +53,10 @@ router.post('/register', async (req, res) => {
res.send({ message: 'User added' }); res.send({ message: 'User added' });
}); });
router.use('/me', checkAuth);
router.post('/me', async (req, res) => { router.post('/me', async (req, res) => {
const { token } = req.body; const user = req.user;
res.send({ id: user.id, username: user.username, admin: user.admin });
if (!token) {
return res.status(400).send({ error: 'Invalid token' });
}
const decoded = jwt.verify(token, process.env.JWT_SECRET);
if (!decoded.id) {
return res.status(400).send({ error: 'Invalid token' });
}
const connection = await getConnection();
const users = await getUser(connection, decoded.id);
connection.end();
if (users[0]) {
res.send({ id: users[0].id, username: users[0].username, admin: users[0].admin });
} else {
res.status(401).send({ error: 'Invalid token' });
}
}); });
module.exports = router; module.exports = router;

View file

@ -1,6 +1,7 @@
const express = require('express'); const express = require('express');
const jwt = require('jsonwebtoken'); const jwt = require('jsonwebtoken');
const { getConnection, getUser, getChannels, getChannel, addChannel, getMessages, addMessage, deleteMessage, getLastMessages } = require('../libs/mysql'); const { getConnection, getUser, getChannels, getChannel, addChannel, getMessages, addMessage, deleteMessage, getLastMessages } = require('../libs/mysql');
const { checkAuth } = require('../libs/middlewares');
const router = express.Router(); const router = express.Router();
@ -36,53 +37,48 @@ router.get('/:name/messages', async (req, res) => {
res.send(messages); res.send(messages);
}); });
router.use('/:name/messages/send', checkAuth);
router.post('/:name/messages/send', async (req, res) => { router.post('/:name/messages/send', async (req, res) => {
const { token, message } = req.body; const { message } = req.body;
const name = req.params.name; const name = req.params.name;
const connection = await getConnection(); const user = req.user;
const decoded = jwt.verify(token, process.env.JWT_SECRET); if (!message) {
const user = await getUser(connection, decoded.id); return res.status(400).send({ error: 'Missing parameters' });
if (!user[0]) {
connection.end();
return res.status(401).send({ error: 'Invalid token' });
} }
const connection = await getConnection();
const channel = await getChannel(connection, name); const channel = await getChannel(connection, name);
if (!channel[0]) { if (!channel[0]) {
connection.end(); connection.end();
return res.send('No channel found'); return res.send('No channel found');
} }
await addMessage(connection, channel[0].id, user[0].id, message.replace("\"", "'")); await addMessage(connection, channel[0].id, user.id, message.replace("\"", "'"));
connection.end(); connection.end();
res.send({ message: 'Message sent' }); res.send({ message: 'Message sent' });
}); });
router.use('/:name/messages', checkAuth);
router.post('/:name/messages/delete', async (req, res) => { router.post('/:name/messages/delete', async (req, res) => {
const { token, message_id } = req.body; const { message_id } = req.body;
const name = req.params.name; const name = req.params.name;
const user = req.user;
if (!message_id || !token) { if (!message_id) {
return res.status(400).send({ error: 'Missing parameters' }); return res.status(400).send({ error: 'Missing message_id' });
} }
const connection = await getConnection(); 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); const channel = await getChannel(connection, name);
if (!channel[0]) { if (!channel[0]) {
connection.end(); connection.end();
return res.status(400).send({ error: 'No channel found' }); return res.status(400).send({ error: 'No channel found' });
} }
if (user[0].id !== channel[0].owner_id && user[0].id !== message_id && user[0].admin !== 1) { if (user.id !== channel[0].owner_id && user.id !== message_id && user.admin !== 1) {
connection.end(); connection.end();
return res.status(401).send({ error: 'Unauthorized' }); return res.status(401).send({ error: 'Unauthorized' });
} }
@ -92,22 +88,17 @@ router.post('/:name/messages/delete', async (req, res) => {
res.send({ message: 'Message deleted' }); res.send({ message: 'Message deleted' });
}); });
router.use('/add', checkAuth);
router.post('/add', async (req, res) => { router.post('/add', async (req, res) => {
const { name, description, token } = req.body; const { name, description } = req.body;
const user = req.user;
if (!name || !description || !token) { if (!name || !description) {
return res.status(400).send({ error: 'Missing parameters' }); return res.status(400).send({ error: 'Missing parameters' });
} }
const connection = await getConnection(); 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); const channel = await getChannel(connection, name);
if (channel[0]) { if (channel[0]) {
connection.end(); connection.end();
@ -119,7 +110,7 @@ router.post('/add', async (req, res) => {
return res.status(400).send({ error: 'Invalid channel name' }); return res.status(400).send({ error: 'Invalid channel name' });
} }
await addChannel(connection, name, description, user[0].id); await addChannel(connection, name, description, user.id);
connection.end(); connection.end();
res.send({ message: 'Channel added' }); res.send({ message: 'Channel added' });
}); });

28
back/libs/middlewares.js Normal file
View file

@ -0,0 +1,28 @@
const jwt = require('jsonwebtoken');
const { getConnection, getUser } = require('./mysql');
async function checkAuth(req, res, next) {
const { token } = req.body;
if (!token) {
return res.status(401).send({ error: 'No token provided' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
const connection = await getConnection();
const user = await getUser(connection, decoded.id);
connection.end();
if (!user[0]) {
return res.status(401).send({ error: 'Invalid token' });
}
req.user = user[0];
next();
}
catch (err) {
return res.status(401).send({ error: 'Invalid token' });
}
}
module.exports = {
checkAuth,
};

BIN
front/public/osaka_arch.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 MiB

View file

@ -1,3 +1,7 @@
.cat { .cat {
width: 100px; width: 100px;
} }
.osaka {
width: 200px;
}

View file

@ -26,7 +26,7 @@ export default function ChannelPage() {
); );
}) })
.catch((err) => { .catch((err) => {
console.error(err.response.data.message); console.error(err.response);
}); });
} }
@ -42,7 +42,7 @@ export default function ChannelPage() {
); );
}) })
.catch((err) => { .catch((err) => {
console.error(err.response.data.message); console.error(err.response);
}); });
} }

View file

@ -19,25 +19,48 @@ export default function Home() {
setUser(res.data) setUser(res.data)
}) })
.catch((err) => { .catch((err) => {
console.error(err) console.error(err.response)
}) })
} }
axios axios
.get("/api/channels").then((res) => { .get("/api/channels")
.then((res) => {
setChannels(res.data) setChannels(res.data)
}) })
.catch((err) => { .catch((err) => {
console.error(err) console.error(err.response)
}) })
axios axios
.get("/api/lastmessages").then((res) => { .get("/api/lastmessages")
.then((res) => {
setMessages(res.data) setMessages(res.data)
})
.catch((err) => {
console.error(err.response)
} }
) )
}, []) }, [])
useEffect(() => {
const id = setInterval(() => {
axios
.get("/api/lastmessages").then((res) => {
setMessages(res.data)
}
)
axios
.get("/api/channels").then((res) => {
setChannels(res.data)
}
)
}, 5000)
return () => { clearInterval(id) }
}, [])
return ( return (
<div> <div>
<h1>Home</h1> <h1>Home</h1>
@ -74,7 +97,7 @@ export default function Home() {
</li> </li>
))} ))}
</ul> </ul>
<img src="cat.jpg" alt="cat" className="cat"/> <img src="osaka_arch.png" alt="osaka" className="osaka"/>
</div> </div>
) )
} }

View file

@ -16,7 +16,7 @@ export default function Login() {
navigate("/"); navigate("/");
}) })
.catch((err) => { .catch((err) => {
alert(err.response.data.message); alert(err.response);
}); });
} }

View file

@ -9,18 +9,22 @@ export default function Register () {
function handleSubmit(e: React.FormEvent) { function handleSubmit(e: React.FormEvent) {
e.preventDefault(); e.preventDefault();
axios.post("/api/auth/register", { username, password }).then(() => { axios
axios .post("/api/auth/register", { username, password }).then(() => {
.post("/api/auth/login", { username, password }) axios
.then((res) => { .post("/api/auth/login", { username, password })
localStorage.setItem("token", res.data.token); .then((res) => {
navigate("/"); localStorage.setItem("token", res.data.token);
}) navigate("/");
.catch((err) => { })
alert(err.response.data.message); .catch((err) => {
} alert(err.response);
); }
}); );
})
.catch((err) => {
alert(err.response);
});
} }
return ( return (