diff --git a/server/client.js b/server/client.js index 72f0a4e8e..0890ec8be 100644 --- a/server/client.js +++ b/server/client.js @@ -19,9 +19,7 @@ async function sendNotificationList(socket) { const timeLogger = new TimeLogger(); let result = []; - let list = await R.find("notification", " user_id = ? ", [ - socket.userID, - ]); + let list = await R.findAll("notification"); for (let bean of list) { let notificationObject = bean.export(); @@ -102,7 +100,7 @@ async function sendImportantHeartbeatList(socket, monitorID, toUser = false, ove async function sendProxyList(socket) { const timeLogger = new TimeLogger(); - const list = await R.find("proxy", " user_id = ? ", [ socket.userID ]); + const list = await R.findAll("proxy"); io.to(socket.userID).emit("proxyList", list.map(bean => bean.export())); timeLogger.print("Send Proxy List"); @@ -174,9 +172,7 @@ async function sendDockerHostList(socket) { const timeLogger = new TimeLogger(); let result = []; - let list = await R.find("docker_host", " user_id = ? ", [ - socket.userID, - ]); + let list = await R.findAll("docker_host"); for (let bean of list) { result.push(bean.toJSON()); diff --git a/server/docker.js b/server/docker.js index 7ca5da562..85bfb6f7b 100644 --- a/server/docker.js +++ b/server/docker.js @@ -23,7 +23,7 @@ class DockerHost { let bean; if (dockerHostID) { - bean = await R.findOne("docker_host", " id = ? AND user_id = ? ", [ dockerHostID, userID ]); + bean = await R.findOne("docker_host", " id = ? ", [ dockerHostID ]); if (!bean) { throw new Error("docker host not found"); @@ -46,11 +46,10 @@ class DockerHost { /** * Delete a Docker host * @param {number} dockerHostID ID of the Docker host to delete - * @param {number} userID ID of the user who created the Docker host * @returns {Promise} */ - static async delete(dockerHostID, userID) { - let bean = await R.findOne("docker_host", " id = ? AND user_id = ? ", [ dockerHostID, userID ]); + static async delete(dockerHostID) { + let bean = await R.findOne("docker_host", " id = ? ", [ dockerHostID ]); if (!bean) { throw new Error("docker host not found"); diff --git a/server/model/user.js b/server/model/user.js index 33277d485..da9e9c66f 100644 --- a/server/model/user.js +++ b/server/model/user.js @@ -43,6 +43,7 @@ class User extends BeanModel { */ static createJWT(user, jwtSecret) { return jwt.sign({ + userID: user.id, username: user.username, h: shake256(user.password, SHAKE256_LENGTH), }, jwtSecret); diff --git a/server/notification.js b/server/notification.js index fd8c23d67..667049e84 100644 --- a/server/notification.js +++ b/server/notification.js @@ -212,10 +212,7 @@ class Notification { let bean; if (notificationID) { - bean = await R.findOne("notification", " id = ? AND user_id = ? ", [ - notificationID, - userID, - ]); + bean = await R.findOne("notification", " id = ? ", [ notificationID ]); if (! bean) { throw new Error("notification not found"); @@ -241,14 +238,10 @@ class Notification { /** * Delete a notification * @param {number} notificationID ID of notification to delete - * @param {number} userID ID of user who created notification * @returns {Promise} */ - static async delete(notificationID, userID) { - let bean = await R.findOne("notification", " id = ? AND user_id = ? ", [ - notificationID, - userID, - ]); + static async delete(notificationID) { + let bean = await R.findOne("notification", " id = ? ", [ notificationID ]); if (! bean) { throw new Error("notification not found"); @@ -272,13 +265,10 @@ class Notification { /** * Apply the notification to every monitor * @param {number} notificationID ID of notification to apply - * @param {number} userID ID of user who created notification * @returns {Promise} */ -async function applyNotificationEveryMonitor(notificationID, userID) { - let monitors = await R.getAll("SELECT id FROM monitor WHERE user_id = ?", [ - userID - ]); +async function applyNotificationEveryMonitor(notificationID) { + let monitors = await R.getAll("SELECT id FROM monitor"); for (let i = 0; i < monitors.length; i++) { let checkNotification = await R.findOne("monitor_notification", " monitor_id = ? AND notification_id = ? ", [ diff --git a/server/proxy.js b/server/proxy.js index d38e3e4f1..1c8872304 100644 --- a/server/proxy.js +++ b/server/proxy.js @@ -22,7 +22,7 @@ class Proxy { let bean; if (proxyID) { - bean = await R.findOne("proxy", " id = ? AND user_id = ? ", [ proxyID, userID ]); + bean = await R.findOne("proxy", " id = ? ", [ proxyID ]); if (!bean) { throw new Error("proxy not found"); @@ -67,11 +67,10 @@ class Proxy { /** * Deletes proxy with given id and removes it from monitors * @param {number} proxyID ID of proxy to delete - * @param {number} userID ID of proxy owner * @returns {Promise} */ - static async delete(proxyID, userID) { - const bean = await R.findOne("proxy", " id = ? AND user_id = ? ", [ proxyID, userID ]); + static async delete(proxyID) { + const bean = await R.findOne("proxy", " id = ? ", [ proxyID ]); if (!bean) { throw new Error("proxy not found"); @@ -181,12 +180,11 @@ class Proxy { /** * Applies given proxy id to monitors * @param {number} proxyID ID of proxy to apply - * @param {number} userID ID of proxy owner * @returns {Promise} */ -async function applyProxyEveryMonitor(proxyID, userID) { +async function applyProxyEveryMonitor(proxyID) { // Find all monitors with id and proxy id - const monitors = await R.getAll("SELECT id, proxy_id FROM monitor WHERE user_id = ?", [ userID ]); + const monitors = await R.getAll("SELECT id, proxy_id FROM monitor"); // Update proxy id not match with given proxy id for (const monitor of monitors) { diff --git a/server/server.js b/server/server.js index b7025464b..9c1bf12d7 100644 --- a/server/server.js +++ b/server/server.js @@ -150,6 +150,7 @@ const { resetChrome } = require("./monitor-types/real-browser-monitor-type"); const { EmbeddedMariaDB } = require("./embedded-mariadb"); const { SetupDatabase } = require("./setup-database"); const { chartSocketHandler } = require("./socket-handlers/chart-socket-handler"); +const { sendUserList, getUser, saveUser } = require("./user"); app.use(express.json()); @@ -493,8 +494,8 @@ let needSetup = false; return; } - checkLogin(socket); - await doubleCheckPassword(socket, currentPassword); + await checkLogin(socket); + await doubleCheckPassword(socket.userID, currentPassword); let user = await R.findOne("user", " id = ? AND active = 1 ", [ socket.userID, @@ -543,8 +544,8 @@ let needSetup = false; return; } - checkLogin(socket); - await doubleCheckPassword(socket, currentPassword); + await checkLogin(socket); + await doubleCheckPassword(socket.userID, currentPassword); await R.exec("UPDATE `user` SET twofa_status = 1 WHERE id = ? ", [ socket.userID, @@ -576,8 +577,8 @@ let needSetup = false; return; } - checkLogin(socket); - await doubleCheckPassword(socket, currentPassword); + await checkLogin(socket); + await doubleCheckPassword(socket.userID, currentPassword); await TwoFA.disable2FA(socket.userID); log.info("auth", `Disabled 2FA token. IP=${clientIP}`); @@ -600,8 +601,8 @@ let needSetup = false; socket.on("verifyToken", async (token, currentPassword, callback) => { try { - checkLogin(socket); - await doubleCheckPassword(socket, currentPassword); + await checkLogin(socket); + await doubleCheckPassword(socket.userID, currentPassword); let user = await R.findOne("user", " id = ? AND active = 1 ", [ socket.userID, @@ -633,7 +634,7 @@ let needSetup = false; socket.on("twoFAStatus", async (callback) => { try { - checkLogin(socket); + await checkLogin(socket); let user = await R.findOne("user", " id = ? AND active = 1 ", [ socket.userID, @@ -668,10 +669,6 @@ let needSetup = false; throw new Error("Password is too weak. It should contain alphabetic and numeric characters. It must be at least 6 characters in length."); } - if ((await R.knex("user").count("id as count").first()).count !== 0) { - throw new Error("Uptime Kuma has been initialized. If you want to run setup again, please delete the database."); - } - let user = R.dispense("user"); user.username = username; user.password = await passwordHash.generate(password); @@ -697,10 +694,65 @@ let needSetup = false; // Auth Only API // *************************** + socket.on("getUsers", async callback => { + try { + await checkLogin(socket); + + const users = await sendUserList(socket); + + callback({ + ok: true, + users + }); + } catch (e) { + callback({ + ok: false, + msg: e.message, + }); + } + }); + + socket.on("getUser", async (userID, callback) => { + try { + await checkLogin(socket); + + const user = await getUser(userID); + + callback({ + ok: true, + user + }); + } catch (e) { + callback({ + ok: false, + msg: e.message, + }); + } + }); + + socket.on("saveUser", async (user, callback) => { + try { + await checkLogin(socket); + + await saveUser(socket, user); + await sendUserList(socket); + + callback({ + ok: true, + msg: "Saved Successfully.", + }); + } catch (e) { + callback({ + ok: false, + msg: e.message, + }); + } + }); + // Add a new monitor socket.on("add", async (monitor, callback) => { try { - checkLogin(socket); + await checkLogin(socket); let bean = R.dispense("monitor"); let notificationIDList = monitor.notificationIDList; @@ -759,14 +811,10 @@ let needSetup = false; socket.on("editMonitor", async (monitor, callback) => { try { let removeGroupChildren = false; - checkLogin(socket); + await checkLogin(socket); let bean = await R.findOne("monitor", " id = ? ", [ monitor.id ]); - if (bean.user_id !== socket.userID) { - throw new Error("Permission denied."); - } - // Check if Parent is Descendant (would cause endless loop) if (monitor.parent !== null) { const childIDs = await Monitor.getAllChildrenIDs(monitor.id); @@ -918,7 +966,7 @@ let needSetup = false; socket.on("getMonitorList", async (callback) => { try { - checkLogin(socket); + await checkLogin(socket); await server.sendMonitorList(socket); callback({ ok: true, @@ -934,14 +982,11 @@ let needSetup = false; socket.on("getMonitor", async (monitorID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); log.info("monitor", `Get Monitor: ${monitorID} User ID: ${socket.userID}`); - let monitor = await R.findOne("monitor", " id = ? AND user_id = ? ", [ - monitorID, - socket.userID, - ]); + let monitor = await R.findOne("monitor", " id = ? ", [ monitorID ]); const monitorData = [{ id: monitor.id, active: monitor.active }]; @@ -961,7 +1006,7 @@ let needSetup = false; socket.on("getMonitorBeats", async (monitorID, period, callback) => { try { - checkLogin(socket); + await checkLogin(socket); log.info("monitor", `Get Monitor Beats: ${monitorID} User ID: ${socket.userID}`); @@ -997,7 +1042,7 @@ let needSetup = false; // Start or Resume the monitor socket.on("resumeMonitor", async (monitorID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); await startMonitor(socket.userID, monitorID); await server.sendUpdateMonitorIntoList(socket, monitorID); @@ -1017,7 +1062,7 @@ let needSetup = false; socket.on("pauseMonitor", async (monitorID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); await pauseMonitor(socket.userID, monitorID); await server.sendUpdateMonitorIntoList(socket, monitorID); @@ -1037,7 +1082,7 @@ let needSetup = false; socket.on("deleteMonitor", async (monitorID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); log.info("manage", `Delete Monitor: ${monitorID} User ID: ${socket.userID}`); @@ -1048,10 +1093,7 @@ let needSetup = false; const startTime = Date.now(); - await R.exec("DELETE FROM monitor WHERE id = ? AND user_id = ? ", [ - monitorID, - socket.userID, - ]); + await R.exec("DELETE FROM monitor WHERE id = ? ", [ monitorID ]); // Fix #2880 apicache.clear(); @@ -1077,7 +1119,7 @@ let needSetup = false; socket.on("getTags", async (callback) => { try { - checkLogin(socket); + await checkLogin(socket); const list = await R.findAll("tag"); @@ -1096,7 +1138,7 @@ let needSetup = false; socket.on("addTag", async (tag, callback) => { try { - checkLogin(socket); + await checkLogin(socket); let bean = R.dispense("tag"); bean.name = tag.name; @@ -1118,7 +1160,7 @@ let needSetup = false; socket.on("editTag", async (tag, callback) => { try { - checkLogin(socket); + await checkLogin(socket); let bean = await R.findOne("tag", " id = ? ", [ tag.id ]); if (bean == null) { @@ -1150,7 +1192,7 @@ let needSetup = false; socket.on("deleteTag", async (tagID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); await R.exec("DELETE FROM tag WHERE id = ? ", [ tagID ]); @@ -1170,7 +1212,7 @@ let needSetup = false; socket.on("addMonitorTag", async (tagID, monitorID, value, callback) => { try { - checkLogin(socket); + await checkLogin(socket); await R.exec("INSERT INTO monitor_tag (tag_id, monitor_id, value) VALUES (?, ?, ?)", [ tagID, @@ -1194,7 +1236,7 @@ let needSetup = false; socket.on("editMonitorTag", async (tagID, monitorID, value, callback) => { try { - checkLogin(socket); + await checkLogin(socket); await R.exec("UPDATE monitor_tag SET value = ? WHERE tag_id = ? AND monitor_id = ?", [ value, @@ -1218,7 +1260,7 @@ let needSetup = false; socket.on("deleteMonitorTag", async (tagID, monitorID, value, callback) => { try { - checkLogin(socket); + await checkLogin(socket); await R.exec("DELETE FROM monitor_tag WHERE tag_id = ? AND monitor_id = ? AND value = ?", [ tagID, @@ -1306,9 +1348,9 @@ let needSetup = false; } }); - socket.on("changePassword", async (password, callback) => { + socket.on("changePassword", async (userID, password, callback) => { try { - checkLogin(socket); + await checkLogin(socket); if (!password.newPassword) { throw new Error("Invalid new password"); @@ -1318,7 +1360,7 @@ let needSetup = false; throw new Error("Password is too weak. It should contain alphabetic and numeric characters. It must be at least 6 characters in length."); } - let user = await doubleCheckPassword(socket, password.currentPassword); + let user = await doubleCheckPassword(userID, password.currentPassword); await user.resetPassword(password.newPassword); server.disconnectAllSocketClients(user.id, socket.id); @@ -1340,7 +1382,7 @@ let needSetup = false; socket.on("getSettings", async (callback) => { try { - checkLogin(socket); + await checkLogin(socket); const data = await getSettings("general"); if (!data.serverTimezone) { @@ -1362,7 +1404,7 @@ let needSetup = false; socket.on("setSettings", async (data, currentPassword, callback) => { try { - checkLogin(socket); + await checkLogin(socket); // If currently is disabled auth, don't need to check // Disabled Auth + Want to Disable Auth => No Check @@ -1426,7 +1468,7 @@ let needSetup = false; // Add or Edit socket.on("addNotification", async (notification, notificationID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); let notificationBean = await Notification.save(notification, notificationID, socket.userID); await sendNotificationList(socket); @@ -1448,7 +1490,7 @@ let needSetup = false; socket.on("deleteNotification", async (notificationID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); await Notification.delete(notificationID, socket.userID); await sendNotificationList(socket); @@ -1469,7 +1511,7 @@ let needSetup = false; socket.on("testNotification", async (notification, callback) => { try { - checkLogin(socket); + await checkLogin(socket); let msg = await Notification.send(notification, notification.name + " Testing"); @@ -1490,7 +1532,7 @@ let needSetup = false; socket.on("checkApprise", async (callback) => { try { - checkLogin(socket); + await checkLogin(socket); callback(Notification.checkApprise()); } catch (e) { callback(false); @@ -1499,7 +1541,7 @@ let needSetup = false; socket.on("clearEvents", async (monitorID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); log.info("manage", `Clear Events Monitor: ${monitorID} User ID: ${socket.userID}`); @@ -1523,7 +1565,7 @@ let needSetup = false; socket.on("clearHeartbeats", async (monitorID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); log.info("manage", `Clear Heartbeats Monitor: ${monitorID} User ID: ${socket.userID}`); @@ -1547,7 +1589,7 @@ let needSetup = false; socket.on("clearStatistics", async (callback) => { try { - checkLogin(socket); + await checkLogin(socket); log.info("manage", `Clear Statistics User ID: ${socket.userID}`); @@ -1654,24 +1696,6 @@ async function updateMonitorNotification(monitorID, notificationIDList) { } } -/** - * Check if a given user owns a specific monitor - * @param {number} userID ID of user to check - * @param {number} monitorID ID of monitor to check - * @returns {Promise} - * @throws {Error} The specified user does not own the monitor - */ -async function checkOwner(userID, monitorID) { - let row = await R.getRow("SELECT id FROM monitor WHERE id = ? AND user_id = ? ", [ - monitorID, - userID, - ]); - - if (! row) { - throw new Error("You do not own this monitor."); - } -} - /** * Function called after user login * This function is used to send the heartbeat list of a monitor. @@ -1693,6 +1717,7 @@ async function afterLogin(socket, user) { sendAPIKeyList(socket), sendRemoteBrowserList(socket), sendMonitorTypeList(socket), + sendUserList(socket), ]); await StatusPage.sendStatusPageList(io, socket); @@ -1755,14 +1780,9 @@ async function initDatabase(testMode = false) { * @returns {Promise} */ async function startMonitor(userID, monitorID) { - await checkOwner(userID, monitorID); - log.info("manage", `Resume Monitor: ${monitorID} User ID: ${userID}`); - await R.exec("UPDATE monitor SET active = 1 WHERE id = ? AND user_id = ? ", [ - monitorID, - userID, - ]); + await R.exec("UPDATE monitor SET active = 1 WHERE id = ? ", [ monitorID ]); let monitor = await R.findOne("monitor", " id = ? ", [ monitorID, @@ -1793,14 +1813,9 @@ async function restartMonitor(userID, monitorID) { * @returns {Promise} */ async function pauseMonitor(userID, monitorID) { - await checkOwner(userID, monitorID); - log.info("manage", `Pause Monitor: ${monitorID} User ID: ${userID}`); - await R.exec("UPDATE monitor SET active = 0 WHERE id = ? AND user_id = ? ", [ - monitorID, - userID, - ]); + await R.exec("UPDATE monitor SET active = 0 WHERE id = ? ", [ monitorID ]); if (monitorID in server.monitorList) { await server.monitorList[monitorID].stop(); diff --git a/server/socket-handlers/api-key-socket-handler.js b/server/socket-handlers/api-key-socket-handler.js index d49ac086b..54b5afb1b 100644 --- a/server/socket-handlers/api-key-socket-handler.js +++ b/server/socket-handlers/api-key-socket-handler.js @@ -17,7 +17,7 @@ module.exports.apiKeySocketHandler = (socket) => { // Add a new api key socket.on("addAPIKey", async (key, callback) => { try { - checkLogin(socket); + await checkLogin(socket); let clearKey = nanoid(40); let hashedKey = await passwordHash.generate(clearKey); @@ -54,7 +54,7 @@ module.exports.apiKeySocketHandler = (socket) => { socket.on("getAPIKeyList", async (callback) => { try { - checkLogin(socket); + await checkLogin(socket); await sendAPIKeyList(socket); callback({ ok: true, @@ -70,14 +70,11 @@ module.exports.apiKeySocketHandler = (socket) => { socket.on("deleteAPIKey", async (keyID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); log.debug("apikeys", `Deleted API Key: ${keyID} User ID: ${socket.userID}`); - await R.exec("DELETE FROM api_key WHERE id = ? AND user_id = ? ", [ - keyID, - socket.userID, - ]); + await R.exec("DELETE FROM api_key WHERE id = ? ", [ keyID ]); apicache.clear(); @@ -99,7 +96,7 @@ module.exports.apiKeySocketHandler = (socket) => { socket.on("disableAPIKey", async (keyID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); log.debug("apikeys", `Disabled Key: ${keyID} User ID: ${socket.userID}`); @@ -127,7 +124,7 @@ module.exports.apiKeySocketHandler = (socket) => { socket.on("enableAPIKey", async (keyID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); log.debug("apikeys", `Enabled Key: ${keyID} User ID: ${socket.userID}`); diff --git a/server/socket-handlers/cloudflared-socket-handler.js b/server/socket-handlers/cloudflared-socket-handler.js index 809191fe8..9508aeb6f 100644 --- a/server/socket-handlers/cloudflared-socket-handler.js +++ b/server/socket-handlers/cloudflared-socket-handler.js @@ -36,7 +36,7 @@ module.exports.cloudflaredSocketHandler = (socket) => { socket.on(prefix + "join", async () => { try { - checkLogin(socket); + await checkLogin(socket); socket.join("cloudflared"); io.to(socket.userID).emit(prefix + "installed", cloudflared.checkInstalled()); io.to(socket.userID).emit(prefix + "running", cloudflared.running); @@ -46,14 +46,14 @@ module.exports.cloudflaredSocketHandler = (socket) => { socket.on(prefix + "leave", async () => { try { - checkLogin(socket); + await checkLogin(socket); socket.leave("cloudflared"); } catch (error) { } }); socket.on(prefix + "start", async (token) => { try { - checkLogin(socket); + await checkLogin(socket); if (token && typeof token === "string") { await setSetting("cloudflaredTunnelToken", token); cloudflared.token = token; @@ -66,7 +66,7 @@ module.exports.cloudflaredSocketHandler = (socket) => { socket.on(prefix + "stop", async (currentPassword, callback) => { try { - checkLogin(socket); + await checkLogin(socket); const disabledAuth = await setting("disableAuth"); if (!disabledAuth) { await doubleCheckPassword(socket, currentPassword); @@ -82,7 +82,7 @@ module.exports.cloudflaredSocketHandler = (socket) => { socket.on(prefix + "removeToken", async () => { try { - checkLogin(socket); + await checkLogin(socket); await setSetting("cloudflaredTunnelToken", ""); } catch (error) { } }); diff --git a/server/socket-handlers/database-socket-handler.js b/server/socket-handlers/database-socket-handler.js index 33f8f3195..fb92f2d7a 100644 --- a/server/socket-handlers/database-socket-handler.js +++ b/server/socket-handlers/database-socket-handler.js @@ -11,7 +11,7 @@ module.exports.databaseSocketHandler = (socket) => { // Post or edit incident socket.on("getDatabaseSize", async (callback) => { try { - checkLogin(socket); + await checkLogin(socket); callback({ ok: true, size: await Database.getSize(), @@ -26,7 +26,7 @@ module.exports.databaseSocketHandler = (socket) => { socket.on("shrinkDatabase", async (callback) => { try { - checkLogin(socket); + await checkLogin(socket); await Database.shrink(); callback({ ok: true, diff --git a/server/socket-handlers/docker-socket-handler.js b/server/socket-handlers/docker-socket-handler.js index 95a60bcd3..c483b253c 100644 --- a/server/socket-handlers/docker-socket-handler.js +++ b/server/socket-handlers/docker-socket-handler.js @@ -11,7 +11,7 @@ const { log } = require("../../src/util"); module.exports.dockerSocketHandler = (socket) => { socket.on("addDockerHost", async (dockerHost, dockerHostID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); let dockerHostBean = await DockerHost.save(dockerHost, dockerHostID, socket.userID); await sendDockerHostList(socket); @@ -33,7 +33,7 @@ module.exports.dockerSocketHandler = (socket) => { socket.on("deleteDockerHost", async (dockerHostID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); await DockerHost.delete(dockerHostID, socket.userID); await sendDockerHostList(socket); @@ -54,7 +54,7 @@ module.exports.dockerSocketHandler = (socket) => { socket.on("testDockerHost", async (dockerHost, callback) => { try { - checkLogin(socket); + await checkLogin(socket); let amount = await DockerHost.testDockerHost(dockerHost); let msg; diff --git a/server/socket-handlers/general-socket-handler.js b/server/socket-handlers/general-socket-handler.js index b996efe7b..1b1e60f04 100644 --- a/server/socket-handlers/general-socket-handler.js +++ b/server/socket-handlers/general-socket-handler.js @@ -38,7 +38,7 @@ function getGameList() { module.exports.generalSocketHandler = (socket, server) => { socket.on("initServerTimezone", async (timezone) => { try { - checkLogin(socket); + await checkLogin(socket); log.debug("generalSocketHandler", "Timezone: " + timezone); await Settings.set("initServerTimezone", true); await server.setTimezone(timezone); diff --git a/server/socket-handlers/maintenance-socket-handler.js b/server/socket-handlers/maintenance-socket-handler.js index 7de13fe57..a38943c23 100644 --- a/server/socket-handlers/maintenance-socket-handler.js +++ b/server/socket-handlers/maintenance-socket-handler.js @@ -15,7 +15,7 @@ module.exports.maintenanceSocketHandler = (socket) => { // Add a new maintenance socket.on("addMaintenance", async (maintenance, callback) => { try { - checkLogin(socket); + await checkLogin(socket); log.debug("maintenance", maintenance); @@ -46,14 +46,10 @@ module.exports.maintenanceSocketHandler = (socket) => { // Edit a maintenance socket.on("editMaintenance", async (maintenance, callback) => { try { - checkLogin(socket); + await checkLogin(socket); let bean = server.getMaintenance(maintenance.id); - if (bean.user_id !== socket.userID) { - throw new Error("Permission denied."); - } - await Maintenance.jsonToBean(bean, maintenance); await R.store(bean); await bean.run(true); @@ -78,7 +74,7 @@ module.exports.maintenanceSocketHandler = (socket) => { // Add a new monitor_maintenance socket.on("addMonitorMaintenance", async (maintenanceID, monitors, callback) => { try { - checkLogin(socket); + await checkLogin(socket); await R.exec("DELETE FROM monitor_maintenance WHERE maintenance_id = ?", [ maintenanceID @@ -113,7 +109,7 @@ module.exports.maintenanceSocketHandler = (socket) => { // Add a new monitor_maintenance socket.on("addMaintenanceStatusPage", async (maintenanceID, statusPages, callback) => { try { - checkLogin(socket); + await checkLogin(socket); await R.exec("DELETE FROM maintenance_status_page WHERE maintenance_id = ?", [ maintenanceID @@ -147,14 +143,11 @@ module.exports.maintenanceSocketHandler = (socket) => { socket.on("getMaintenance", async (maintenanceID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); log.debug("maintenance", `Get Maintenance: ${maintenanceID} User ID: ${socket.userID}`); - let bean = await R.findOne("maintenance", " id = ? AND user_id = ? ", [ - maintenanceID, - socket.userID, - ]); + let bean = await R.findOne("maintenance", " id = ? ", [ maintenanceID ]); callback({ ok: true, @@ -171,7 +164,7 @@ module.exports.maintenanceSocketHandler = (socket) => { socket.on("getMaintenanceList", async (callback) => { try { - checkLogin(socket); + await checkLogin(socket); await server.sendMaintenanceList(socket); callback({ ok: true, @@ -187,7 +180,7 @@ module.exports.maintenanceSocketHandler = (socket) => { socket.on("getMonitorMaintenance", async (maintenanceID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); log.debug("maintenance", `Get Monitors for Maintenance: ${maintenanceID} User ID: ${socket.userID}`); @@ -211,7 +204,7 @@ module.exports.maintenanceSocketHandler = (socket) => { socket.on("getMaintenanceStatusPage", async (maintenanceID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); log.debug("maintenance", `Get Status Pages for Maintenance: ${maintenanceID} User ID: ${socket.userID}`); @@ -235,7 +228,7 @@ module.exports.maintenanceSocketHandler = (socket) => { socket.on("deleteMaintenance", async (maintenanceID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); log.debug("maintenance", `Delete Maintenance: ${maintenanceID} User ID: ${socket.userID}`); @@ -244,10 +237,7 @@ module.exports.maintenanceSocketHandler = (socket) => { delete server.maintenanceList[maintenanceID]; } - await R.exec("DELETE FROM maintenance WHERE id = ? AND user_id = ? ", [ - maintenanceID, - socket.userID, - ]); + await R.exec("DELETE FROM maintenance WHERE id = ? ", [ maintenanceID ]); apicache.clear(); @@ -269,7 +259,7 @@ module.exports.maintenanceSocketHandler = (socket) => { socket.on("pauseMaintenance", async (maintenanceID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); log.debug("maintenance", `Pause Maintenance: ${maintenanceID} User ID: ${socket.userID}`); @@ -303,7 +293,7 @@ module.exports.maintenanceSocketHandler = (socket) => { socket.on("resumeMaintenance", async (maintenanceID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); log.debug("maintenance", `Resume Maintenance: ${maintenanceID} User ID: ${socket.userID}`); diff --git a/server/socket-handlers/proxy-socket-handler.js b/server/socket-handlers/proxy-socket-handler.js index 9e80371d7..800977a7f 100644 --- a/server/socket-handlers/proxy-socket-handler.js +++ b/server/socket-handlers/proxy-socket-handler.js @@ -12,7 +12,7 @@ const server = UptimeKumaServer.getInstance(); module.exports.proxySocketHandler = (socket) => { socket.on("addProxy", async (proxy, proxyID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); const proxyBean = await Proxy.save(proxy, proxyID, socket.userID); await sendProxyList(socket); @@ -39,7 +39,7 @@ module.exports.proxySocketHandler = (socket) => { socket.on("deleteProxy", async (proxyID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); await Proxy.delete(proxyID, socket.userID); await sendProxyList(socket); diff --git a/server/socket-handlers/status-page-socket-handler.js b/server/socket-handlers/status-page-socket-handler.js index 952ec2fa7..15457d31d 100644 --- a/server/socket-handlers/status-page-socket-handler.js +++ b/server/socket-handlers/status-page-socket-handler.js @@ -18,7 +18,7 @@ module.exports.statusPageSocketHandler = (socket) => { // Post or edit incident socket.on("postIncident", async (slug, incident, callback) => { try { - checkLogin(socket); + await checkLogin(socket); let statusPageID = await StatusPage.slugToID(slug); @@ -71,7 +71,7 @@ module.exports.statusPageSocketHandler = (socket) => { socket.on("unpinIncident", async (slug, callback) => { try { - checkLogin(socket); + await checkLogin(socket); let statusPageID = await StatusPage.slugToID(slug); @@ -92,7 +92,7 @@ module.exports.statusPageSocketHandler = (socket) => { socket.on("getStatusPage", async (slug, callback) => { try { - checkLogin(socket); + await checkLogin(socket); let statusPage = await R.findOne("status_page", " slug = ? ", [ slug @@ -118,7 +118,7 @@ module.exports.statusPageSocketHandler = (socket) => { // imgDataUrl Only Accept PNG! socket.on("saveStatusPage", async (slug, config, imgDataUrl, publicGroupList, callback) => { try { - checkLogin(socket); + await checkLogin(socket); // Save Config let statusPage = await R.findOne("status_page", " slug = ? ", [ @@ -264,7 +264,7 @@ module.exports.statusPageSocketHandler = (socket) => { // Add a new status page socket.on("addStatusPage", async (title, slug, callback) => { try { - checkLogin(socket); + await checkLogin(socket); title = title?.trim(); slug = slug?.trim(); @@ -313,7 +313,7 @@ module.exports.statusPageSocketHandler = (socket) => { const server = UptimeKumaServer.getInstance(); try { - checkLogin(socket); + await checkLogin(socket); let statusPageID = await StatusPage.slugToID(slug); diff --git a/server/uptime-kuma-server.js b/server/uptime-kuma-server.js index a04e6bd49..99172b5a5 100644 --- a/server/uptime-kuma-server.js +++ b/server/uptime-kuma-server.js @@ -204,7 +204,7 @@ class UptimeKumaServer { * @returns {Promise} List of monitors */ async sendMonitorList(socket) { - let list = await this.getMonitorJSONList(socket.userID); + let list = await this.getMonitorJSONList(); this.io.to(socket.userID).emit("monitorList", list); return list; } @@ -231,25 +231,21 @@ class UptimeKumaServer { } /** - * Get a list of monitors for the given user. - * @param {string} userID - The ID of the user to get monitors for. + * Get a list of monitors. * @param {number} monitorID - The ID of monitor for. * @returns {Promise} A promise that resolves to an object with monitor IDs as keys and monitor objects as values. * * Generated by Trelent */ - async getMonitorJSONList(userID, monitorID = null) { - - let query = " user_id = ? "; - let queryParams = [ userID ]; + async getMonitorJSONList(monitorID = null) { + let monitorList = []; if (monitorID) { - query += "AND id = ? "; - queryParams.push(monitorID); + monitorList = await R.find("monitor", "id = ? ORDER BY weight DESC, name", [ monitorID ]); + } else { + monitorList = await R.findAll("monitor", "ORDER BY weight DESC, name"); } - let monitorList = await R.find("monitor", query + "ORDER BY weight DESC, name", queryParams); - const monitorData = monitorList.map(monitor => ({ id: monitor.id, active: monitor.active, diff --git a/server/user.js b/server/user.js new file mode 100644 index 000000000..4f54fa668 --- /dev/null +++ b/server/user.js @@ -0,0 +1,84 @@ +const { TimeLogger } = require("../src/util"); +const { R } = require("redbean-node"); +const { UptimeKumaServer } = require("./uptime-kuma-server"); +const server = UptimeKumaServer.getInstance(); +const io = server.io; + +/** + * Send list of users to client + * @param {Socket} socket Socket.io socket instance + * @returns {Promise} list of users + */ +async function sendUserList(socket) { + const timeLogger = new TimeLogger(); + const userList = await R.getAll("SELECT id, username, active FROM user"); + + io.to(socket.userID).emit("userList", userList); + timeLogger.print("Send User List"); + + return userList; +} + +/** + * Fetch specified user + * @param {number} userID ID of user to retrieve + * @returns {Promise} User + */ +async function getUser(userID) { + const timeLogger = new TimeLogger(); + + const user = await R.getRow( + "SELECT id, username, active FROM user WHERE id = ? ", + [ userID ] + ); + + if (!user) { + throw new Error("User not found"); + } + + timeLogger.print(`Get user ${userID}`); + + return user; +} + +/** + * Saves and updates given user entity + * @param {Socket} socket Socket.io socket instance + * @param {object} user user to update + * @returns {Promise} + */ +async function saveUser(socket, user) { + const timeLogger = new TimeLogger(); + const { id, username, active } = user; + + const bean = await R.findOne("user", " id = ? ", [ id ]); + + if (!bean) { + throw new Error("User not found"); + } + + if (username) { + bean.username = username; + } + if (active !== undefined) { + bean.active = active; + } + + await R.store(bean); + + io.to(socket.userID).emit("saveUser", bean); + + // If user is deactivated, disconnect his sockets + if (!bean.active) { + const roomId = typeof id === "number" ? id : parseInt(id, 10); + io.in(roomId).disconnectSockets(); + } + + timeLogger.print(`Save user ${user.id}`); +} + +module.exports = { + sendUserList, + getUser, + saveUser +}; diff --git a/server/util-server.js b/server/util-server.js index d4a37970d..cd049ad31 100644 --- a/server/util-server.js +++ b/server/util-server.js @@ -797,28 +797,28 @@ exports.allowAllOrigin = (res) => { * @returns {void} * @throws The user is not logged in */ -exports.checkLogin = (socket) => { - if (!socket.userID) { +exports.checkLogin = async (socket) => { + const user = await R.findOne("user", " id = ? AND active = 1 ", [ socket.userID ]); + + if (!user) { throw new Error("You are not logged in."); } }; /** * For logged-in users, double-check the password - * @param {Socket} socket Socket.io instance + * @param {number} userID ID of user to check * @param {string} currentPassword Password to validate * @returns {Promise} User * @throws The current password is not a string * @throws The provided password is not correct */ -exports.doubleCheckPassword = async (socket, currentPassword) => { +exports.doubleCheckPassword = async (userID, currentPassword) => { if (typeof currentPassword !== "string") { throw new Error("Wrong data type?"); } - let user = await R.findOne("user", " id = ? AND active = 1 ", [ - socket.userID, - ]); + let user = await R.findOne("user", " id = ? ", [ userID ]); if (!user || !passwordHash.verify(currentPassword, user.password)) { throw new Error("Incorrect current password"); diff --git a/src/components/settings/Security.vue b/src/components/settings/Security.vue index 5d8aed85b..3d900cee4 100644 --- a/src/components/settings/Security.vue +++ b/src/components/settings/Security.vue @@ -171,7 +171,7 @@ export default { } else { this.$root .getSocket() - .emit("changePassword", this.password, (res) => { + .emit("changePassword", this.$root.userID, this.password, (res) => { this.$root.toastRes(res); if (res.ok) { this.password.currentPassword = ""; diff --git a/src/components/settings/Users/AddUser.vue b/src/components/settings/Users/AddUser.vue new file mode 100644 index 000000000..3f0eaf14e --- /dev/null +++ b/src/components/settings/Users/AddUser.vue @@ -0,0 +1,94 @@ + + + diff --git a/src/components/settings/Users/EditUser.vue b/src/components/settings/Users/EditUser.vue new file mode 100644 index 000000000..4e36f045b --- /dev/null +++ b/src/components/settings/Users/EditUser.vue @@ -0,0 +1,206 @@ + + + diff --git a/src/components/settings/Users/Users.vue b/src/components/settings/Users/Users.vue new file mode 100644 index 000000000..02d7e5e9c --- /dev/null +++ b/src/components/settings/Users/Users.vue @@ -0,0 +1,155 @@ + + + + + diff --git a/src/components/settings/Users/routes.js b/src/components/settings/Users/routes.js new file mode 100644 index 000000000..6d3517455 --- /dev/null +++ b/src/components/settings/Users/routes.js @@ -0,0 +1,29 @@ +import { h } from "vue"; +import { RouterView } from "vue-router"; + +// Needed for settings enter/leave CSS animation +const AnimatedRouterView = () => h("div", [ h(RouterView) ]); +AnimatedRouterView.displayName = "AnimatedRouterView"; + +export default { + path: "users", + component: AnimatedRouterView, + children: [ + { + path: "", + name: "settings.users", + component: () => import("./Users.vue") + }, + { + path: "add", + name: "settings.users.add", + component: () => import("./AddUser.vue") + }, + { + path: "edit/:id", + name: "settings.users.edit", + props: true, + component: () => import("./EditUser.vue") + }, + ] +}; diff --git a/src/icon.js b/src/icon.js index 7bdfe1ca0..b40482783 100644 --- a/src/icon.js +++ b/src/icon.js @@ -50,6 +50,8 @@ import { faInfoCircle, faClone, faCertificate, + faUserSlash, + faUserCheck, } from "@fortawesome/free-solid-svg-icons"; library.add( @@ -97,6 +99,8 @@ library.add( faInfoCircle, faClone, faCertificate, + faUserSlash, + faUserCheck, ); export { FontAwesomeIcon }; diff --git a/src/lang/en.json b/src/lang/en.json index b6449371b..e63db3400 100644 --- a/src/lang/en.json +++ b/src/lang/en.json @@ -1075,6 +1075,13 @@ "Can be found on:": "Can be found on: {0}", "The phone number of the recipient in E.164 format.": "The phone number of the recipient in E.164 format.", "Either a text sender ID or a phone number in E.164 format if you want to be able to receive replies.": "Either a text sender ID or a phone number in E.164 format if you want to be able to receive replies.", + "Users": "Users", + "Add New User": "Add New User", + "confirmDisableUserMsg": "Are you sure you want to disable this user? The user will not be able to login anymore.", + "Create an admin account": "Create an admin account", + "Identity": "Identity", + "Update Username": "Update Username", + "Permissions": "Permissions", "RabbitMQ Nodes": "RabbitMQ Management Nodes", "rabbitmqNodesDescription": "Enter the URL for the RabbitMQ management nodes including protocol and port. Example: {0}", "rabbitmqNodesRequired": "Please set the nodes for this monitor.", @@ -1126,4 +1133,4 @@ "Clear Form": "Clear Form", "pause": "Pause", "Manual": "Manual" -} +} \ No newline at end of file diff --git a/src/layouts/Layout.vue b/src/layouts/Layout.vue index e93a5159e..82ab098cd 100644 --- a/src/layouts/Layout.vue +++ b/src/layouts/Layout.vue @@ -1,6 +1,6 @@