Initial commit

This commit is contained in:
2025-08-19 09:55:57 -04:00
commit dae1a31b4c
69 changed files with 8243 additions and 0 deletions

63
server/app.js Normal file
View File

@ -0,0 +1,63 @@
// server/app.js
console.log("Starting Server...");
import express from 'express';
import cors from 'cors';
// import multer from 'multer';
// import path from 'path';
import db from './models/db.js';
import dotenv from 'dotenv';
dotenv.config();
// test db connection
try {
await db.query("SELECT 1")
console.log("DB connection successful")
await db.get('users', {id: 1});
console.log("Users table exists");
} catch (err) {
console.error(err);
process.exit(1);
}
const app = express();
app.use(cors());
app.use(express.json());
// Serve static files from the client build directory
if (process.env.NODE_ENV !== 'development') app.use("/", express.static('../client/dist'));
/*const UPLOAD_FOLDER = path.join(process.cwd(), 'Scans');
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, UPLOAD_FOLDER);
},
filename: (req, file, cb) => {
cb(null, file.originalname);
}
});
const upload = multer({storage});*/
// user routes
import userRouter from './controllers/userController.js';
app.use('/api/users', userRouter);
// email routes
import emailRouter from "./controllers/emailController.js";
app.use('/api/email', emailRouter);
// other routes
// Error handling middleware
import errorHandler from './middleware/ErrorHandler.js';
app.use(errorHandler);
// 404 handler
app.use((req, res) => {
res.status(404).json({message: 'Route not found'});
});
const PORT = process.env.PORT || 8000;
app.listen(PORT, () => {
console.log(`Express server running on port ${PORT}`);
});

View File

