tanuki-s-forum/back/api/users.js

96 lines
No EOL
2.8 KiB
JavaScript

const express = require('express');
const { getConnection, getUsers, getUserByUsername, getUserLastMessages, getMentions, deleteUser, deleteUserMessages, deleteUserMentions } = require('../libs/mysql');
const { checkAuth } = require("../libs/middlewares")
const path = require('path');
const router = express.Router();
router.get('/', async (req, res) => {
const connection = await getConnection();
const users = await getUsers(connection);
connection.end();
res.send(users);
});
router.get('/:username', async (req, res) => {
const username = req.params.username;
const connection = await getConnection();
const user = await getUserByUsername(connection, username);
connection.end();
if (user[0]) {
res.send({id: user[0].id, username: user[0].username, admin: user[0].admin});
} else {
res.send('No user found');
}
});
router.get('/:username/lastmessages', async (req, res) => {
const username = req.params.username;
const connection = await getConnection();
const messages = await getUserLastMessages(connection, username);
for (const message of messages) {
if (message.content.includes('@')) {
const mentions = await getMentions(connection, message.id);
message.mentions = mentions;
} else {
message.mentions = [];
}
}
connection.end();
res.send(messages);
});
router.get('/:username/pfp', async (req, res) => {
const username = req.params.username;
const connection = await getConnection();
const user = await getUserByUsername(connection, username);
connection.end();
if (!user[0]) {
return res.status(400).send({ error: 'No user found' });
}
const pfp = user[0].pfp;
if (!pfp) {
return res.sendFile(path.join(__dirname, `../images/default-pfp.png`), { headers: { 'Content-Type': 'image' } });
}
res.sendFile(path.join(__dirname, `../data/pfps/${pfp}`), { headers: { 'Content-Type': 'image' } });
});
router.post('/:username/delete', checkAuth, async (req, res) => {
const username = req.params.username;
const user = req.user;
const connection = await getConnection();
const userToDelete = await getUserByUsername(connection, username);
if (!userToDelete[0]) {
connection.end();
return res.status(400).send({ error: 'No user found' });
}
if (user.admin !== 1) {
connection.end();
return res.status(401).send({ error: 'Unauthorized' });
}
await deleteUserMentions(connection, userToDelete[0].id);
await deleteUserMessages(connection, userToDelete[0].id);
await deleteUser(connection, userToDelete[0].id);
connection.end();
req.sockets.emit({
type: 'delete_user',
user_id: userToDelete[0].id,
});
res.send({ message: 'User deleted' });
});
module.exports = router;