Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor: Convert Variables to let and const, Improve configuration handling in app.loadConfig() #319

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
106 changes: 75 additions & 31 deletions app.js
@@ -1,7 +1,7 @@
const mongoose = require("mongoose");
mongoose.promise = global.Promise;
const recaptcha = require("express-recaptcha");
const readline = require("readline").createInterface({input: process.stdin, output: process.stdout});
const readline = require("readline").createInterface({ input: process.stdin, output: process.stdout });
const util = require("util");
const PaintingManager = require("./util/PaintingManager");
const HTTPServer = require("./util/HTTPServer");
Expand All @@ -18,29 +18,73 @@ const User = require("./models/user");
const fs = require("fs");
const path = require("path");

var app = {};
const app = {};

app.logger = require('./util/logger');

app.loadConfig = (path = "./config/config") => {
const loadNewConfig = (path) => {
delete require.cache[require.resolve(path)];
var oldConfig = app.config;
app.config = require(path);
app.colours = [... new Set((app.config.colours || ["#FFFFFF", "#E4E4E4", "#888888", "#222222", "#FFA7D1", "#E50000", "#E59500", "#A06A42", "#E5D900", "#94E044", "#02BE01", "#00D3DD", "#0083C7", "#0000EA", "#CF6EE4", "#820080"]).map((c) => c.toUpperCase()))];
if(!app.config.siteName) app.config.siteName = "Place";
if(!app.config.enableChangelogs) app.config.enableChangelogs = true;
if(!app.config.boardSize) app.config.boardSize = 1600; // default to 1600 if not specified in config
if(oldConfig && (oldConfig.secret != app.config.secret || oldConfig.database != app.config.database || oldConfig.boardSize != app.config.boardSize)) {
app.logger.log("Configuration", "We are stopping the Place server because the database URL, secret, and/or board image size has been changed, which will require restarting the entire server.");
app.colours = [
...new Set(
(app.config.colours || [
"#FFFFFF", "#E4E4E4", "#888888", "#222222", "#FFA7D1", "#E50000",
"#E59500", "#A06A42", "#E5D900", "#94E044", "#02BE01", "#00D3DD",
"#0083C7", "#0000EA", "#CF6EE4", "#820080"
]).map((c) => c.toUpperCase())
),
]
}

const setDefaultValues = () => {
if (!app.config.siteName) {
app.config.siteName = "Place";
}
if (!app.config.enableChangelogs) {
app.config.enableChangelogs = true;
}
if (!app.config.boardSize) {
app.config.boardSize = 1600;
} // default to 1600 if not specified in config
}
const checkConfigChanges = (oldConfig) => {
const hasConfigChanged =
oldConfig &&
(oldConfig.secret !== app.config.secret ||
oldConfig.database !== app.config.database ||
oldConfig.boardSize !== app.config.boardSize);

if (hasConfigChanged) {
app.logger.log(
"Configuration",
"We are stopping the Place server because the database URL, secret, and/or board image size has been changed, which will require restarting the entire server."
);
process.exit(0);
}
if(oldConfig && (oldConfig.oauth != app.config.oauth)) {
}

const checkPortChanges = (oldConfig) => {
const hasPortChanges =
oldConfig &&
(oldConfig.port != app.config.port ||
oldConfig.onlyListenLocal != app.config.onlyListenLocal)
if (hasPortChanges) {
app.restartServer()
}
}
app.loadConfig = (path = "./config/config") => {
const oldConfig = app.config
loadNewConfig(path)
setDefaultValues()
checkConfigChanges(oldConfig)
checkPortChanges(oldConfig)

if (oldConfig && (oldConfig.oauth != app.config.oauth)) {
app.stopServer();
app.recreateServer();
app.restartServer();
app.recreateRoutes();
}
if(oldConfig && (oldConfig.port != app.config.port || oldConfig.onlyListenLocal != app.config.onlyListenLocal)) app.restartServer();
}
app.loadConfig();

Expand Down Expand Up @@ -73,24 +117,24 @@ app.leaderboardManager = LeaderboardManager(app);
app.userActivityController = UserActivityManager(app);

app.enableCaptcha = false;
if(typeof app.config.recaptcha !== "undefined") {
if(typeof app.config.recaptcha.siteKey !== "undefined" && typeof app.config.recaptcha.secretKey !== "undefined") {
if (typeof app.config.recaptcha !== "undefined") {
if (typeof app.config.recaptcha.siteKey !== "undefined" && typeof app.config.recaptcha.secretKey !== "undefined") {
app.enableCaptcha = app.config.recaptcha.siteKey != "" && app.config.recaptcha.secretKey != "";
}
}
if(app.enableCaptcha) {
if (app.enableCaptcha) {
// Set up reCaptcha
recaptcha.init(app.config.recaptcha.siteKey, app.config.recaptcha.secretKey);
app.recaptcha = recaptcha;
}

app.adminMiddleware = (req, res, next) => {
if(!req.user || !req.user.admin) return res.status(403).redirect("/?admindenied=1");
if (!req.user || !req.user.admin) return res.status(403).redirect("/?admindenied=1");
next();
};

app.modMiddleware = (req, res, next) => {
if(!req.user || !(req.user.admin || req.user.moderator)) return res.status(403).redirect("/?moddenied=1");
if (!req.user || !(req.user.admin || req.user.moderator)) return res.status(403).redirect("/?moddenied=1");
next();
};

Expand All @@ -106,7 +150,7 @@ mongoose.connect(process.env.DATABASE || app.config.database);
const handlePendingDeletions = () => {
setInterval(() => {
const now = new Date();
User.remove({ deletionDate: { $lte: now } }, function(err, result) {
User.remove({ deletionDate: { $lte: now } }, function (err, result) {
if (err) { console.error(err); return }
if (result.n) app.logger.log('Deleter', `Deleted ${result.n} users.`);
});
Expand All @@ -122,10 +166,10 @@ app.javascriptProcessor = new JavaScriptProcessor(app);
app.javascriptProcessor.processJavaScript();

app.stopServer = () => {
if(app.server.listening) {
if (app.server.listening) {
app.logger.log('Shutdown', "Closing server…")
app.server.close();
setImmediate(function() { app.server.emit("close"); });
setImmediate(function () { app.server.emit("close"); });
}
}

Expand All @@ -150,18 +194,18 @@ app.recreateRoutes = () => {
app.recreateRoutes();
readline.on('line', i => {
try {
var output = eval(i)
const output = eval(i)
output instanceof Promise
? output.then(a => {
console.log('Promise Resolved')
console.log(util.inspect(a, {depth: 0}))
}).catch(e => {
console.log('Promise Rejected')
console.log(e.stack)
})
: output instanceof Object
? console.log(util.inspect(output, {depth: 0}))
: console.log(output)
? output.then(a => {
console.log('Promise Resolved')
console.log(util.inspect(a, { depth: 0 }))
}).catch(e => {
console.log('Promise Rejected')
console.log(e.stack)
})
: output instanceof Object
? console.log(util.inspect(output, { depth: 0 }))
: console.log(output)
} catch (err) {
console.log(err.stack)
}
Expand Down
22 changes: 11 additions & 11 deletions client/js/account.js
@@ -1,16 +1,16 @@
var passwordProgressAlert = $("div[name=\"changePasswordProgressAlert\"]");
var deactivateProgressAlert = $("div[name=\"deactivateAccountProgressAlert\"]");
var enableTOTPAlert = $("div[name=\"enableTOTPAlert\"]");
let passwordProgressAlert = $("div[name=\"changePasswordProgressAlert\"]");
let deactivateProgressAlert = $("div[name=\"deactivateAccountProgressAlert\"]");
let enableTOTPAlert = $("div[name=\"enableTOTPAlert\"]");

function setAlert(alert, success = true, text) {
alert.attr("class", "").addClass(`alert alert-${success ? "success" : "danger"}`).html(`<strong>${success ? "Success!" : "Uh oh!"}</strong> ${text || "An unknown error occurred."}`);
}

$("form#changePasswordForm").submit(function (e) {
e.preventDefault();
var oPassword = $(this).find("input[name=\"password\"]").val();
var nPassword = $(this).find("input[name=\"newPassword\"]").val();
var nCPassword = $(this).find("input[name=\"newConfPassword\"]").val();
let oPassword = $(this).find("input[name=\"password\"]").val();
let nPassword = $(this).find("input[name=\"newPassword\"]").val();
let nCPassword = $(this).find("input[name=\"newConfPassword\"]").val();
if (oPassword == "" || nPassword == "" || nCPassword == "") return setAlert(passwordProgressAlert, false, "Please fill out all the fields.");
if (nPassword !== nCPassword) return setAlert(passwordProgressAlert, false, "The passwords you entered did not match.");

Expand All @@ -23,7 +23,7 @@ const passwordField = $("#deactivateAccount").find("input[name=\"password\"]");

$("#deactivateButton").click(function(e) {
e.preventDefault();
var password = passwordField.val();
let password = passwordField.val();
if (password == "") return setAlert(deactivateProgressAlert, false, "Please enter your password.");
placeAjax.post("/api/user/deactivate", { password: password }, null).then((response) => {
window.location.href = "/deactivated";
Expand All @@ -32,15 +32,15 @@ $("#deactivateButton").click(function(e) {

$("#deleteButton").click(function(e) {
e.preventDefault();
var password = passwordField.val();
let password = passwordField.val();
if (password == "") return setAlert(deactivateProgressAlert, false, "Please enter your password.");
placeAjax.delete("/api/user", { password: password }, null).then((response) => {
window.location.href = "/deleted";
}).catch((err) => setAlert(deactivateProgressAlert, false, err ? err.message : null));
});

$("#disableTwoFactorAuth").click(function () {
var elem = $(this).addClass("disabled");
let elem = $(this).addClass("disabled");
placeAjax.delete("/api/user/totp-setup", null, "An unknown error occurred while trying to disable two-factor authentication.", () => {
elem.removeClass("disabled");
}).then((response) => {
Expand All @@ -50,7 +50,7 @@ $("#disableTwoFactorAuth").click(function () {

$("form#enableTOTPForm").submit(function (e) {
e.preventDefault();
var submitBtn = $(this).find("button[type=submit]").text("Verifying").addClass("disabled");
let submitBtn = $(this).find("button[type=submit]").text("Verifying").addClass("disabled");
placeAjax.post("/api/user/totp-setup", $(this).serialize(), null, () => {
submitBtn.text("Verify").removeClass("disabled");
}).then((response) => {
Expand All @@ -59,7 +59,7 @@ $("form#enableTOTPForm").submit(function (e) {
});

$("#enableTwoFactorAuth").click(function () {
var elem = $(this).addClass("disabled");
let elem = $(this).addClass("disabled");
placeAjax.get("/api/user/totp-setup", null, "An unknown error occurred while trying to load two-factor authentication setup.", () => {
elem.removeClass("disabled");
}).then((response) => {
Expand Down
2 changes: 1 addition & 1 deletion client/js/admin_similar_users.js
@@ -1,6 +1,6 @@
$(document).ready(function() {
$(".timeago").timeago();
var getUserRow = function(user, relationString) {
let getUserRow = function(user, relationString) {
return `<div class="user">
<div class="user-info">
<a href="/@${user.username}" class="username">${user.username}</a>
Expand Down
4 changes: 2 additions & 2 deletions client/js/admin_users.js
@@ -1,5 +1,5 @@
$(document).ready(function() {
var table = $("#users").DataTable({
let table = $("#users").DataTable({
processing: true,
serverSide: true,
aaSorting: [[2, "desc"]],
Expand All @@ -24,7 +24,7 @@ $(document).ready(function() {
},
serverParams: (data) => data.bChunkSearch = true
}).columns().every( function () {
var that = this;
let that = this;
$("input[type=search]", this.footer() ).attr("spellcheck", "false").attr("autocomplete", "off").attr("autocorrect", "off").attr("autocapitalize", "off").on( "keyup change", function () {
if (that.search() !== this.value) {
that.search(this.value, true).draw();
Expand Down