@ -0,0 +1,148 @@
import nodemailer from 'nodemailer';
import dotenv from 'dotenv';
import {Router} from 'express';
/** @typedef Email
* @property {string} name - name of sender.
* @property {string} email - email addr of sender.
* @property {string} subject - subject of email.
* @property {string} message - message body of email.
*/
/** @typedef {import("@types/express").Request} Request */
/** @typedef {import("@types/express").Response} Response */
/** @typedef {import("@types/express").NextFunction} NextFunction */
/** @typedef {import("@types/nodemailer").TransportOptions} TransportOptions */
dotenv.config();
const transporter = nodemailer.createTransport(
/** @type {TransportOptions}*/
{
service: 'gmail', // Use Gmail as the email service
target: process.env.EMAIL_TARGET, // The email address to send the email to
auth: {
user: process.env.MAILER_EMAIL_ADDR, // Your Gmail address
pass: process.env.MAILER_EMAIL_PASS, // Your Gmail password or App Password
},
});
await withTimeout(transporter.verify(), 15000)
.then(() => {
console.log("Transporter is ready to send emails");
})
.catch((error) => console.error("Error verifying transporter:", error));
const router = Router()
router.post('/',
/**
* Sends an email using the configured transporter.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @return {Promise<e.Response<any, Record<string, any>> | void>}
*/
async (req, res, next) => {
try {
console.debug("made it to sendEmail function");
let exitonError = false;
await withTimeout(transporter.verify(), 15000)
.then(() => {
console.debug("Transporter is ready to send emails");
})
.catch((error) => {
console.error("Error verifying transporter:", error);
res.status(500).json({message: 'Failed to verify email transporter'});
exitonError = true;
});
if (exitonError) return;
const emailWithZeroWidthSpace = req.body.email.replace(/@/g, '@\u200B').replace(/\./g, ".\u200B"); // Add zero-width space to prevent email scraping
/** @type {Email} */
const contact = {
name: req.body.name,
email: emailWithZeroWidthSpace, // Add zero-width space to prevent email scraping
subject: req.body.subject,
message: req.body.message,
};
if (!contact.name || !contact.email || !contact.subject || !contact.message) {
return res.status(400).json({message: 'To, subject, and text are required'});
}
const emailText = `
This email was sent from Li0nhunter's Bot.
Name: ${contact.name}
Email: ${contact.email}
Subject: ${contact.subject}
Message: ${contact.message}
Respond now: mailto:${contact.email}
`
const emailHtml = `
<div style="max-width:80%;margin:40px auto;background:var(--color-background);border-radius:8px;box-shadow:0 2px 8px rgba(0,0,0,0.14);padding:32px 24px;font-family:Arial,sans-serif;">
<h1 style="margin-bottom:24px;text-align:center;color:var(--color-text);">You got a message from your website's contact page!</h1>
<div style="margin-bottom:16px;">
<label style="display:block;font-size:1rem;font-weight:500;margin-bottom:4px;color:var(--color-text);"><b>Name:</b></label>
<div style="font-size:1rem;font-weight:500;padding:10px 12px;border:1px solid #333333;border-radius:4px;background:var(--color-form-background);color:var(--color-text);"><b>${contact.name}</b></div>
</div>
<div style="margin-bottom:16px;">
<label style="display:block;font-size:1rem;font-weight:500;margin-bottom:4px;color:var(--color-text);"><b>Email:</b></label>
<div style="font-size:1rem;font-weight:500;padding:10px 12px;border:1px solid #333333;border-radius:4px;background:var(--color-form-background);color:var(--color-text);"><b>${contact.email}</b></div>
</div>
<div style="margin-bottom:16px;">
<label style="display:block;font-size:1rem;font-weight:500;margin-bottom:4px;color:var(--color-text);"><b>Subject:</b></label>
<div style="font-size:1rem;font-weight:500;padding:10px 12px;border:1px solid #333333;border-radius:4px;background:var(--color-form-background);color:var(--color-text);"><b>${contact.subject}</b></div>
</div>
<div style="margin-bottom:24px;">
<label style="display:block;font-size:1rem;font-weight:500;margin-bottom:4px;color:var(--color-text);"><b>Message:</b></label>
<div style="font-size:1rem;font-weight:500;padding:10px 12px;border:1px solid #333333;border-radius:4px;background:var(--color-form-background);color:var(--color-text);white-space:pre-line;"><b>${contact.message}</b></div>
</div>
<div style="text-align:center;">
<a href="mailto:${contact.email}" style="display:inline-block;font-weight:500;color:var(--color-text);background-color:var(--color-form-background);border:1px solid #333333;padding:10px 32px;text-align:center;border-radius:4px;text-decoration:none;font-size:1.1rem;transition:background 0.2s;"><b>Respond now</b></a>
</div>
<p style="text-align:center;color:var(--color-text);">This email was sent from Li0nhunter's Bot.</p>
</div>
`;
const mailOptions = {
from: `"Li0nhunter's Web Bot" <${process.env.EMAIL_ADDR}>`, // sender address
to: process.env.EMAIL_TARGET,
replyTo: contact.email,
subject: contact.subject, // Subject line
text: emailText, // plain text body
html: emailHtml, // html body
};
// Set a timeout of 15 seconds (15,000 ms) for sending the email
await withTimeout(transporter.sendMail(mailOptions), 15000)
.then((result) => res.status(200).json({data: result, message: 'Email sent successfully'}))
.catch((error) => {
console.error(error);
res.status(500).json({message: error.message || 'Failed to send email'});
});
} catch (error) {
next(error);
}
});
/**
* Executes a promise with a timeout.
* @param {Promise<any>} promise The promise to execute.
* @param {number} ms The timeout in milliseconds.
* @throws {Error} If the promise does not resolve within the specified time.
* @return {Promise<any>}
*/
async function withTimeout(promise, ms) {
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error('Operation timed out')), ms)
);
return Promise.race([promise, timeout])
}
export default router;

View File

