generated from li0nhunter/Website-template
Initial commit
This commit is contained in:
148
server/controllers/emailController.js
Normal file
148
server/controllers/emailController.js
Normal 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;
|
||||
|
||||
161
server/controllers/userController.js
Normal file
161
server/controllers/userController.js
Normal 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
|
||||
Reference in New Issue
Block a user