From 4035793762b5fd58a08c3100c7b5142a1417a55a Mon Sep 17 00:00:00 2001 From: M1CK431 Date: Mon, 31 Jul 2023 23:08:03 +0200 Subject: [PATCH 1/6] API: make all resources users-agnostic --- server/client.js | 10 ++-- server/docker.js | 7 ++- server/notification.js | 20 ++------ server/proxy.js | 12 ++--- server/server.js | 46 ++----------------- .../socket-handlers/api-key-socket-handler.js | 5 +- .../maintenance-socket-handler.js | 14 +----- server/uptime-kuma-server.js | 11 ++--- 8 files changed, 27 insertions(+), 98 deletions(-) diff --git a/server/client.js b/server/client.js index 2e3bd43b7b..8db5bc5f14 100644 --- a/server/client.js +++ b/server/client.js @@ -18,9 +18,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(); @@ -105,7 +103,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"); @@ -171,9 +169,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 1a8c0a5d25..3a9bba343a 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/notification.js b/server/notification.js index 570c440dfd..f7c04a58b3 100644 --- a/server/notification.js +++ b/server/notification.js @@ -159,10 +159,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"); @@ -188,14 +185,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"); @@ -219,13 +212,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 660b9b411d..612848ca50 100644 --- a/server/proxy.js +++ b/server/proxy.js @@ -21,7 +21,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 proxyID - * @param userID * @return {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"); @@ -173,12 +172,11 @@ class Proxy { * Applies given proxy id to monitors * * @param proxyID - * @param userID * @return {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 d36ca662ed..4b0dec1589 100644 --- a/server/server.js +++ b/server/server.js @@ -693,10 +693,6 @@ let needSetup = false; 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); @@ -839,10 +835,7 @@ let needSetup = false; log.info("monitor", `Get Monitor: ${monitorID} User ID: ${socket.userID}`); - let bean = await R.findOne("monitor", " id = ? AND user_id = ? ", [ - monitorID, - socket.userID, - ]); + let bean = await R.findOne("monitor", " id = ? ", [ monitorID ]); callback({ ok: true, @@ -941,10 +934,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(); @@ -1660,24 +1650,6 @@ async function updateMonitorNotification(monitorID, notificationIDList) { } } -/** - * Check if a given user owns a specific monitor - * @param {number} userID - * @param {number} monitorID - * @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. @@ -1768,14 +1740,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, @@ -1806,14 +1773,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) { 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 69b0b60de8..8e07df79e4 100644 --- a/server/socket-handlers/api-key-socket-handler.js +++ b/server/socket-handlers/api-key-socket-handler.js @@ -72,10 +72,7 @@ module.exports.apiKeySocketHandler = (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(); diff --git a/server/socket-handlers/maintenance-socket-handler.js b/server/socket-handlers/maintenance-socket-handler.js index ff5bb0fcfc..f5c7fa83b4 100644 --- a/server/socket-handlers/maintenance-socket-handler.js +++ b/server/socket-handlers/maintenance-socket-handler.js @@ -48,10 +48,6 @@ module.exports.maintenanceSocketHandler = (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); @@ -146,10 +142,7 @@ module.exports.maintenanceSocketHandler = (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, @@ -239,10 +232,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(); diff --git a/server/uptime-kuma-server.js b/server/uptime-kuma-server.js index 7817c9e1c3..001b4b8b90 100644 --- a/server/uptime-kuma-server.js +++ b/server/uptime-kuma-server.js @@ -127,24 +127,21 @@ class UptimeKumaServer { * @returns {Object} 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; } /** - * 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. * @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) { + async getMonitorJSONList() { let result = {}; - let monitorList = await R.find("monitor", " user_id = ? ORDER BY weight DESC, name", [ - userID, - ]); + let monitorList = await R.findAll("monitor", "ORDER BY weight DESC, name"); for (let monitor of monitorList) { result[monitor.id] = await monitor.toJSON(); From b4bb715a6f1cce486aef22b7d1b95590819cb18b Mon Sep 17 00:00:00 2001 From: M1CK431 Date: Tue, 1 Aug 2023 00:23:55 +0200 Subject: [PATCH 2/6] API: add basic multiple admin users --- server/server.js | 74 ++++++++++++++++++++++++++++++++++------ server/user.js | 78 +++++++++++++++++++++++++++++++++++++++++++ server/util-server.js | 8 ++--- 3 files changed, 145 insertions(+), 15 deletions(-) create mode 100644 server/user.js diff --git a/server/server.js b/server/server.js index 4b0dec1589..440ac8d127 100644 --- a/server/server.js +++ b/server/server.js @@ -157,6 +157,7 @@ const { Settings } = require("./settings"); const { CacheableDnsHttpAgent } = require("./cacheable-dns-http-agent"); const apicache = require("./modules/apicache"); const { resetChrome } = require("./monitor-types/real-browser-monitor-type"); +const { sendUserList, getUser, saveUser } = require("./user"); app.use(express.json()); @@ -358,6 +359,7 @@ let needSetup = false; callback({ ok: true, token: jwt.sign({ + userID: user.id, username: data.username, }, server.jwtSecret), }); @@ -434,7 +436,7 @@ let needSetup = false; } checkLogin(socket); - await doubleCheckPassword(socket, currentPassword); + await doubleCheckPassword(socket.userID, currentPassword); let user = await R.findOne("user", " id = ? AND active = 1 ", [ socket.userID, @@ -483,7 +485,7 @@ let needSetup = false; } checkLogin(socket); - await doubleCheckPassword(socket, currentPassword); + await doubleCheckPassword(socket.userID, currentPassword); await R.exec("UPDATE `user` SET twofa_status = 1 WHERE id = ? ", [ socket.userID, @@ -515,7 +517,7 @@ let needSetup = false; } checkLogin(socket); - await doubleCheckPassword(socket, currentPassword); + await doubleCheckPassword(socket.userID, currentPassword); await TwoFA.disable2FA(socket.userID); log.info("auth", `Disabled 2FA token. IP=${clientIP}`); @@ -538,7 +540,7 @@ let needSetup = false; socket.on("verifyToken", async (token, currentPassword, callback) => { try { checkLogin(socket); - await doubleCheckPassword(socket, currentPassword); + await doubleCheckPassword(socket.userID, currentPassword); let user = await R.findOne("user", " id = ? AND active = 1 ", [ socket.userID, @@ -604,10 +606,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.count("user")) !== 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 = passwordHash.generate(password); @@ -632,6 +630,61 @@ let needSetup = false; // Auth Only API // *************************** + socket.on("getUsers", async callback => { + try { + 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 { + 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 { + 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 { @@ -1122,7 +1175,7 @@ let needSetup = false; } }); - socket.on("changePassword", async (password, callback) => { + socket.on("changePassword", async (userID, password, callback) => { try { checkLogin(socket); @@ -1134,7 +1187,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); callback({ @@ -1668,6 +1721,7 @@ async function afterLogin(socket, user) { sendProxyList(socket); sendDockerHostList(socket); sendAPIKeyList(socket); + sendUserList(socket); await sleep(500); diff --git a/server/user.js b/server/user.js new file mode 100644 index 0000000000..5b8dfa09b3 --- /dev/null +++ b/server/user.js @@ -0,0 +1,78 @@ +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); + + timeLogger.print(`Save user ${user.id}`); +} + +module.exports = { + sendUserList, + getUser, + saveUser +}; diff --git a/server/util-server.js b/server/util-server.js index 8354b56094..d6366a379c 100644 --- a/server/util-server.js +++ b/server/util-server.js @@ -810,18 +810,16 @@ exports.checkLogin = (socket) => { /** * 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 * @returns {Promise} */ -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"); From 7b4f98d947adb60e0c859309aded42855a058e4d Mon Sep 17 00:00:00 2001 From: M1CK431 Date: Sat, 12 Aug 2023 22:15:50 +0200 Subject: [PATCH 3/6] API: ensure user is active in checkLogin helper --- server/server.js | 68 +++++++++---------- .../socket-handlers/api-key-socket-handler.js | 10 +-- .../cloudflared-socket-handler.js | 10 +-- .../database-socket-handler.js | 4 +- .../socket-handlers/docker-socket-handler.js | 6 +- .../socket-handlers/general-socket-handler.js | 2 +- .../maintenance-socket-handler.js | 22 +++--- .../socket-handlers/proxy-socket-handler.js | 4 +- .../status-page-socket-handler.js | 12 ++-- server/util-server.js | 6 +- 10 files changed, 73 insertions(+), 71 deletions(-) diff --git a/server/server.js b/server/server.js index 440ac8d127..511d92d1d3 100644 --- a/server/server.js +++ b/server/server.js @@ -435,7 +435,7 @@ let needSetup = false; return; } - checkLogin(socket); + await checkLogin(socket); await doubleCheckPassword(socket.userID, currentPassword); let user = await R.findOne("user", " id = ? AND active = 1 ", [ @@ -484,7 +484,7 @@ let needSetup = false; return; } - checkLogin(socket); + await checkLogin(socket); await doubleCheckPassword(socket.userID, currentPassword); await R.exec("UPDATE `user` SET twofa_status = 1 WHERE id = ? ", [ @@ -516,7 +516,7 @@ let needSetup = false; return; } - checkLogin(socket); + await checkLogin(socket); await doubleCheckPassword(socket.userID, currentPassword); await TwoFA.disable2FA(socket.userID); @@ -539,7 +539,7 @@ let needSetup = false; socket.on("verifyToken", async (token, currentPassword, callback) => { try { - checkLogin(socket); + await checkLogin(socket); await doubleCheckPassword(socket.userID, currentPassword); let user = await R.findOne("user", " id = ? AND active = 1 ", [ @@ -571,7 +571,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, @@ -632,7 +632,7 @@ let needSetup = false; socket.on("getUsers", async callback => { try { - checkLogin(socket); + await checkLogin(socket); const users = await sendUserList(socket); @@ -650,7 +650,7 @@ let needSetup = false; socket.on("getUser", async (userID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); const user = await getUser(userID); @@ -668,7 +668,7 @@ let needSetup = false; socket.on("saveUser", async (user, callback) => { try { - checkLogin(socket); + await checkLogin(socket); await saveUser(socket, user); await sendUserList(socket); @@ -688,7 +688,7 @@ let needSetup = false; // 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; @@ -742,7 +742,7 @@ 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 ]); @@ -868,7 +868,7 @@ let needSetup = false; socket.on("getMonitorList", async (callback) => { try { - checkLogin(socket); + await checkLogin(socket); await server.sendMonitorList(socket); callback({ ok: true, @@ -884,7 +884,7 @@ 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}`); @@ -905,7 +905,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}`); @@ -938,7 +938,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.sendMonitorList(socket); @@ -957,7 +957,7 @@ let needSetup = false; socket.on("pauseMonitor", async (monitorID, callback) => { try { - checkLogin(socket); + await checkLogin(socket); await pauseMonitor(socket.userID, monitorID); await server.sendMonitorList(socket); @@ -976,7 +976,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}`); @@ -1015,7 +1015,7 @@ let needSetup = false; socket.on("getTags", async (callback) => { try { - checkLogin(socket); + await checkLogin(socket); const list = await R.findAll("tag"); @@ -1034,7 +1034,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; @@ -1056,7 +1056,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) { @@ -1086,7 +1086,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 ]); @@ -1105,7 +1105,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, @@ -1128,7 +1128,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, @@ -1151,7 +1151,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, @@ -1177,7 +1177,7 @@ let needSetup = false; socket.on("changePassword", async (userID, password, callback) => { try { - checkLogin(socket); + await checkLogin(socket); if (! password.newPassword) { throw new Error("Invalid new password"); @@ -1205,7 +1205,7 @@ let needSetup = false; socket.on("getSettings", async (callback) => { try { - checkLogin(socket); + await checkLogin(socket); const data = await getSettings("general"); if (!data.serverTimezone) { @@ -1227,7 +1227,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 @@ -1276,7 +1276,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); @@ -1297,7 +1297,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); @@ -1317,7 +1317,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"); @@ -1338,7 +1338,7 @@ let needSetup = false; socket.on("checkApprise", async (callback) => { try { - checkLogin(socket); + await checkLogin(socket); callback(Notification.checkApprise()); } catch (e) { callback(false); @@ -1347,7 +1347,7 @@ let needSetup = false; socket.on("uploadBackup", async (uploadedJSON, importHandle, callback) => { try { - checkLogin(socket); + await checkLogin(socket); let backupData = JSON.parse(uploadedJSON); @@ -1552,7 +1552,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}`); @@ -1578,7 +1578,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}`); @@ -1602,7 +1602,7 @@ let needSetup = false; socket.on("clearStatistics", async (callback) => { try { - checkLogin(socket); + await checkLogin(socket); log.info("manage", `Clear Statistics User ID: ${socket.userID}`); diff --git a/server/socket-handlers/api-key-socket-handler.js b/server/socket-handlers/api-key-socket-handler.js index 8e07df79e4..1aaa63c935 100644 --- a/server/socket-handlers/api-key-socket-handler.js +++ b/server/socket-handlers/api-key-socket-handler.js @@ -16,7 +16,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 = passwordHash.generate(clearKey); @@ -52,7 +52,7 @@ module.exports.apiKeySocketHandler = (socket) => { socket.on("getAPIKeyList", async (callback) => { try { - checkLogin(socket); + await checkLogin(socket); await sendAPIKeyList(socket); callback({ ok: true, @@ -68,7 +68,7 @@ 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}`); @@ -93,7 +93,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}`); @@ -120,7 +120,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 ee58e1ad08..b025b09cec 100644 --- a/server/socket-handlers/cloudflared-socket-handler.js +++ b/server/socket-handlers/cloudflared-socket-handler.js @@ -33,7 +33,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); @@ -43,14 +43,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; @@ -63,7 +63,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); @@ -79,7 +79,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 041cbba069..044735aa4a 100644 --- a/server/socket-handlers/database-socket-handler.js +++ b/server/socket-handlers/database-socket-handler.js @@ -10,7 +10,7 @@ module.exports = (socket) => { // Post or edit incident socket.on("getDatabaseSize", async (callback) => { try { - checkLogin(socket); + await checkLogin(socket); callback({ ok: true, size: Database.getSize(), @@ -25,7 +25,7 @@ module.exports = (socket) => { socket.on("shrinkDatabase", async (callback) => { try { - checkLogin(socket); + await checkLogin(socket); Database.shrink(); callback({ ok: true, diff --git a/server/socket-handlers/docker-socket-handler.js b/server/socket-handlers/docker-socket-handler.js index 542f18cef6..16533b80c4 100644 --- a/server/socket-handlers/docker-socket-handler.js +++ b/server/socket-handlers/docker-socket-handler.js @@ -10,7 +10,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); @@ -31,7 +31,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); @@ -51,7 +51,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 2f0c63b412..8250baa00a 100644 --- a/server/socket-handlers/general-socket-handler.js +++ b/server/socket-handlers/general-socket-handler.js @@ -31,7 +31,7 @@ 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 f5c7fa83b4..cca7abaaa7 100644 --- a/server/socket-handlers/maintenance-socket-handler.js +++ b/server/socket-handlers/maintenance-socket-handler.js @@ -14,7 +14,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); @@ -44,7 +44,7 @@ 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); @@ -71,7 +71,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 @@ -105,7 +105,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 @@ -138,7 +138,7 @@ 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}`); @@ -159,7 +159,7 @@ module.exports.maintenanceSocketHandler = (socket) => { socket.on("getMaintenanceList", async (callback) => { try { - checkLogin(socket); + await checkLogin(socket); await server.sendMaintenanceList(socket); callback({ ok: true, @@ -175,7 +175,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}`); @@ -199,7 +199,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}`); @@ -223,7 +223,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}`); @@ -253,7 +253,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}`); @@ -286,7 +286,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 e67a829ff9..b04565dc2b 100644 --- a/server/socket-handlers/proxy-socket-handler.js +++ b/server/socket-handlers/proxy-socket-handler.js @@ -11,7 +11,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); @@ -37,7 +37,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 eba40daecd..c14d511340 100644 --- a/server/socket-handlers/status-page-socket-handler.js +++ b/server/socket-handlers/status-page-socket-handler.js @@ -17,7 +17,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); @@ -70,7 +70,7 @@ module.exports.statusPageSocketHandler = (socket) => { socket.on("unpinIncident", async (slug, callback) => { try { - checkLogin(socket); + await checkLogin(socket); let statusPageID = await StatusPage.slugToID(slug); @@ -91,7 +91,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 @@ -117,7 +117,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 = ? ", [ @@ -254,7 +254,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(); @@ -300,7 +300,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/util-server.js b/server/util-server.js index d6366a379c..e2d652232f 100644 --- a/server/util-server.js +++ b/server/util-server.js @@ -802,8 +802,10 @@ exports.allowAllOrigin = (res) => { * Check if a user is logged in * @param {Socket} socket Socket instance */ -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."); } }; From a42959da88b2b64160d6cc290e891aca088c2049 Mon Sep 17 00:00:00 2001 From: M1CK431 Date: Sun, 13 Aug 2023 23:06:31 +0200 Subject: [PATCH 4/6] Webapp > Settings > Security: adapt changePassword call --- src/components/settings/Security.vue | 2 +- src/mixins/socket.js | 6 +++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/components/settings/Security.vue b/src/components/settings/Security.vue index 7d13ea90e5..5c0b282c56 100644 --- a/src/components/settings/Security.vue +++ b/src/components/settings/Security.vue @@ -159,7 +159,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/mixins/socket.js b/src/mixins/socket.js index fabd344065..25f4ea8d84 100644 --- a/src/mixins/socket.js +++ b/src/mixins/socket.js @@ -31,6 +31,7 @@ export default { connectCount: 0, initedSocketIO: false, }, + userID: null, username: null, remember: (localStorage.remember !== "0"), allowLoginDialog: false, // Allowed to show login dialog, but "loggedIn" have to be true too. This exists because prevent the login dialog show 0.1s in first before the socket server auth-ed. @@ -371,10 +372,13 @@ export default { } if (res.ok) { + const { userID, username } = this.getJWTPayload() || {}; + this.userID = userID; + this.username = username; + this.storage().token = res.token; this.socket.token = res.token; this.loggedIn = true; - this.username = this.getJWTPayload()?.username; // Trigger Chrome Save Password history.pushState({}, ""); From 8756edabb3967f079e76048c1f6e7643860569aa Mon Sep 17 00:00:00 2001 From: M1CK431 Date: Fri, 4 Aug 2023 01:40:12 +0200 Subject: [PATCH 5/6] webapp > Settings: add breadcrumbs --- src/pages/Settings.vue | 62 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 59 insertions(+), 3 deletions(-) diff --git a/src/pages/Settings.vue b/src/pages/Settings.vue index f3c6b7765a..d6549a3cb8 100644 --- a/src/pages/Settings.vue +++ b/src/pages/Settings.vue @@ -35,9 +35,20 @@
-
- {{ subMenus[currentPage].title }} -
+
@@ -54,6 +65,14 @@ diff --git a/src/components/settings/Users/EditUser.vue b/src/components/settings/Users/EditUser.vue new file mode 100644 index 0000000000..59a8a17471 --- /dev/null +++ b/src/components/settings/Users/EditUser.vue @@ -0,0 +1,205 @@ + + + diff --git a/src/components/settings/Users/Users.vue b/src/components/settings/Users/Users.vue new file mode 100644 index 0000000000..e367fd76d7 --- /dev/null +++ b/src/components/settings/Users/Users.vue @@ -0,0 +1,153 @@ + + + + + diff --git a/src/components/settings/Users/routes.js b/src/components/settings/Users/routes.js new file mode 100644 index 0000000000..6d35174558 --- /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 7bdfe1ca02..b404827832 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 772e572997..56e4ed70f9 100644 --- a/src/lang/en.json +++ b/src/lang/en.json @@ -796,8 +796,8 @@ "noGroupMonitorMsg": "Not Available. Create a Group Monitor First.", "Close": "Close", "Request Body": "Request Body", - "wayToGetFlashDutyKey":"You can go to Channel -> (Select a Channel) -> Integrations -> Add a new integration' page, add a 'Custom Event' to get a push address, copy the Integration Key in the address. For more information, please visit", - "FlashDuty Severity":"Severity", + "wayToGetFlashDutyKey": "You can go to Channel -> (Select a Channel) -> Integrations -> Add a new integration' page, add a 'Custom Event' to get a push address, copy the Integration Key in the address. For more information, please visit", + "FlashDuty Severity": "Severity", "nostrRelays": "Nostr relays", "nostrRelaysHelp": "One relay URL per line", "nostrSender": "Sender Private Key (nsec)", @@ -806,5 +806,12 @@ "showCertificateExpiry": "Show Certificate Expiry", "noOrBadCertificate": "No/Bad Certificate", "gamedigGuessPort": "Gamedig: Guess Port", - "gamedigGuessPortDescription": "The port used by Valve Server Query Protocol may be different from the client port. Try this if the monitor cannot connect to your server." -} + "gamedigGuessPortDescription": "The port used by Valve Server Query Protocol may be different from the client port. Try this if the monitor cannot connect to your server.", + "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" +} \ No newline at end of file diff --git a/src/pages/Settings.vue b/src/pages/Settings.vue index d6549a3cb8..1f533aab18 100644 --- a/src/pages/Settings.vue +++ b/src/pages/Settings.vue @@ -126,6 +126,13 @@ export default { security: { title: this.$t("Security"), }, + users: { + title: this.$t("Users"), + children: { + add: { title: this.$t("Add") }, + edit: { title: this.$t("Edit") } + }, + }, "api-keys": { title: this.$t("API Keys") }, diff --git a/src/router.js b/src/router.js index a8644805e8..f52ecaad8f 100644 --- a/src/router.js +++ b/src/router.js @@ -26,6 +26,7 @@ import General from "./components/settings/General.vue"; const Notifications = () => import("./components/settings/Notifications.vue"); import ReverseProxy from "./components/settings/ReverseProxy.vue"; import Tags from "./components/settings/Tags.vue"; +import usersSettingsRoutes from "./components/settings/Users/routes.js"; import MonitorHistory from "./components/settings/MonitorHistory.vue"; const Security = () => import("./components/settings/Security.vue"); import Proxies from "./components/settings/Proxies.vue"; @@ -117,6 +118,7 @@ const routes = [ path: "security", component: Security, }, + usersSettingsRoutes, { path: "api-keys", component: APIKeys, diff --git a/src/util-frontend.js b/src/util-frontend.js index 4b85fa3468..ea003a0ae8 100644 --- a/src/util-frontend.js +++ b/src/util-frontend.js @@ -139,3 +139,22 @@ export function colorOptions(self) { color: "#DB2777" }, ]; } + +/** + * Get debounced function + * @returns {function} debounced function + */ +export function Debounce() { + let timeout = null; + + /** + * exec callback function after delay if no new call to function happens + * @param {function} callback function to execute after delay + * @param {number} [delay=100] delay before execute the callback if no new call to function happens + * @returns {void} + */ + return function (callback, delay = 100) { + clearTimeout(timeout); + timeout = setTimeout(() => callback(), delay); + }; +}