@ -0,0 +1,161 @@
import authHandler from "../middleware/AuthHandler.js";
import users from "../models/users.js";
import express from "express";
const router = express.Router();
/** @typedef User
* @property {number} id - The unique identifier for the user.
* @property {string} username - The username of the user.
* @property {string} password - The hashed password of the user.
*/
/** @typedef {import("@types/express").Request} Request */
/** @typedef {import("@types/express").Response} Response */
/** @typedef {import("@types/express").NextFunction} NextFunction */
router.get("/",
/** * Fetches all users from the database.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @return {Promise<void>}
*/
async (req, res, next) => {
await users.getAllUsers()
.then((users) => {
res.status(200).json({data: users});
})
.catch((err) => next(err));
}
)
router.get("/",
/**
* adds new user to db as non-admin. only direct db manipulation can make users admins
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @return {Promise<e.Response<any, Record<string, any>> | void>}
*/
async (req, res, next) => {
if (!req.body || !req.body.username || !req.body.password) {
return res.status(400).json({data: null, message: 'Username and password are required'});
}
await users.addNewUser(req.body.username, req.body.password)
.then((user) => {
if (!user) {
return res.status(500).json({data: null, message: 'User not found after insertion'});
}
res.status(200).json({data: user, message: 'User added successfully'});
})
.catch((err) => next(err));
});
router.get("/:identifier",
/**
* Fetches a user by ID or username from the database.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @return {Promise<e.Response<any, Record<string, any>> | void>}
*/
async (req, res, next) => {
const userIdentifier = req.params.identifier;
if (!userIdentifier) return res.status(400).json({data: null, message: 'User identifier is required'});
await users.getUser(userIdentifier)
.then(user => {
if (!user) return res.status(404).json({data: null, message: 'User not found'});
res.status(200).json({data: user});
})
.catch((err) => {
if (err instanceof Error) {
if (err.message === 'User not found') {
return res.status(404).json({data: null, error: err});
}
if (err.message === 'Multiple users found with the same identifier, something has gone wrong') {
res.status(500).json({
data: null,
error: err
});
} else next(err);
} else {
next(new Error('An unhandled error occurred while fetching the user'));
}
})
}
)
router.post("/login",
/**
* Fetches a user by ID or username from the database.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @return {Promise<e.Response<any, Record<string, any>> | void>}
*/
async (req, res, next) => {
const {username, password} = req.body;
if (!username || !password) return res.status(400).json({
data: null,
message: 'Username and password are required'
});
await users.login(username, password).then(data => {
if (!data) return res.status(401).json({data: null, message: 'Invalid username or password'});
res.status(200).json({data: data, message: 'Login successful'});
})
.catch((err) => {
if (err instanceof Error) {
if (err.message === 'Invalid username or password') {
res.status(401).json({data: null, error: err});
} else next(err);
} else {
next(new Error('An unhandled error occurred while login'));
}
})
})
router.patch("/:identifier", authHandler.authenticateUser,
/**
* Updates a user by ID or username in the database.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @return {Promise<e.Response<any, Record<string, any>> | void>}
*/
async (req, res, next) => {
const userIdentifier = req.params.id;
if (!userIdentifier) return res.status(400).json({data: null, message: 'User Identifier is required'});
await users.updateUser(req.body)
.then(user => {
if (!user) res.status(404).json({data: null, message: 'User not found'});
else res.status(200).json({data: user, message: 'User updated successfully'});
})
.catch((err) => next(err))
}
)
router.delete("/:identifier", authHandler.authenticateUser,
/**
* deletes a user by ID or username from the database.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @return {Promise<e.Response<any, Record<string, any>> | void>}
*/
async (req, res, next) => {
const userIdentifier = req.params.identifier;
if (!userIdentifier) return res.status(400).json({data: null, message: 'User identifier is required'});
await users.deleteUser(userIdentifier)
.then(user => {
if (!user) return res.status(404).json({data: null, message: 'User not found'});
res.status(200).json({data: user, message: 'User deleted successfully'});
})
.catch((err) => next(err));
}
)
export default router

View File

