tanuki-s-forum/back/api/auth.js
2025-06-26 17:02:29 +02:00

168 lines
No EOL
5 KiB
JavaScript

const express = require('express');
const sha256 = require("sha256");
const jwt = require('jsonwebtoken');
const { getConnection, getUserByUsername, addUser, setUserPfp, setUserUsername, setUserPassword, setUserDescription } = require('../libs/mysql');
const { checkAuth } = require('../libs/middlewares');
const multer = require('multer')
const rateLimit = require("express-rate-limit");
const slowDown = require("express-slow-down");
const fs = require('node:fs');
const upload = multer({ dest: 'data/pfps/' })
upload.limits = {
fileSize: 1024 * 1024 * 5,
files: 1,
};
const limiter = rateLimit({
windowMs: 3 * 1000,
max: 2,
});
const speedLimiter = slowDown({
windowMs: 1 * 1000,
delayAfter: 2,
delayMs: () => 5000,
});
const router = express.Router();
router.post('/login', speedLimiter, limiter, async (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).send({ error: 'Invalid username or password' });
}
const connection = await getConnection();
const user = await getUserByUsername(connection, username);
connection.end();
if (user[0]) {
if (user[0].password === sha256(password)) {
const token = jwt.sign({ id: user[0].id }, process.env.JWT_SECRET, {
expiresIn: 60 * 60 * 24 * 7,
});
return res.send({ token: token });
}
}
res.status(401).send({ error: 'Invalid username or password' });
});
router.post('/register', speedLimiter, limiter, async (req, res) => {
const { username, password } = req.body;
const connection = await getConnection();
if (!username || !password) {
connection.end();
return res.status(400).send({ error: 'Invalid username or password' });
}
const user = await getUserByUsername(connection, username);
if (user[0]) {
connection.end();
return res.status(401).send({ error: 'Username already exists' });
}
if (!/^[a-zA-Z0-9-_]+$/.test(username)) {
connection.end();
return res.status(400).send({ error: 'Invalid username' });
}
const hash = sha256(password);
await addUser(connection, username, hash);
connection.end();
req.sockets.emit({
type: 'new_user',
username: username,
});
res.send({ message: 'User added' });
});
router.post('/me', checkAuth, async (req, res) => {
const user = req.user;
res.send({ id: user.id, username: user.username, admin: user.admin , description: user.description });
});
router.post('/me/uploadpfp', upload.single('pfp'), checkAuth, async (req, res) => {
const fileName = req.file.filename;
const user = req.user;
if (user.pfp && fs.existsSync(`data/pfps/${user.pfp}`)) {
fs.unlinkSync(`data/pfps/${user.pfp}`);
}
const connection = await getConnection();
await setUserPfp(connection, user.id, fileName);
connection.end();
res.send({ message: 'Profile picture uploaded.' });
});
router.post('/me/deletepfp', checkAuth, async (req, res) => {
const user = req.user;
if (user.pfp && fs.existsSync(`data/pfps/${user.pfp}`)) {
fs.unlinkSync(`data/pfps/${user.pfp}`);
}
const connection = await getConnection();
await setUserPfp(connection, user.id, null);
connection.end();
res.send({ message: 'Profile picture deleted.' });
});
router.post('/me/setusername', checkAuth, async (req, res) => {
const { username } = req.body;
const user = req.user;
if (!username) {
return res.status(400).send({ error: 'Invalid username' });
}
if (!/^[a-zA-Z0-9-_]+$/.test(username)) {
return res.status(400).send({ error: 'Invalid username' });
}
const connection = await getConnection();
const userExists = await getUserByUsername(connection, username);
if (userExists[0]) {
connection.end();
return res.status(401).send({ error: 'Username already exists' });
}
await setUserUsername(connection, user.id, username);
connection.end();
res.send({ message: 'Username changed.' });
});
router.post('/me/setpassword', checkAuth, async (req, res) => {
const { oldPassword, password } = req.body;
const user = req.user;
if (!password || !oldPassword || sha256(oldPassword) !== user.password) {
return res.status(400).send({ error: 'Invalid password' });
}
const connection = await getConnection();
await setUserPassword(connection, user.id, sha256(password));
connection.end();
res.send({ message: 'Password changed.' });
});
router.post('/me/setdescription', checkAuth, async (req, res) => {
const { description } = req.body;
const user = req.user;
if (!description) {
return res.status(400).send({ error: 'Invalid description' });
}
const connection = await getConnection();
await setUserDescription(connection, user.id, description);
connection.end();
res.send({ message: 'Description changed.' });
});
module.exports = router;