@ -0,0 +1,65 @@
import jwt from "jsonwebtoken";
/** @typedef {import("@types/express").Request} Request */
/** @typedef {import("@types/express").Response} Response */
/** @typedef {import("@types/express").NextFunction} NextFunction */
export default {
/**
* Express middleware to verify JWT and check for the admin role.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<e.Response<any, Record<string, any>> | void>}
*/
authenticateAdmin: async (req, res, next) => {
const token = req.headers.authorization;
if (!token) return res.status(401).send({data: null, error: "Token missing"});
try {
const payload = await new Promise((resolve, reject) => {
jwt.verify(token, process.env.JWT_SECRET || "super-secret-key", (err, decoded) => {
if (err) return reject(err);
return resolve(decoded);
});
});
// Check if payload has id and role and if the role is admin
if (!payload || !payload.id || !payload.role) return res.status(401).json({data: null, error: "Invalid token"});
if (payload.role !== "admin") return res.status(403).json({data: null, error: "admins only"});
next();
} catch (err) {
if (err instanceof Error && err.message === 'jwt expired') return res.status(401).json({data: null, message: "Token expired", error: err});
res.status(401).json({data: null, message: "Invalid token", error: err});
}
},
/**
* Express middleware to verify JWT and check for the user role.
* @param {Request} req
* @param {Response} res
* @param {NextFunction} next
* @returns {Promise<e.Response<any, Record<string, any>> | void>}
*/
authenticateUser: async (req, res, next) => {
const token = req.headers.authorization;
if (!token) {
return res.status(401).send({data: null, error: "Token missing"});
}
try {
const payload = jwt.verify(token, process.env.JWT_SECRET || "super-secret-key");
// Check if payload has id and role
if (!payload || !payload.id || !payload.role) {
return res.status(401).json({data: null, error: "Invalid token"});
}
// check if the user id matches the id in the token
else if (payload.role !== "admin" && req.params.id && req.params.id !== payload.id.toString()) {
return res.status(403).json({data: null, error: "Forbidden"});
}
next();
} catch (err) {
if (err instanceof Error && err.message === 'jwt expired') {
return res.status(401).json({data: null, message: "Token expired", error: err});
}
res.status(401).json({data: null, message: "Invalid token", error: err});
}
}
}

View File

@ -0,0 +1,18 @@
/** @typedef {import("@types/express").Request} Request */
/** @typedef {import("@types/express").Response} Response */
/** @typedef {import("@types/express").NextFunction} NextFunction */
/**
* Express error handler middleware.
* @param {Error & {status?: number}} err
* @param {Request} req
* @param {Response} res
* @param {NextFunction} _
* @returns {void}
*/
export default (err, req, res, _) => {
console.error(err);
if (!res.statusCode) {
res.status(err.status || 500).json({message: err.message || 'Internal Server Error'});
}
};

141
server/models/db.js Normal file
View File

@ -0,0 +1,141 @@
import dotenv from 'dotenv';
import {Pool} from 'pg';
dotenv.config();
const pool = new Pool(process.env.DATABASE_URL ? {connectionString: process.env.DATABASE_URL} : {
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_NAME,
password: process.env.DB_PASSWORD,
port: parseInt(process.env.DB_PORT || '5432', 10),
});
/**
* Generic query function for PostgreSQL database.
* @template T
* @param {string} text
* @param {any[]} [params]
* @return {Promise<T[]>}
*/
async function query(text, params= []) {
const start = Date.now();
const res = await pool.query(text, params).then(qr => qr);
const duration = Date.now() - start;
if (params) for (let i = 0; i < params.length; i++) text = text.replace("$".concat(String(i + 1)), params[i]);
console.log('executed query', {text, duration, rows: res.rowCount});
/**@type T[]*/
return res.rows;
}
/**
* function to insert data into a table.
* @template T
* @param {string} table The name of the table to insert data into.
* @param {Object.<string, any>} map The {keys: values} to insert data into.
* @returns {Promise<T[] | Error>} Returns inserted value if the insertion was successful, error otherwise.
* */
async function insert(table, map) {
const valuePlaceholders = Object.keys(map).map((_, index) => `$${index + 1}`).join(", ");
const queryText = `INSERT INTO ${table} (${Object.keys(map).join(", ")}) VALUES (${valuePlaceholders}) RETURNING *`;
return await query(queryText, Object.values(map))
.then(resRows => {
if (resRows.length === 0) {
console.error('Insert failed: No rows affected');
return new Error('Insert failed: No rows affected');
}
console.log('Insert successful:', resRows);
return resRows;
})
.catch(err => {
console.error('Insert error:', err);
return err;
});
}
/**
* Function to update data in a table.
* @template T
* @param {string} table
* @param {Object.<string, any>} updateMap The {keys: values} to update.
* @param {Object.<string, any>} conditions The conditions to match to update.
* @returns {Promise<T[] | Error>} Returns updated rows if the insertion was successful, error otherwise.
*/
async function update(table, updateMap, conditions) {
if (Object.keys(updateMap).length === 0) {
console.error('Update failed: No fields to update');
return new Error('Update failed: No fields to update');
}
if (Object.keys(conditions).length === 0) {
console.error('Update failed: No conditions specified');
return new Error('Update failed: No conditions specified');
}
const setClause = Object.keys(updateMap).map((key, index) => `${key} = ${index + 1}`).join(', ');
const whereClause = Object.entries(conditions).map(([key, value]) => `${key} = ${value}`).join(' AND ');
return await query(`UPDATE ${table} SET ${setClause} WHERE ${whereClause} RETURNING *`, Object.values(updateMap))
.then(resRows => {
if (resRows.length === 0) {
console.error('Update failed: No rows affected');
return new Error('Update failed: No rows affected');
}
console.log('Update successful:', resRows);
return resRows;
})
.catch(err => {
console.error('Update error:', err);
return err;
});
}
/**
* Function to delete a row from a table by ID.
* @template T
* @param {string} table The name of the table to delete from.
* @param {Object.<string, any>} conditions The conditions to match to delete row/rows.
* @return {Promise<T[] | Error>} Returns true if the deletion was successful, false otherwise.
*/
async function remove(table, conditions = {}) {
if (!conditions || Object.keys(conditions).length === 0) {
console.error('Delete failed: No identifier specified');
return new Error('Delete failed: No identifier specified');
}
const whereClause = Object.entries(conditions).map(([key, _], index) => `${key} = ${index + 1}`).join(' AND ');
const queryText = `DELETE FROM ${table} WHERE ${whereClause} RETURNING *`;
return await query(queryText, Object.values(conditions))
.then(resRows => {
if (resRows.length === 0) {
console.error('Delete failed: No rows affected');
return new Error('Delete failed: No rows affected');
}
console.log('Delete successful:', resRows);
return resRows;
})
.catch(err => {
console.error('Delete error:', err);
return err;
});
}
/**
* Function to get rows from a table based on conditions.
* @template T
* @param {string} table The name of the table to query.
* @param {{}} conditions The conditions to match rows.
* @return {Promise<T[]>} Returns an array of rows that match the conditions.
*/
async function get(table, conditions = {}) {
if (Object.keys(conditions).length === 0) {
return await query(`SELECT * FROM "${table}"`);
}
const whereClause = Object.entries(conditions).map(([key, _], index) => `${key} = $${index + 1}`).join(' AND ');
return await query(`SELECT * FROM ${table} WHERE ${whereClause}`, Object.values(conditions));
}
export default {
pool,
query,
insert,
update,
remove,
get,
};

146
server/models/users.js Normal file
View File

@ -0,0 +1,146 @@
import jwt from "jsonwebtoken";
import db from "./db.js";
import bcrypt from "bcryptjs";
/** @typedef User
* @property {number} id - The unique identifier for the user.
* @property {string} username - The username of the user.
* @property {string} password - The hashed password of the user.
* @property {string} role - The role of the user, e.g., 'user' or 'admin'.
*/
/**
* Fetches all users from the database.
* @return {Promise<User[]>}
*/
async function getAllUsers() {
try {
return await db.get('users').then((users) => users);
} catch (error) {
console.error('Error fetching users:', error);
throw error;
}
}
/**
* gets user by id or username
* @param {string | number} identifier can be either user id or username
* @return {Promise<{id: number, username: string, password: string, role: string}>}
*/
async function getUser(identifier) {
/** @type {User[]} users */
let users;
if (/^\d+$/.test(identifier)) users = await db.get('users',{"id": identifier});
else users = await db.get('users', {'username': identifier});
if (users.length === 0) throw new Error("User not found");
else if (users.length > 1) throw new Error("Multiple users found with the same identifier, something has gone wrong");
return users[0];
}
/**
* adds new user to db as non-admin. only direct db manipulation can make users admins
* @param {string} username
* @param {string} password
* @return {Promise<User|void>}
*/
async function addNewUser(username, password) {
if (!username || !password) throw new Error('Username and password are required');
// Check if the user already exists
if ((await db.get('users', {'username': username})).length > 0) throw new Error('User already exists with this username');
// Hash the password before storing it
const hashedPassword = await bcrypt.hash(password, 10);
/** @type {Promise<User|Error>} */
const result = await db.insert('users', {username, password: hashedPassword, role: 'user'});
if (!result) throw new Error('User could not be created');
if (result instanceof Error) throw result;
return result;
}
/**
* Logs in a user by validating their credentials and generating a JWT token.
* @param {string} username
* @param {string} password
* @return {Promise<{id: number, username: string, role: string, token: (*)}>}
*/
async function login (username, password) {
/** @type {User} user*/
const user = await db.get('users', {'username': username}).then(response => {
if (response instanceof Error) throw response;
if (response.length === 0) throw new Error('User not found');
if (response.length > 1) throw new Error('Multiple users found with the same username, something has gone wrong');
return response[0];
});
if (!user || !bcrypt.compareSync(password, user.password)) {
throw new Error('Invalid username or password');
}
console.log(user);
const token = jwt.sign({id: user.id, role: user.role}, process.env.JWT_SECRET, {expiresIn: "1d"});
return {
id: user.id,
username: user.username,
role: user.role,
token: token
}
}
/**
* Updates a user's information.
* @param {{id?: number, username?: string, password?: string, newPassword?: string}} mapping
* @return {Promise<User>}
*/
async function updateUser(mapping) {
if (!mapping) throw new Error('User mapping is required');
if (!mapping.id && !mapping.username) throw new Error('User id or username is required for update');
let user;
if (mapping.id) user = await getUser(mapping.id);
else user = await getUser(mapping.username);
if (!user) throw new Error('User not found');
if (mapping.newPassword) {
// validate the old password to make sure the user is authenticated
if (!mapping.password) throw new Error('Old password is required to update password');
if (!bcrypt.compareSync(mapping.password, user.password)) throw new Error('Old password is incorrect');
// Hash the new password before updating
mapping.password = await bcrypt.hash(mapping.newPassword, 10);
delete mapping.newPassword; // Remove newPassword from the mapping
}
/** @type {User[] | Error} */
let result;
if (mapping.id) {
// remove id from mapping to avoid updating it
const id = mapping.id;
delete mapping.id;
result = await db.update('users', mapping, {'id': id});
} else {
// remove username from mapping to avoid updating it
const username = mapping.username;
delete mapping.username;
result = await db.update('users', mapping, {'username': username});
}
if (result instanceof Error) throw result;
if (result.length > 1) throw new Error('Multiple users updated, something has gone wrong');
return result[0];
}
/**
* Deletes a user by their ID.
* @param {string | number} identifier can be either user id or username
* @return {Promise<User>}
*/
async function deleteUser(identifier) {
if (!identifier) throw new Error('User identifier is required');
/** @type {User[] | Error} */
let result;
if (/^\d+$/.test(identifier)) result = await db.remove('users', {"id": identifier});
else result = await db.remove('users', {'username': identifier});
if (result instanceof Error) throw result;
return result[0];
}
export default {
getAllUsers,
getUser,
addNewUser,
login,
updateUser,
deleteUser
}

2093
server/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

28
server/package.json Normal file
View File

@ -0,0 +1,28 @@
{
"name": "server",
"version": "0.1.0",
"private": false,
"type": "module",
"description": "Server application for to-do-list-partner",
"author": "li0nhunter",
"scripts": {
"dev": "nodemon app.js",
"start": "node app.js"
},
"dependencies": {
"bcryptjs": "^3.0.2",
"cors": "^2.8.5",
"dotenv": "^16.5.0",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"multer": "^2.0.1",
"nodemailer": "^7.0.5",
"pg": "^8.16.3"
},
"devDependencies": {
"@types/express": "^5.0.3",
"@types/nodemailer": "^6.4.7",
"jsdoc": "^4.0.4",
"nodemon": "^3.1.10"
}
}