From 9e16619e5673eadaab03aaf89e71ea7219c60c83 Mon Sep 17 00:00:00 2001 From: theonlynexus Date: Wed, 20 Jul 2022 15:25:01 +0900 Subject: [PATCH] Updated documentation, minor fixes --- src/dashboard.py | 6 +- src/db.py | 61 +++- src/rest_routes.py | 6 +- src/static/js/configuration.js | 544 ++++++++++++++--------------- src/static/js/configuration.min.js | 2 +- src/templates/configuration.html | 408 ++++++++++++---------- src/templates/settings.html | 155 ++++---- src/util.py | 49 +-- src/wg.py | 65 +++- 9 files changed, 713 insertions(+), 583 deletions(-) diff --git a/src/dashboard.py b/src/dashboard.py index 0a24476..7521732 100644 --- a/src/dashboard.py +++ b/src/dashboard.py @@ -286,9 +286,9 @@ def update_peer_default_config(): config = g.conf if ( - len(request.form["peer_endpoint_allowed_ips"]) == 0 - or len(request.form["peer_global_DNS"]) == 0 - or len(request.form["peer_remote_endpoint"]) == 0 + not (request.form["peer_endpoint_allowed_ips"]) + or not (request.form["peer_global_DNS"]) + or not (request.form["peer_remote_endpoint"]) ): session["message"] = "Please fill in all required boxes." session["message_status"] = "danger" diff --git a/src/db.py b/src/db.py index 7c8983a..3f1a24a 100644 --- a/src/db.py +++ b/src/db.py @@ -3,7 +3,10 @@ from __main__ import app import sqlite3 -def get_net_stats(interface_name: str) -> list: +def get_net_stats(interface_name: str) -> list[sqlite3.Row]: + """ + Gets net stats for all peers of `interface_name` and returns a list of dicts + """ app.logger.debug(f"db.get_net_stats({interface_name})") data = g.cur.execute( f"SELECT total_sent, total_receive, cumu_sent, cumu_receive FROM {interface_name}" @@ -12,6 +15,9 @@ def get_net_stats(interface_name: str) -> list: def get_net_stats_and_peer_status(interface_name: str, id: str) -> sqlite3.Row | None: + """ + Gets net stats for a given peer of `interface_name` and the data as `dict`, `None` if not found. + """ app.logger.debug(f"db.get_net_stats_and_peer_status({interface_name})") data = g.cur.execute( """SELECT total_receive, total_sent, cumu_receive, cumu_sent, status @@ -21,7 +27,12 @@ def get_net_stats_and_peer_status(interface_name: str, id: str) -> sqlite3.Row | return data.fetchone() -def get_peer_count_by_allowed_ips(interface_name: str, ip: str, id: str): +def get_peer_count_by_allowed_ips( + interface_name: str, ip: str, id: str +) -> sqlite3.Row | None: + """ + Gets and returns the number of peers of `interface_name` that have allowed_ips similar to `ip`. + """ app.logger.debug(f"db.get_peer_count_by_allowed_ips({interface_name}, {ip}, {id})") data = g.cur.execute( f"""SELECT COUNT(*) FROM {interface_name} @@ -31,7 +42,7 @@ def get_peer_count_by_allowed_ips(interface_name: str, ip: str, id: str): return data.fetchone() -def get_peers(interface_name: str, search: str = None) -> list: +def get_peers(interface_name: str, search: str = None) -> list[sqlite3.Row]: """Returns the list of records which name matches the search string, or all if no search is provided""" app.logger.debug(f"db.get_peers({interface_name}, {search})") @@ -44,8 +55,10 @@ def get_peers(interface_name: str, search: str = None) -> list: return data.fetchall() -def get_peer_by_id(interface_name: str, id: str) -> list: - """Returns the record matching the pass id or None.""" +def get_peer_by_id(interface_name: str, id: str) -> sqlite3.Row | None: + """ + Returns the peer of `interface_name` matching `id` or None. + """ app.logger.debug(f"db.get_peer_by_id({interface_name}, {id})") sql = "SELECT * FROM %s WHERE id='%s'" % (interface_name, id) @@ -53,21 +66,29 @@ def get_peer_by_id(interface_name: str, id: str) -> list: return data.fetchone() -def get_peer_allowed_ips(interface_name: str) -> list: +def get_peer_allowed_ips(interface_name: str) -> list[sqlite3.Row]: + """ + Returns the `allowed_ips` of all peers of `interface_name`. + """ app.logger.debug(f"db.get_peer_allowed_ips({interface_name})") sql = f"SELECT allowed_ips FROM {interface_name}" data = g.cur.execute(sql) return data.fetchall() -def get_peer_ids(interface_name: str): +def get_peer_ids(interface_name: str) -> list[sqlite3.Row]: + """ + Returns the `id`s of all peers of `interface_name`. + """ app.logger.debug(f"db.get_peer_ids({interface_name})") data = g.cur.execute("SELECT id FROM %s" % interface_name) return data.fetchall() -def remove_stale_peers(interface_name: str, peer_data: str): - """Removes entries that which id is present in the db, but not in peer_data""" +def remove_stale_peers(interface_name: str, peer_data: dict): + """ + Removes from the DB entries that are present there, but not in `peer_data` + """ app.logger.debug(f"db.remove_stale_peers({interface_name}, peer_data)") db_key = set(map(lambda a: a[0], get_peer_ids(interface_name))) @@ -79,12 +100,18 @@ def remove_stale_peers(interface_name: str, peer_data: str): def delete_peer(interface_name: str, id: str): + """ + Removes a peer of `interface_name` with the given `id` + """ app.logger.debug(f"db.delete_peer({interface_name}, {id})") sql = "DELETE FROM %s WHERE id = '%s'" % (interface_name, id) g.cur.execute(sql) def insert_peer(interface_name: str, data: dict): + """ + Inserts a peer of `interface_name` with the given `data` + """ app.logger.debug(f"db.insert_peer({interface_name}, {data})") sql = f""" INSERT INTO {interface_name} @@ -95,10 +122,13 @@ def insert_peer(interface_name: str, data: dict): g.cur.execute(sql, data) -def create_table_if_missing(table_name: str): - app.logger.debug(f"db.create_table_if_missing({table_name})") +def create_table_if_missing(interface_name: str): + """ + Creates a table for `interface_name`, if missing. + """ + app.logger.debug(f"db.create_table_if_missing({interface_name})") create_table = f""" - CREATE TABLE IF NOT EXISTS {table_name} ( + CREATE TABLE IF NOT EXISTS {interface_name} ( id VARCHAR NOT NULL PRIMARY KEY, private_key VARCHAR NULL UNIQUE, DNS VARCHAR NULL, endpoint_allowed_ips VARCHAR NULL, name VARCHAR NULL, total_receive FLOAT NULL, total_sent FLOAT NULL, total_data FLOAT NULL, endpoint VARCHAR NULL, @@ -111,6 +141,9 @@ def create_table_if_missing(table_name: str): def update_peer(interface_name: str, data: dict): + """ + Updates the peer of `interface_name` with the given `data`, if the peer record exists. + """ app.logger.debug(f"db.interface_name({data})") id = data["id"] db_peer = get_peer_by_id(interface_name, id) @@ -121,6 +154,10 @@ def update_peer(interface_name: str, data: dict): def _update_peer(interface_name: str, data: dict): + """ + Updates the peer of `interface_name` with the given `data`. + `data` should contain the peer's `id` (public key), plus any other field to be updated. + """ app.logger.debug(f"db.update_peer({interface_name}, {data})") sql = f""" UPDATE {interface_name} SET diff --git a/src/rest_routes.py b/src/rest_routes.py index 0dfa77b..89fbd9b 100644 --- a/src/rest_routes.py +++ b/src/rest_routes.py @@ -322,7 +322,7 @@ def add_peer(interface_name): data = request.get_json() public_key = data["public_key"] allowed_ips = data["allowed_ips"] - endpoint_allowed_ips = data["endpoint_allowed_ip"] + endpoint_allowed_ips = data["endpoint_allowed_ips"] dns_addresses = data["DNS"] enable_preshared_key = data["enable_preshared_key"] preshared_key = data["preshared_key"] @@ -398,7 +398,7 @@ def save_peer_setting(interface_name): private_key = data["private_key"] dns_addresses = data["DNS"] allowed_ips = data["allowed_ips"] - endpoint_allowed_ips = data["endpoint_allowed_ip"] + endpoint_allowed_ips = data["endpoint_allowed_ips"] preshared_key = data["preshared_key"] db_peer = db.get_peer_by_id(interface_name, id) if db_peer: @@ -624,7 +624,7 @@ def add_peer_bulk(interface_name): data = request.get_json() keys = data["keys"] - endpoint_allowed_ips = data["endpoint_allowed_ip"] + endpoint_allowed_ips = data["endpoint_allowed_ips"] dns_addresses = data["DNS"] enable_preshared_key = data["enable_preshared_key"] amount = data["amount"] diff --git a/src/static/js/configuration.js b/src/static/js/configuration.js index ff4619d..80bd3f5 100644 --- a/src/static/js/configuration.js +++ b/src/static/js/configuration.js @@ -3,7 +3,7 @@ * Under Apache-2.0 License */ -(function(){ +(function () { /* global peers */ /* global conf_name */ @@ -32,7 +32,7 @@ * @param response */ function configurationAlert(response) { - if (response.listen_port === "" && response.status === "stopped"){ + if (response.listen_port === "" && response.status === "stopped") { let configAlert = document.createElement("div"); configAlert.classList.add("alert"); configAlert.classList.add("alert-warning"); @@ -40,7 +40,7 @@ configAlert.innerHTML = 'Peer QR Code and configuration file download required a specified Listen Port.'; document.querySelector("#config_info_alert").appendChild(configAlert); } - if (response.conf_address === "N/A"){ + if (response.conf_address === "N/A") { let configAlert = document.createElement("div"); configAlert.classList.add("alert"); configAlert.classList.add("alert-warning"); @@ -56,9 +56,9 @@ */ function configurationHeader(response) { let $conf_status_btn = document.getElementById("conf_status_btn"); - if (response.checked === "checked"){ + if (response.checked === "checked") { $conf_status_btn.innerHTML = ` ON`; - }else{ + } else { $conf_status_btn.innerHTML = ` OFF`; } $conf_status_btn.classList.remove("info_loading"); @@ -85,11 +85,11 @@ */ function configurationPeers(response) { let result = ""; - if (response.peer_data.length === 0){ + if (response.peer_data.length === 0) { document.querySelector(".peer_list").innerHTML = `

Oops! No peers found ‘︿’

`; - }else{ + } else { let display_mode = response.peer_display_mode === "list" ? "col-12" : "col-sm-6 col-lg-4"; - response.peer_data.forEach(function(peer){ + response.peer_data.forEach(function (peer) { let total_r = 0; let total_s = 0; total_r += peer.cumu_receive; @@ -97,41 +97,41 @@ let spliter = '
'; let peer_name = '
' + - '
'+ (peer.name === "" ? "Untitled" : peer.name) +'
' + - '
' + + '
' + (peer.name === "" ? "Untitled" : peer.name) + '
' + + '
' + '
'; - let peer_transfer = '

'+ roundN(peer.total_receive + total_r, 4) +' GB

'+ roundN(peer.total_sent + total_s, 4) +' GB

'; - let peer_key = '
PEERCLICK TO COPY
'+peer.id+'
'; - let peer_allowed_ip = '
ALLOWED IP
'+peer.allowed_ip+'
'; - let peer_latest_handshake = '
LATEST HANDSHAKE
'+peer.latest_handshake+'
'; - let peer_endpoint = '
END POINT
'+peer.endpoint+'
'; - let peer_control = '

'; - if (peer.private_key !== ""){ - peer_control += ''; + let peer_transfer = '

' + roundN(peer.total_receive + total_r, 4) + ' GB

' + roundN(peer.total_sent + total_s, 4) + ' GB

'; + let peer_key = '
PEERCLICK TO COPY
' + peer.id + '
'; + let peer_allowed_ip = '
ALLOWED IP
' + peer.allowed_ips + '
'; + let peer_latest_handshake = '
LATEST HANDSHAKE
' + peer.latest_handshake + '
'; + let peer_endpoint = '
END POINT
' + peer.endpoint + '
'; + let peer_control = '

'; + if (peer.private_key !== "") { + peer_control += ''; } peer_control += '
'; - let html = '
' + - '
' + - '
' + - '
' + - peer_name + - spliter + - peer_transfer + - peer_key + - peer_allowed_ip + - peer_latest_handshake + - spliter + - peer_endpoint + - spliter + - peer_control + - '
' + - '
' + - '
' + - '
'; + let html = '
' + + '
' + + '
' + + '
' + + peer_name + + spliter + + peer_transfer + + peer_key + + peer_allowed_ip + + peer_latest_handshake + + spliter + + peer_endpoint + + spliter + + peer_control + + '
' + + '
' + + '
' + + '
'; result += html; }); document.querySelector(".peer_list").innerHTML = result; - if (response.dashboard_refresh_interval !== configuration_timeout){ + if (response.dashboard_refresh_interval !== configuration_timeout) { configuration_timeout = response.dashboard_refresh_interval; removeConfigurationInterval(); setConfigurationInterval(); @@ -144,18 +144,18 @@ */ function addPeersByBulk() { let $new_add_amount = $("#new_add_amount"); - $add_peer.setAttribute("disabled","disabled"); + $add_peer.setAttribute("disabled", "disabled"); $add_peer.innerHTML = `Adding ${$new_add_amount.val()} peers...`; let $new_add_DNS = $("#new_add_DNS"); $new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val())); let $new_add_endpoint_allowed_ip = $("#new_add_endpoint_allowed_ip"); - $new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val())); + $new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val())); let $new_add_MTU = $("#new_add_MTU"); let $new_add_keep_alive = $("#new_add_keep_alive"); let $enable_preshare_key = $("#enable_preshare_key"); - let data_list = [$new_add_DNS, $new_add_endpoint_allowed_ip,$new_add_MTU, $new_add_keep_alive]; - if ($new_add_amount.val() > 0 && !$new_add_amount.hasClass("is-invalid")){ - if ($new_add_DNS.val() !== "" && $new_add_endpoint_allowed_ip.val() !== ""){ + let data_list = [$new_add_DNS, $new_add_endpoint_allowed_ip, $new_add_MTU, $new_add_keep_alive]; + if ($new_add_amount.val() > 0 && !$new_add_amount.hasClass("is-invalid")) { + if ($new_add_DNS.val() !== "" && $new_add_endpoint_allowed_ip.val() !== "") { let conf = $add_peer.getAttribute('conf_id'); let keys = []; for (let i = 0; i < $new_add_amount.val(); i++) { @@ -163,43 +163,43 @@ } $.ajax({ method: "POST", - url: "/add_peer_bulk/"+conf, - headers:{ + url: "/add_peer_bulk/" + conf, + headers: { "Content-Type": "application/json" }, data: JSON.stringify({ "DNS": $new_add_DNS.val(), - "endpoint_allowed_ip": $new_add_endpoint_allowed_ip.val(), + "endpoint_allowed_ips": $new_add_endpoint_allowed_ip.val(), "MTU": $new_add_MTU.val(), "keep_alive": $new_add_keep_alive.val(), "enable_preshared_key": $enable_preshare_key.prop("checked"), "keys": keys, "amount": $new_add_amount.val() }), - success: function (response){ - if(response !== "true"){ + success: function (response) { + if (response !== "true") { $("#add_peer_alert").html(response).removeClass("d-none"); data_list.forEach((ele) => ele.removeAttr("disabled")); $add_peer.removeAttribute("disabled"); $add_peer.innerHTML = "Save"; } - else{ + else { window.configurations.loadPeers(""); data_list.forEach((ele) => ele.removeAttr("disabled")); $("#add_peer_form").trigger("reset"); $add_peer.removeAttribute("disabled"); $add_peer.innerHTML = "Save"; - window.configurations.showToast($new_add_amount.val()+" peers added successful!"); + window.configurations.showToast($new_add_amount.val() + " peers added successful!"); window.configurations.addModal().toggle(); } } }); - }else{ + } else { $("#add_peer_alert").html("Please fill in all required box.").removeClass("d-none"); $add_peer.removeAttribute("disabled"); $add_peer.innerHTML = "Add"; } - }else{ + } else { $add_peer.removeAttribute("disabled"); $add_peer.innerHTML = "Add"; } @@ -210,33 +210,33 @@ * @param config * @param peer_ids */ - function deletePeers(config, peer_ids){ + function deletePeers(config, peer_ids) { $.ajax({ method: "POST", - url: "/remove_peer/"+config, - headers:{ + url: "/remove_peer/" + config, + headers: { "Content-Type": "application/json" }, - data: JSON.stringify({"action": "delete", "peer_ids": peer_ids}), - success: function (response){ - if(response !== "true"){ + data: JSON.stringify({ "action": "delete", "peer_ids": peer_ids }), + success: function (response) { + if (response !== "true") { if (window.configurations.deleteModal()._isShown) { - $("#remove_peer_alert").html(response+$("#add_peer_alert").html()) - .removeClass("d-none"); + $("#remove_peer_alert").html(response + $("#add_peer_alert").html()) + .removeClass("d-none"); $("#delete_peer").removeAttr("disabled").html("Delete"); } - if (window.configurations.deleteBulkModal()._isShown){ + if (window.configurations.deleteBulkModal()._isShown) { let $bulk_remove_peer_alert = $("#bulk_remove_peer_alert"); - $bulk_remove_peer_alert.html(response+$bulk_remove_peer_alert.html()) - .removeClass("d-none"); + $bulk_remove_peer_alert.html(response + $bulk_remove_peer_alert.html()) + .removeClass("d-none"); $("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete"); } } - else{ + else { if (window.configurations.deleteModal()._isShown) { window.configurations.deleteModal().toggle(); } - if (window.configurations.deleteBulkModal()._isShown){ + if (window.configurations.deleteBulkModal()._isShown) { $("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete"); $("#selected_peer_list").html(''); $(".delete-bulk-peer-item.active").removeClass('active'); @@ -254,73 +254,73 @@ /** * Handle when the server is not responding */ - function noResponding(){ + function noResponding() { document.querySelectorAll(".no-response").forEach(ele => ele.classList.add("active")); - setTimeout(function (){ + setTimeout(function () { document.querySelectorAll(".no-response").forEach(ele => ele.classList.add("show")); document.querySelector("#right_body").classList.add("no-responding"); document.querySelector(".navbar").classList.add("no-responding"); - },10); + }, 10); } /** * Remove no responding */ - function removeNoResponding(){ + function removeNoResponding() { document.querySelectorAll(".no-response").forEach(ele => ele.classList.remove("show")); document.querySelector("#right_body").classList.remove("no-responding"); document.querySelector(".navbar").classList.remove("no-responding"); - setTimeout(function (){ + setTimeout(function () { document.querySelectorAll(".no-response").forEach(ele => ele.classList.remove("active")); - },1010); + }, 1010); } /** * Set configuration refresh Interval */ - function setConfigurationInterval(){ - configuration_interval = setInterval(function (){ + function setConfigurationInterval() { + configuration_interval = setInterval(function () { loadPeers($('#search_peer_textbox').val()); - }, configuration_timeout); + }, configuration_timeout); } /** * Remove configuration refresh interval */ - function removeConfigurationInterval(){ + function removeConfigurationInterval() { clearInterval(configuration_interval); } /** * Start Progress Bar */ - function startProgressBar(){ - $progress_bar.css("width","0%") + function startProgressBar() { + $progress_bar.css("width", "0%") .css("opacity", "100") .css("background", "rgb(255,69,69)") .css("background", "linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)") - .css("width","25%"); - setTimeout(function(){ + .css("width", "25%"); + setTimeout(function () { stillLoadingProgressBar(); - },300); + }, 300); } /** * Still Loading Progress Bar */ - function stillLoadingProgressBar(){ + function stillLoadingProgressBar() { $progress_bar.css("transition", "3s ease-in-out").css("width", "75%"); } /** * End Progress Bar */ - function endProgressBar(){ - $progress_bar.css("transition", "0.3s ease-in-out").css("width","100%"); - setTimeout(function(){ + function endProgressBar() { + $progress_bar.css("transition", "0.3s ease-in-out").css("width", "100%"); + setTimeout(function () { $progress_bar.css("opacity", "0"); - },250); + }, 250); } /** @@ -330,8 +330,8 @@ * @returns {number} */ function roundN(value, digits) { - let tenToN = 10 ** digits; - return (Math.round(value * tenToN)) / tenToN; + let tenToN = 10 ** digits; + return (Math.round(value * tenToN)) / tenToN; } /** @@ -341,30 +341,30 @@ let d1 = new Date(); let time = 0; let count = 0; - function loadPeers(searchString){ + function loadPeers(searchString) { startProgressBar(); d1 = new Date(); $.ajax({ method: "GET", url: `/get_config/${conf_name}?search=${encodeURIComponent(searchString)}`, - headers:{"Content-Type": "application/json"} - }).done(function(response){ + headers: { "Content-Type": "application/json" } + }).done(function (response) { removeNoResponding(); peers = response.peer_data; configurationAlert(response); configurationHeader(response); configurationPeers(response); - $(".dot.dot-running").attr("title","Peer Connected").tooltip(); - $(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip(); + $(".dot.dot-running").attr("title", "Peer Connected").tooltip(); + $(".dot.dot-stopped").attr("title", "Peer Disconnected").tooltip(); $("i[data-toggle='tooltip']").tooltip(); endProgressBar(); let d2 = new Date(); let seconds = (d2 - d1); time += seconds; count += 1; - console.log(`Average ${time/count}ms`); + console.log(`Average ${time / count}ms`); $("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`); - }).fail(function(){ + }).fail(function () { noResponding(); }); } @@ -372,7 +372,7 @@ /** * Generate Private and Public key for a new peer */ - function generate_key(){ + function generate_key() { let keys = window.wireguard.generateKeypair(); document.querySelector("#private_key").value = keys.privateKey; document.querySelector("#public_key").value = keys.publicKey; @@ -396,14 +396,14 @@ * @param interval */ function updateRefreshInterval(res, interval) { - if (res === "true"){ + if (res === "true") { configuration_timeout = interval; removeConfigurationInterval(); setConfigurationInterval(); - showToast("Refresh Interval set to "+Math.round(interval/1000)+" seconds"); - }else{ + showToast("Refresh Interval set to " + Math.round(interval / 1000) + " seconds"); + } else { $(".interval-btn-group button").removeClass("active"); - $('.interval-btn-group button[data-refresh-interval="'+configuration_timeout+'"]').addClass("active"); + $('.interval-btn-group button[data-refresh-interval="' + configuration_timeout + '"]').addClass("active"); showToast("Refresh Interval set unsuccessful"); } } @@ -413,7 +413,7 @@ * @param val * @returns {string} */ - function cleanIp(val){ + function cleanIp(val) { let clean_ip = val.split(','); for (let i = 0; i < clean_ip.length; i++) { clean_ip[i] = clean_ip[i].trim(' '); @@ -425,13 +425,13 @@ * Trigger IP badge and item * @param ip */ - function trigger_ip(ip){ + function trigger_ip(ip) { let $ip_ele = document.querySelector(`.available-ip-item[data-ip='${ip}']`); - if ($ip_ele){ - if ($ip_ele.classList.contains("active")){ + if ($ip_ele) { + if ($ip_ele.classList.contains("active")) { $ip_ele.classList.remove("active"); document.querySelector(`#selected_ip_list .badge[data-ip='${ip}']`).remove(); - }else{ + } else { $ip_ele.classList.add("active"); document.querySelector("#selected_ip_list").innerHTML += `${ip}`; } @@ -442,10 +442,10 @@ * Download single configuration file * @param conf */ - function download_one_config(conf){ + function download_one_config(conf) { let link = document.createElement('a'); link.download = conf.filename; - let blob = new Blob([conf.content], {type: 'text/conf'}); + let blob = new Blob([conf.content], { type: 'text/conf' }); link.href = window.URL.createObjectURL(blob); link.click(); } @@ -454,16 +454,16 @@ * Toggle delete by bulk IP * @param element */ - function toggleBulkIP(element){ + function toggleBulkIP(element) { let $selected_peer_list = $("#selected_peer_list"); let id = element.data("id"); let name = element.data("name") === "" ? "Untitled Peer" : element.data("name"); - if (element.hasClass("active")){ + if (element.hasClass("active")) { element.removeClass("active"); - $("#selected_peer_list .badge[data-id='"+id+"']").remove(); - }else{ + $("#selected_peer_list .badge[data-id='" + id + "']").remove(); + } else { element.addClass("active"); - $selected_peer_list.append(''+name+' - '+id+''); + $selected_peer_list.append('' + name + ' - ' + id + ''); } } @@ -474,7 +474,7 @@ function copyToClipboard(element) { let $temp = $(""); $body.append($temp); - $temp.val($(element).text()).trigger( "select" ); + $temp.val($(element).text()).trigger("select"); document.execCommand("copy"); $temp.remove(); } @@ -482,7 +482,7 @@ /** * Get all available IP for this configuration */ - function getAvailableIps(){ + function getAvailableIps() { $.ajax({ "url": `/available_ips/${$add_peer.getAttribute("conf_id")}`, "method": "GET", @@ -493,7 +493,7 @@ document.querySelector("#allowed_ips").value = available_ips[0]; available_ips.forEach((ip) => $list_group.innerHTML += - `${ip}`); + `${ip}`); }); } @@ -547,7 +547,7 @@ document.querySelector(".add_btn").addEventListener("click", () => { */ document.querySelector(".info").addEventListener("click", (event) => { let selector = document.querySelector(".switch"); - if (selector.contains(event.target)){ + if (selector.contains(event.target)) { selector.style.display = "none"; document.querySelector('div[role=status]').style.display = "inline-block"; location.replace(`/switch/${selector.getAttribute("id")}`); @@ -559,10 +559,10 @@ document.querySelector(".info").addEventListener("click", (event) => { */ document.querySelector("#private_key").addEventListener("change", (event) => { let publicKey = document.querySelector("#public_key"); - if (event.target.value.length === 44){ + if (event.target.value.length === 44) { publicKey.value = window.wireguard.generatePublicKey(event.target.value); publicKey.setAttribute("disabled", "disabled"); - }else{ + } else { publicKey.attributes.removeNamedItem("disabled"); publicKey.value = ""; } @@ -574,15 +574,15 @@ document.querySelector("#private_key").addEventListener("change", (event) => { $('#add_modal').on('show.bs.modal', function () { window.configurations.generateKeyPair(); window.configurations.getAvailableIps(); -}).on('hide.bs.modal', function(){ +}).on('hide.bs.modal', function () { $("#allowed_ips_indicator").html(''); }); /** * Handle when user clicked the regenerate button */ -$("#re_generate_key").on("click",function (){ - $("#public_key").attr("disabled","disabled"); +$("#re_generate_key").on("click", function () { + $("#public_key").attr("disabled", "disabled"); $("#re_generate_key i").addClass("rotating"); window.configurations.generateKeyPair(); }); @@ -590,13 +590,13 @@ $("#re_generate_key").on("click",function (){ /** * Handle when user is editing in allowed ips textbox */ -$("#allowed_ips").on("keyup", function(){ +$("#allowed_ips").on("keyup", function () { let s = window.configurations.cleanIp($(this).val()); s = s.split(","); - if (available_ips.includes(s[s.length - 1])){ + if (available_ips.includes(s[s.length - 1])) { $("#allowed_ips_indicator").removeClass().addClass("text-success") .html(''); - }else{ + } else { $("#allowed_ips_indicator").removeClass().addClass("text-warning") .html(''); } @@ -605,18 +605,18 @@ $("#allowed_ips").on("keyup", function(){ /** * Change peer name when user typing in peer name textbox */ -$("#peer_name_textbox").on("keyup", function(){ +$("#peer_name_textbox").on("keyup", function () { $(".peer_name").html($(this).val()); }); /** * When Add Peer button got clicked */ -$add_peer.addEventListener("click",function(){ +$add_peer.addEventListener("click", function () { let $bulk_add = $("#bulk_add"); - if ($bulk_add.prop("checked")){ - if (!$("#new_add_amount").hasClass("is-invalid")){ - window.configurations.addPeersByBulk(); + if ($bulk_add.prop("checked")) { + if (!$("#new_add_amount").hasClass("is-invalid")) { + window.configurations.addPeersByBulk(); } } else { let $public_key = $("#public_key"); @@ -631,38 +631,38 @@ $add_peer.addEventListener("click",function(){ let $new_add_MTU = $("#new_add_MTU"); let $new_add_keep_alive = $("#new_add_keep_alive"); let $enable_preshare_key = $("#enable_preshare_key"); - $add_peer.setAttribute("disabled","disabled"); + $add_peer.setAttribute("disabled", "disabled"); $add_peer.innerHTML = "Adding..."; - if ($allowed_ips.val() !== "" && $public_key.val() !== "" && $new_add_DNS.val() !== "" && $new_add_endpoint_allowed_ip.val() !== ""){ + if ($allowed_ips.val() !== "" && $public_key.val() !== "" && $new_add_DNS.val() !== "" && $new_add_endpoint_allowed_ip.val() !== "") { let conf = $add_peer.getAttribute('conf_id'); - let data_list = [$private_key, $allowed_ips, $new_add_name, $new_add_DNS, $new_add_endpoint_allowed_ip,$new_add_MTU, $new_add_keep_alive]; + let data_list = [$private_key, $allowed_ips, $new_add_name, $new_add_DNS, $new_add_endpoint_allowed_ip, $new_add_MTU, $new_add_keep_alive]; data_list.forEach((ele) => ele.attr("disabled", "disabled")); $.ajax({ method: "POST", - url: "/add_peer/"+conf, - headers:{ + url: "/add_peer/" + conf, + headers: { "Content-Type": "application/json" }, data: JSON.stringify({ - "private_key":$private_key.val(), - "public_key":$public_key.val(), + "private_key": $private_key.val(), + "public_key": $public_key.val(), "allowed_ips": $allowed_ips.val(), - "name":$new_add_name.val(), + "name": $new_add_name.val(), "DNS": $new_add_DNS.val(), - "endpoint_allowed_ip": $new_add_endpoint_allowed_ip.val(), + "endpoint_allowed_ips": $new_add_endpoint_allowed_ip.val(), "MTU": $new_add_MTU.val(), "keep_alive": $new_add_keep_alive.val(), "enable_preshared_key": $enable_preshare_key.prop("checked"), "preshared_key": $enable_preshare_key.val() }), - success: function (response){ - if(response !== "true"){ + success: function (response) { + if (response !== "true") { $("#add_peer_alert").html(response).removeClass("d-none"); data_list.forEach((ele) => ele.removeAttr("disabled")); $add_peer.removeAttribute("disabled"); $add_peer.innerHTML = "Save"; } - else{ + else { window.configurations.loadPeers(""); data_list.forEach((ele) => ele.removeAttr("disabled")); $("#add_peer_form").trigger("reset"); @@ -673,7 +673,7 @@ $add_peer.addEventListener("click",function(){ } } }); - }else{ + } else { $("#add_peer_alert").html("Please fill in all required box.").removeClass("d-none"); $add_peer.removeAttribute("disabled"); $add_peer.innerHTML = "Add"; @@ -685,23 +685,23 @@ $add_peer.addEventListener("click",function(){ * Handle when user is typing the amount of peers they want to add, and will check if the amount is less than 1 or * is larger than the amount of available ips */ -$("#new_add_amount").on("keyup", function(){ +$("#new_add_amount").on("keyup", function () { let $bulk_amount_validation = $("#bulk_amount_validation"); // $(this).removeClass("is-valid").addClass("is-invalid"); - if ($(this).val().length > 0){ - if (isNaN($(this).val())){ + if ($(this).val().length > 0) { + if (isNaN($(this).val())) { $(this).removeClass("is-valid").addClass("is-invalid"); $bulk_amount_validation.html("Please enter a valid integer"); - }else if ($(this).val() > available_ips.length){ + } else if ($(this).val() > available_ips.length) { $(this).removeClass("is-valid").addClass("is-invalid"); $bulk_amount_validation.html(`Cannot create more than ${available_ips.length} peers.`); - }else if ($(this).val() < 1){ + } else if ($(this).val() < 1) { $(this).removeClass("is-valid").addClass("is-invalid"); $bulk_amount_validation.html("Please enter at least 1 or more."); - }else{ + } else { $(this).removeClass("is-invalid").addClass("is-valid"); } - }else{ + } else { $(this).removeClass("is-invalid").removeClass("is-valid"); } }); @@ -709,18 +709,18 @@ $("#new_add_amount").on("keyup", function(){ /** * Handle when user toggled add peers by bulk */ -$("#bulk_add").on("change", function (){ +$("#bulk_add").on("change", function () { let hide = $(".non-bulk").find("input"); let amount = $("#new_add_amount"); - if ($(this).prop("checked") === true){ - for(let i = 0; i < hide.length; i++){ + if ($(this).prop("checked") === true) { + for (let i = 0; i < hide.length; i++) { $(hide[i]).attr("disabled", "disabled"); } amount.removeAttr("disabled"); } - else{ - for(let i = 0; i < hide.length; i++){ - if ($(hide[i]).attr('id') !== "public_key"){ + else { + for (let i = 0; i < hide.length; i++) { + if ($(hide[i]).attr('id') !== "public_key") { $(hide[i]).removeAttr("disabled"); } } @@ -744,7 +744,7 @@ $("#available_ip_modal").on("show.bs.modal", () => { document.querySelector('#add_modal').classList.remove("ip_modal_open"); let ips = []; let $selected_ip_list = document.querySelector("#selected_ip_list"); - for (let i = 0; i < $selected_ip_list.childElementCount; i++){ + for (let i = 0; i < $selected_ip_list.childElementCount; i++) { ips.push($selected_ip_list.children[i].dataset.ip); } ips.forEach((ele) => window.configurations.triggerIp(ele)); @@ -753,8 +753,8 @@ $("#available_ip_modal").on("show.bs.modal", () => { /** * When IP Badge got click */ -$body.on("click", ".available-ip-badge", function(){ - $(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active"); +$body.on("click", ".available-ip-badge", function () { + $(".available-ip-item[data-ip='" + $(this).data("ip") + "']").removeClass("active"); $(this).remove(); }); @@ -771,9 +771,9 @@ $body.on("click", ".available-ip-item", function () { $("#search_available_ip").on("click", function () { window.configurations.ipModal().toggle(); let $allowed_ips = document.querySelector("#allowed_ips"); - if ($allowed_ips.value.length > 0){ + if ($allowed_ips.value.length > 0) { let s = $allowed_ips.value.split(","); - for (let i = 0; i < s.length; i++){ + for (let i = 0; i < s.length; i++) { s[i] = s[i].trim(); window.configurations.triggerIp(s[i]); } @@ -787,7 +787,7 @@ $("#confirm_ip").on("click", () => { window.configurations.ipModal().toggle(); let ips = []; let $selected_ip_list = $("#selected_ip_list"); - $selected_ip_list.children().each(function(){ + $selected_ip_list.children().each(function () { ips.push($(this).data("ip")); }); $("#allowed_ips").val(ips.join(", ")); @@ -803,12 +803,12 @@ $("#confirm_ip").on("click", () => { /** * When the QR-code button got clicked on each peer */ -$body.on("click", ".btn-qrcode-peer", function (){ +$body.on("click", ".btn-qrcode-peer", function () { let src = $(this).data('imgsrc'); $.ajax({ "url": src, "method": "GET" - }).done(function(res){ + }).done(function (res) { $("#qrcode_img").attr('src', res); window.configurations.qrcodeModal().toggle(); }); @@ -823,7 +823,7 @@ $body.on("click", ".btn-qrcode-peer", function (){ /** * When the delete button got clicked on each peer */ -$body.on("click", ".btn-delete-peer", function(){ +$body.on("click", ".btn-delete-peer", function () { let peer_id = $(this).attr("id"); $("#delete_peer").attr("peer_id", peer_id); window.configurations.deleteModal().toggle(); @@ -832,8 +832,8 @@ $body.on("click", ".btn-delete-peer", function(){ /** * When the confirm delete button clicked */ -$("#delete_peer").on("click",function(){ - $(this).attr("disabled","disabled"); +$("#delete_peer").on("click", function () { + $(this).attr("disabled", "disabled"); $(this).html("Deleting..."); let peer_id = $(this).attr("peer_id"); let config = $(this).attr("conf_id"); @@ -850,27 +850,27 @@ $("#delete_peer").on("click",function(){ /** * Handle when setting button got clicked for each peer */ -$body.on("click", ".btn-setting-peer", function(){ +$body.on("click", ".btn-setting-peer", function () { window.configurations.startProgressBar(); let peer_id = $(this).attr("id"); $("#save_peer_setting").attr("peer_id", peer_id); $.ajax({ method: "POST", - url: "/get_peer_data/"+$("#setting_modal").attr("conf_id"), - headers:{ + url: "/get_peer_data/" + $("#setting_modal").attr("conf_id"), + headers: { "Content-Type": "application/json" }, - data: JSON.stringify({"id": peer_id}), - success: function(response){ + data: JSON.stringify({ "id": peer_id }), + success: function (response) { let peer_name = ((response.name === "") ? "Untitled" : response.name); $("#setting_modal .peer_name").html(peer_name); $("#setting_modal #peer_name_textbox").val(response.name); $("#setting_modal #peer_private_key_textbox").val(response.private_key); $("#setting_modal #peer_DNS_textbox").val(response.DNS); - $("#setting_modal #peer_allowed_ip_textbox").val(response.allowed_ip); - $("#setting_modal #peer_endpoint_allowed_ips").val(response.endpoint_allowed_ip); + $("#setting_modal #peer_allowed_ip_textbox").val(response.allowed_ips); + $("#setting_modal #peer_endpoint_allowed_ips").val(response.endpoint_allowed_ips); $("#setting_modal #peer_mtu").val(response.mtu); - $("#setting_modal #peer_keep_alive").val(response.keep_alive); + $("#setting_modal #peer_keep_alive").val(response.keepalive); $("#setting_modal #peer_preshared_key_textbox").val(response.preshared_key); window.configurations.settingModal().toggle(); window.configurations.endProgressBar(); @@ -882,27 +882,27 @@ $body.on("click", ".btn-setting-peer", function(){ * Handle when setting modal is closing */ $('#setting_modal').on('hidden.bs.modal', function () { - $("#setting_peer_alert").addClass("d-none"); + $("#setting_peer_alert").addClass("d-none"); }); /** * Handle when private key text box in setting modal got changed */ -$("#peer_private_key_textbox").on("change",function(){ +$("#peer_private_key_textbox").on("change", function () { let $save_peer_setting = $("#save_peer_setting"); - if ($(this).val().length > 0){ + if ($(this).val().length > 0) { $.ajax({ - "url": "/check_key_match/"+$save_peer_setting.attr("conf_id"), + "url": "/check_key_match/" + $save_peer_setting.attr("conf_id"), "method": "POST", - "headers":{"Content-Type": "application/json"}, + "headers": { "Content-Type": "application/json" }, "data": JSON.stringify({ "private_key": $("#peer_private_key_textbox").val(), "public_key": $save_peer_setting.attr("peer_id") }) - }).done(function(res){ - if(res.status === "failed"){ + }).done(function (res) { + if (res.status === "failed") { $("#setting_peer_alert").html(res.status).removeClass("d-none"); - }else{ + } else { $("#setting_peer_alert").addClass("d-none"); } }); @@ -912,8 +912,8 @@ $("#peer_private_key_textbox").on("change",function(){ /** * When save peer setting button got clicked */ -$("#save_peer_setting").on("click",function (){ - $(this).attr("disabled","disabled"); +$("#save_peer_setting").on("click", function () { + $(this).attr("disabled", "disabled"); $(this).html("Saving..."); let $peer_DNS_textbox = $("#peer_DNS_textbox"); let $peer_allowed_ip_textbox = $("#peer_allowed_ip_textbox"); @@ -925,15 +925,15 @@ $("#save_peer_setting").on("click",function (){ let $peer_keep_alive = $("#peer_keep_alive"); if ($peer_DNS_textbox.val() !== "" && - $peer_allowed_ip_textbox.val() !== "" && $peer_endpoint_allowed_ips.val() !== ""){ + $peer_allowed_ip_textbox.val() !== "" && $peer_endpoint_allowed_ips.val() !== "") { let peer_id = $(this).attr("peer_id"); let conf_id = $(this).attr("conf_id"); let data_list = [$peer_name_textbox, $peer_DNS_textbox, $peer_private_key_textbox, $peer_preshared_key_textbox, $peer_allowed_ip_textbox, $peer_endpoint_allowed_ips, $peer_mtu, $peer_keep_alive]; - data_list.forEach((ele) => ele.attr("disabled","disabled")); + data_list.forEach((ele) => ele.attr("disabled", "disabled")); $.ajax({ method: "POST", - url: "/save_peer_setting/"+conf_id, - headers:{ + url: "/save_peer_setting/" + conf_id, + headers: { "Content-Type": "application/json" }, data: JSON.stringify({ @@ -941,16 +941,16 @@ $("#save_peer_setting").on("click",function (){ name: $peer_name_textbox.val(), DNS: $peer_DNS_textbox.val(), private_key: $peer_private_key_textbox.val(), - allowed_ip: $peer_allowed_ip_textbox.val(), - endpoint_allowed_ip: $peer_endpoint_allowed_ips.val(), + allowed_ips: $peer_allowed_ip_textbox.val(), + endpoint_allowed_ips: $peer_endpoint_allowed_ips.val(), MTU: $peer_mtu.val(), keep_alive: $peer_keep_alive.val(), preshared_key: $peer_preshared_key_textbox.val() }), - success: function (response){ - if (response.status === "failed"){ + success: function (response) { + if (response.status === "failed") { $("#setting_peer_alert").html(response.msg).removeClass("d-none"); - }else{ + } else { window.configurations.settingModal().toggle(); window.configurations.loadPeers($('#search_peer_textbox').val()); $('#alertToast').toast('show'); @@ -960,7 +960,7 @@ $("#save_peer_setting").on("click",function (){ data_list.forEach((ele) => ele.removeAttr("disabled")); } }); - }else{ + } else { $("#setting_peer_alert").html("Please fill in all required box.").removeClass("d-none"); $("#save_peer_setting").removeAttr("disabled").html("Save"); } @@ -969,11 +969,11 @@ $("#save_peer_setting").on("click",function (){ /** * Toggle show or hide for the private key textbox in the setting modal */ -$(".peer_private_key_textbox_switch").on("click",function (){ +$(".peer_private_key_textbox_switch").on("click", function () { let $peer_private_key_textbox = $("#peer_private_key_textbox"); - let mode = (($peer_private_key_textbox.attr('type') === 'password') ? "text":"password"); - let icon = (($peer_private_key_textbox.attr('type') === 'password') ? "bi bi-eye-slash-fill":"bi bi-eye-fill"); - $peer_private_key_textbox.attr('type',mode); + let mode = (($peer_private_key_textbox.attr('type') === 'password') ? "text" : "password"); + let icon = (($peer_private_key_textbox.attr('type') === 'password') ? "bi bi-eye-slash-fill" : "bi bi-eye-fill"); + $peer_private_key_textbox.attr('type', mode); $(".peer_private_key_textbox_switch i").removeClass().addClass(icon); }); @@ -1005,13 +1005,13 @@ $('#search_peer_textbox').on('keyup', function () { /** * Handle when sort peers changed */ -$body.on("change", "#sort_by_dropdown", function (){ +$body.on("change", "#sort_by_dropdown", function () { $.ajax({ - method:"POST", - data: JSON.stringify({'sort':$("#sort_by_dropdown option:selected").val()}), - headers:{"Content-Type": "application/json"}, + method: "POST", + data: JSON.stringify({ 'sort': $("#sort_by_dropdown option:selected").val() }), + headers: { "Content-Type": "application/json" }, url: "/update_dashboard_sort", - success: function (){ + success: function () { window.configurations.loadPeers($('#search_peer_textbox').val()); } }); @@ -1020,16 +1020,16 @@ $body.on("change", "#sort_by_dropdown", function (){ /** * Handle copy public key */ -$body.on("mouseenter", ".key", function(){ +$body.on("mouseenter", ".key", function () { let label = $(this).parent().siblings().children()[1]; label.style.opacity = "100"; -}).on("mouseout", ".key", function(){ +}).on("mouseout", ".key", function () { let label = $(this).parent().siblings().children()[1]; label.style.opacity = "0"; - setTimeout(function (){ + setTimeout(function () { label.innerHTML = "CLICK TO COPY"; - },200); -}).on("click", ".key", function(){ + }, 200); +}).on("click", ".key", function () { let label = $(this).parent().siblings().children()[1]; window.configurations.copyToClipboard($(this)); label.innerHTML = "COPIED!"; @@ -1038,16 +1038,16 @@ $body.on("mouseenter", ".key", function(){ /** * Handle when interval button got clicked */ -$body.on("click", ".update_interval", function(){ +$body.on("click", ".update_interval", function () { $(".interval-btn-group button").removeClass("active"); let _new = $(this); _new.addClass("active"); let interval = $(this).data("refresh-interval"); $.ajax({ - method:"POST", - data: "interval="+$(this).data("refresh-interval"), + method: "POST", + data: "interval=" + $(this).data("refresh-interval"), url: "/update_dashboard_refresh_interval", - success: function (res){ + success: function (res) { window.configurations.updateRefreshInterval(res, interval); } }); @@ -1056,34 +1056,34 @@ $body.on("click", ".update_interval", function(){ /** * Handle when refresh button got clicked */ -$body.on("click", ".refresh", function (){ +$body.on("click", ".refresh", function () { window.configurations.loadPeers($('#search_peer_textbox').val()); }); /** * Handle when display mode button got clicked */ -$body.on("click", ".display_mode", function(){ +$body.on("click", ".display_mode", function () { $(".display-btn-group button").removeClass("active"); $(this).addClass("active"); let display_mode = $(this).data("display-mode"); $.ajax({ - method:"GET", - url: "/switch_display_mode/"+$(this).data("display-mode"), - success: function (res){ - if (res === "true"){ - if (display_mode === "list"){ - Array($(".peer_list").children()).forEach(function(child){ - $(child).removeClass().addClass("col-12"); - }); - window.configurations.showToast("Displaying as List"); - }else{ - Array($(".peer_list").children()).forEach(function(child){ - $(child).removeClass().addClass("col-sm-6 col-lg-4"); - }); - window.configurations.showToast("Displaying as Grids"); + method: "GET", + url: "/switch_display_mode/" + $(this).data("display-mode"), + success: function (res) { + if (res === "true") { + if (display_mode === "list") { + Array($(".peer_list").children()).forEach(function (child) { + $(child).removeClass().addClass("col-12"); + }); + window.configurations.showToast("Displaying as List"); + } else { + Array($(".peer_list").children()).forEach(function (child) { + $(child).removeClass().addClass("col-sm-6 col-lg-4"); + }); + window.configurations.showToast("Displaying as Grids"); + } } - } } }); }); @@ -1095,35 +1095,35 @@ $body.on("click", ".display_mode", function(){ * ================= */ let $setting_btn_menu = $(".setting_btn_menu"); -$setting_btn_menu.css("top", ($setting_btn_menu.height() + 54)*(-1)); +$setting_btn_menu.css("top", ($setting_btn_menu.height() + 54) * (-1)); let $setting_btn = $(".setting_btn"); /** * When the menu button got clicked */ -$setting_btn.on("click", function(){ - if ($setting_btn_menu.hasClass("show")){ +$setting_btn.on("click", function () { + if ($setting_btn_menu.hasClass("show")) { $setting_btn_menu.removeClass("showing"); - setTimeout(function(){ + setTimeout(function () { $setting_btn_menu.removeClass("show"); }, 201); - }else{ - $setting_btn_menu.addClass("show"); - setTimeout(function(){ - $setting_btn_menu.addClass("showing"); - },10); + } else { + $setting_btn_menu.addClass("show"); + setTimeout(function () { + $setting_btn_menu.addClass("showing"); + }, 10); } }); /** * Whenever the user clicked, if it is outside the menu and the menu is opened, hide the menu */ -$("html").on("click", function(r){ - if (document.querySelector(".setting_btn") !== r.target){ - if (!document.querySelector(".setting_btn").contains(r.target)){ - if (!document.querySelector(".setting_btn_menu").contains(r.target)){ +$("html").on("click", function (r) { + if (document.querySelector(".setting_btn") !== r.target) { + if (!document.querySelector(".setting_btn").contains(r.target)) { + if (!document.querySelector(".setting_btn_menu").contains(r.target)) { $setting_btn_menu.removeClass("showing"); - setTimeout(function(){ + setTimeout(function () { $setting_btn_menu.removeClass("show"); }, 310); } @@ -1149,7 +1149,7 @@ $("#delete_peers_by_bulk_btn").on("click", () => { if (peer.name === "") { name = "Untitled Peer"; } else { name = peer.name; } $delete_bulk_modal_list.append(''+name+'
'+peer.id+'
'); + peer.id + '" data-name="' + name + '">' + name + '
' + peer.id + ''); }); window.configurations.deleteBulkModal().toggle(); }); @@ -1157,9 +1157,9 @@ $("#delete_peers_by_bulk_btn").on("click", () => { /** * When the item or tag of delete peers by bulk got clicked */ -$body.on("click", ".delete-bulk-peer-item", function(){ +$body.on("click", ".delete-bulk-peer-item", function () { window.configurations.toggleDeleteByBulkIP($(this)); -}).on("click", ".delete-peer-bulk-badge", function(){ +}).on("click", ".delete-peer-bulk-badge", function () { window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='" + $(this).data("id") + "']")); }); @@ -1169,10 +1169,10 @@ let $selected_peer_list = document.getElementById("selected_peer_list"); * The change observer to observe when user choose 1 or more peers to delete * @type {MutationObserver} */ -let changeObserver = new MutationObserver(function(){ - if ($selected_peer_list.hasChildNodes()){ +let changeObserver = new MutationObserver(function () { + if ($selected_peer_list.hasChildNodes()) { $("#confirm_delete_bulk_peers").removeAttr("disabled"); - }else{ + } else { $("#confirm_delete_bulk_peers").attr("disabled", "disabled"); } }); @@ -1187,19 +1187,19 @@ let confirm_delete_bulk_peers_interval; /** * When the user clicked the delete button in the delete peers by bulk */ -$("#confirm_delete_bulk_peers").on("click", function(){ +$("#confirm_delete_bulk_peers").on("click", function () { let btn = $(this); - if (confirm_delete_bulk_peers_interval !== undefined){ + if (confirm_delete_bulk_peers_interval !== undefined) { clearInterval(confirm_delete_bulk_peers_interval); confirm_delete_bulk_peers_interval = undefined; btn.html("Delete"); - }else{ + } else { let timer = 5; btn.html(`Deleting in ${timer} secs... Click to cancel`); - confirm_delete_bulk_peers_interval = setInterval(function(){ + confirm_delete_bulk_peers_interval = setInterval(function () { timer -= 1; btn.html(`Deleting in ${timer} secs... Click to cancel`); - if (timer === 0){ + if (timer === 0) { btn.html(`Deleting...`); btn.attr("disabled", "disabled"); let ips = []; @@ -1215,23 +1215,23 @@ $("#confirm_delete_bulk_peers").on("click", function(){ /** * Select all peers to delete */ -$("#select_all_delete_bulk_peers").on("click", function(){ - $(".delete-bulk-peer-item").each(function(){ - if (!$(this).hasClass("active")) { - window.configurations.toggleDeleteByBulkIP($(this)); - } - }); +$("#select_all_delete_bulk_peers").on("click", function () { + $(".delete-bulk-peer-item").each(function () { + if (!$(this).hasClass("active")) { + window.configurations.toggleDeleteByBulkIP($(this)); + } + }); }); /** * When delete peers by bulk window is hidden */ -$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal", function(){ - $(".delete-bulk-peer-item").each(function(){ - if ($(this).hasClass("active")) { - window.configurations.toggleDeleteByBulkIP($(this)); - } - }); +$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal", function () { + $(".delete-bulk-peer-item").each(function () { + if ($(this).hasClass("active")) { + window.configurations.toggleDeleteByBulkIP($(this)); + } + }); }); /** @@ -1243,13 +1243,13 @@ $(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal", functi /** * When the download peers button got clicked */ -$body.on("click", ".btn-download-peer", function(e){ +$body.on("click", ".btn-download-peer", function (e) { e.preventDefault(); let link = $(this).attr("href"); $.ajax({ "url": link, "method": "GET", - success: function(res){ + success: function (res) { window.configurations.downloadOneConfig(res); } }); @@ -1258,15 +1258,15 @@ $body.on("click", ".btn-download-peer", function(e){ /** * When the download all peers got clicked */ -$("#download_all_peers").on("click", function(){ +$("#download_all_peers").on("click", function () { $.ajax({ "url": $(this).data("url"), "method": "GET", - success: function(res){ - if (res.peers.length > 0){ - window.wireguard.generateZipFiles(res); - window.configurations.showToast("Peers' zip file download successful!"); - }else{ + success: function (res) { + if (res.peers.length > 0) { + window.wireguard.generateZipFiles(res); + window.configurations.showToast("Peers' zip file download successful!"); + } else { window.configurations.showToast("Oops! There are no peer can be download."); } } diff --git a/src/static/js/configuration.min.js b/src/static/js/configuration.min.js index 3ee86f8..271e65f 100644 --- a/src/static/js/configuration.min.js +++ b/src/static/js/configuration.min.js @@ -1 +1 @@ -(function(){let configuration_interval;let configuration_timeout=0;let $progress_bar=$(".progress-bar");let bootstrapModalConfig={keyboard:false,backdrop:"static"};let addModal=new bootstrap.Modal(document.getElementById("add_modal"),bootstrapModalConfig);let deleteBulkModal=new bootstrap.Modal(document.getElementById("delete_bulk_modal"),bootstrapModalConfig);let ipModal=new bootstrap.Modal(document.getElementById("available_ip_modal"),bootstrapModalConfig);let qrcodeModal=new bootstrap.Modal(document.getElementById("qrcode_modal"),bootstrapModalConfig);let settingModal=new bootstrap.Modal(document.getElementById("setting_modal"),bootstrapModalConfig);let deleteModal=new bootstrap.Modal(document.getElementById("delete_modal"),bootstrapModalConfig);$("[data-toggle='tooltip']").tooltip();$("[data-toggle='popover']").popover();function configurationAlert(response){if(response.listen_port===""&&response.status==="stopped"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Peer QR Code and configuration file download required a specified Listen Port.";document.querySelector("#config_info_alert").appendChild(configAlert)}if(response.conf_address==="N/A"){let configAlert=document.createElement("div");configAlert.classList.add("alert");configAlert.classList.add("alert-warning");configAlert.setAttribute("role","alert");configAlert.innerHTML="Configuration Address need to be specified to have peers connect to it.";document.querySelector("#config_info_alert").appendChild(configAlert)}}function configurationHeader(response){let $conf_status_btn=document.getElementById("conf_status_btn");if(response.checked==="checked"){$conf_status_btn.innerHTML=` ON`}else{$conf_status_btn.innerHTML=` OFF`}$conf_status_btn.classList.remove("info_loading");document.querySelectorAll("#sort_by_dropdown option").forEach(ele=>ele.removeAttribute("selected"));document.querySelector(`#sort_by_dropdown option[value="${response.sort_tag}"]`).setAttribute("selected","selected");document.querySelectorAll(".interval-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-refresh-interval="${response.dashboard_refresh_interval}"]`).classList.add("active");document.querySelectorAll(".display-btn-group button").forEach(ele=>ele.classList.remove("active"));document.querySelector(`button[data-display-mode="${response.peer_display_mode}"]`).classList.add("active");document.querySelector("#conf_status").innerHTML=`${response.status}`;document.querySelector("#conf_connected_peers").innerHTML=response.running_peer;document.querySelector("#conf_total_data_usage").innerHTML=`${response.total_data_usage[0]} GB`;document.querySelector("#conf_total_data_received").innerHTML=`${response.total_data_usage[2]} GB`;document.querySelector("#conf_total_data_sent").innerHTML=`${response.total_data_usage[1]} GB`;document.querySelector("#conf_public_key").innerHTML=response.public_key;document.querySelector("#conf_listen_port").innerHTML=response.listen_port===""?"N/A":response.listen_port;document.querySelector("#conf_address").innerHTML=response.conf_address;document.querySelectorAll(".info h6").forEach(ele=>ele.classList.remove("info_loading"))}function configurationPeers(response){let result="";if(response.peer_data.length===0){document.querySelector(".peer_list").innerHTML=`

Oops! No peers found ‘︿’

`}else{let display_mode=response.peer_display_mode==="list"?"col-12":"col-sm-6 col-lg-4";response.peer_data.forEach(function(peer){let total_r=0;let total_s=0;total_r+=peer.cumu_receive;total_s+=peer.cumu_sent;let spliter='
';let peer_name='
'+'
'+(peer.name===""?"Untitled":peer.name)+"
"+'
'+"
";let peer_transfer='

'+roundN(peer.total_receive+total_r,4)+' GB

'+roundN(peer.total_sent+total_s,4)+" GB

";let peer_key='
PEERCLICK TO COPY
'+peer.id+"
";let peer_allowed_ip='
ALLOWED IP
'+peer.allowed_ip+"
";let peer_latest_handshake='
LATEST HANDSHAKE
'+peer.latest_handshake+"
";let peer_endpoint='
END POINT
'+peer.endpoint+"
";let peer_control='

';if(peer.private_key!==""){peer_control+=''}peer_control+="
";let html='
'+'
'+'
'+'
'+peer_name+spliter+peer_transfer+peer_key+peer_allowed_ip+peer_latest_handshake+spliter+peer_endpoint+spliter+peer_control+"
"+"
"+"
"+"
";result+=html});document.querySelector(".peer_list").innerHTML=result;if(response.dashboard_refresh_interval!==configuration_timeout){configuration_timeout=response.dashboard_refresh_interval;removeConfigurationInterval();setConfigurationInterval()}}}function addPeersByBulk(){let $new_add_amount=$("#new_add_amount");$add_peer.setAttribute("disabled","disabled");$add_peer.innerHTML=`Adding ${$new_add_amount.val()} peers...`;let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_MTU=$("#new_add_MTU");let $new_add_keep_alive=$("#new_add_keep_alive");let $enable_preshare_key=$("#enable_preshare_key");let data_list=[$new_add_DNS,$new_add_endpoint_allowed_ip,$new_add_MTU,$new_add_keep_alive];if($new_add_amount.val()>0&&!$new_add_amount.hasClass("is-invalid")){if($new_add_DNS.val()!==""&&$new_add_endpoint_allowed_ip.val()!==""){let conf=$add_peer.getAttribute("conf_id");let keys=[];for(let i=0;i<$new_add_amount.val();i++){keys.push(window.wireguard.generateKeypair())}$.ajax({method:"POST",url:"/add_peer_bulk/"+conf,headers:{"Content-Type":"application/json"},data:JSON.stringify({DNS:$new_add_DNS.val(),endpoint_allowed_ip:$new_add_endpoint_allowed_ip.val(),MTU:$new_add_MTU.val(),keep_alive:$new_add_keep_alive.val(),enable_preshared_key:$enable_preshare_key.prop("checked"),keys:keys,amount:$new_add_amount.val()}),success:function(response){if(response!=="true"){$("#add_peer_alert").html(response).removeClass("d-none");data_list.forEach(ele=>ele.removeAttr("disabled"));$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save"}else{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast($new_add_amount.val()+" peers added successful!");window.configurations.addModal().toggle()}}})}else{$("#add_peer_alert").html("Please fill in all required box.").removeClass("d-none");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Add"}}else{$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Add"}}function deletePeers(config,peer_ids){$.ajax({method:"POST",url:"/remove_peer/"+config,headers:{"Content-Type":"application/json"},data:JSON.stringify({action:"delete",peer_ids:peer_ids}),success:function(response){if(response!=="true"){if(window.configurations.deleteModal()._isShown){$("#remove_peer_alert").html(response+$("#add_peer_alert").html()).removeClass("d-none");$("#delete_peer").removeAttr("disabled").html("Delete")}if(window.configurations.deleteBulkModal()._isShown){let $bulk_remove_peer_alert=$("#bulk_remove_peer_alert");$bulk_remove_peer_alert.html(response+$bulk_remove_peer_alert.html()).removeClass("d-none");$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete")}}else{if(window.configurations.deleteModal()._isShown){window.configurations.deleteModal().toggle()}if(window.configurations.deleteBulkModal()._isShown){$("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete");$("#selected_peer_list").html("");$(".delete-bulk-peer-item.active").removeClass("active");window.configurations.deleteBulkModal().toggle()}window.configurations.loadPeers($("#search_peer_textbox").val());$("#alertToast").toast("show");$("#alertToast .toast-body").html("Peer deleted!");$("#delete_peer").removeAttr("disabled").html("Delete")}}})}function noResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("active"));setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.add("show"));document.querySelector("#right_body").classList.add("no-responding");document.querySelector(".navbar").classList.add("no-responding")},10)}function removeNoResponding(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("show"));document.querySelector("#right_body").classList.remove("no-responding");document.querySelector(".navbar").classList.remove("no-responding");setTimeout(function(){document.querySelectorAll(".no-response").forEach(ele=>ele.classList.remove("active"))},1010)}function setConfigurationInterval(){configuration_interval=setInterval(function(){loadPeers($("#search_peer_textbox").val())},configuration_timeout)}function removeConfigurationInterval(){clearInterval(configuration_interval)}function startProgressBar(){$progress_bar.css("width","0%").css("opacity","100").css("background","rgb(255,69,69)").css("background","linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)").css("width","25%");setTimeout(function(){stillLoadingProgressBar()},300)}function stillLoadingProgressBar(){$progress_bar.css("transition","3s ease-in-out").css("width","75%")}function endProgressBar(){$progress_bar.css("transition","0.3s ease-in-out").css("width","100%");setTimeout(function(){$progress_bar.css("opacity","0")},250)}function roundN(value,digits){let tenToN=10**digits;return Math.round(value*tenToN)/tenToN}let d1=new Date;let time=0;let count=0;function loadPeers(searchString){startProgressBar();d1=new Date;$.ajax({method:"GET",url:`/get_config/${conf_name}?search=${encodeURIComponent(searchString)}`,headers:{"Content-Type":"application/json"}}).done(function(response){removeNoResponding();peers=response.peer_data;configurationAlert(response);configurationHeader(response);configurationPeers(response);$(".dot.dot-running").attr("title","Peer Connected").tooltip();$(".dot.dot-stopped").attr("title","Peer Disconnected").tooltip();$("i[data-toggle='tooltip']").tooltip();endProgressBar();let d2=new Date;let seconds=d2-d1;time+=seconds;count+=1;console.log(`Average ${time/count}ms`);$("#peer_loading_time").html(`Peer Loading Time: ${seconds}ms`)}).fail(function(){noResponding()})}function generate_key(){let keys=window.wireguard.generateKeypair();document.querySelector("#private_key").value=keys.privateKey;document.querySelector("#public_key").value=keys.publicKey;document.querySelector("#add_peer_alert").classList.add("d-none");document.querySelector("#re_generate_key i").classList.remove("rotating");document.querySelector("#enable_preshare_key").value=keys.presharedKey}function showToast(msg){$("#alertToast").toast("show");$("#alertToast .toast-body").html(msg)}function updateRefreshInterval(res,interval){if(res==="true"){configuration_timeout=interval;removeConfigurationInterval();setConfigurationInterval();showToast("Refresh Interval set to "+Math.round(interval/1e3)+" seconds")}else{$(".interval-btn-group button").removeClass("active");$('.interval-btn-group button[data-refresh-interval="'+configuration_timeout+'"]').addClass("active");showToast("Refresh Interval set unsuccessful")}}function cleanIp(val){let clean_ip=val.split(",");for(let i=0;i${ip}`}}}function download_one_config(conf){let link=document.createElement("a");link.download=conf.filename;let blob=new Blob([conf.content],{type:"text/conf"});link.href=window.URL.createObjectURL(blob);link.click()}function toggleBulkIP(element){let $selected_peer_list=$("#selected_peer_list");let id=element.data("id");let name=element.data("name")===""?"Untitled Peer":element.data("name");if(element.hasClass("active")){element.removeClass("active");$("#selected_peer_list .badge[data-id='"+id+"']").remove()}else{element.addClass("active");$selected_peer_list.append(''+name+" - "+id+"")}}function copyToClipboard(element){let $temp=$("");$body.append($temp);$temp.val($(element).text()).trigger("select");document.execCommand("copy");$temp.remove()}function getAvailableIps(){$.ajax({url:`/available_ips/${$add_peer.getAttribute("conf_id")}`,method:"GET"}).done(function(res){available_ips=res;let $list_group=document.querySelector("#available_ip_modal .modal-body .list-group");$list_group.innerHTML="";document.querySelector("#allowed_ips").value=available_ips[0];available_ips.forEach(ip=>$list_group.innerHTML+=`${ip}`)})}window.configurations={addModal:()=>{return addModal},deleteBulkModal:()=>{return deleteBulkModal},deleteModal:()=>{return deleteModal},ipModal:()=>{return ipModal},qrcodeModal:()=>{return qrcodeModal},settingModal:()=>{return settingModal},loadPeers:searchString=>{loadPeers(searchString)},addPeersByBulk:()=>{addPeersByBulk()},deletePeers:(config,peers_ids)=>{deletePeers(config,peers_ids)},getAvailableIps:()=>{getAvailableIps()},generateKeyPair:()=>{generate_key()},showToast:message=>{showToast(message)},updateRefreshInterval:(res,interval)=>{updateRefreshInterval(res,interval)},copyToClipboard:element=>{copyToClipboard(element)},toggleDeleteByBulkIP:element=>{toggleBulkIP(element)},downloadOneConfig:conf=>{download_one_config(conf)},triggerIp:ip=>{trigger_ip(ip)},cleanIp:val=>{return cleanIp(val)},startProgressBar:()=>{startProgressBar()},stillLoadingProgressBar:()=>{stillLoadingProgressBar()},endProgressBar:()=>{endProgressBar()}}})();let $body=$("body");let available_ips=[];let $add_peer=document.getElementById("save_peer");document.querySelector(".add_btn").addEventListener("click",()=>{window.configurations.addModal().toggle()});document.querySelector(".info").addEventListener("click",event=>{let selector=document.querySelector(".switch");if(selector.contains(event.target)){selector.style.display="none";document.querySelector("div[role=status]").style.display="inline-block";location.replace(`/switch/${selector.getAttribute("id")}`)}});document.querySelector("#private_key").addEventListener("change",event=>{let publicKey=document.querySelector("#public_key");if(event.target.value.length===44){publicKey.value=window.wireguard.generatePublicKey(event.target.value);publicKey.setAttribute("disabled","disabled")}else{publicKey.attributes.removeNamedItem("disabled");publicKey.value=""}});$("#add_modal").on("show.bs.modal",function(){window.configurations.generateKeyPair();window.configurations.getAvailableIps()}).on("hide.bs.modal",function(){$("#allowed_ips_indicator").html("")});$("#re_generate_key").on("click",function(){$("#public_key").attr("disabled","disabled");$("#re_generate_key i").addClass("rotating");window.configurations.generateKeyPair()});$("#allowed_ips").on("keyup",function(){let s=window.configurations.cleanIp($(this).val());s=s.split(",");if(available_ips.includes(s[s.length-1])){$("#allowed_ips_indicator").removeClass().addClass("text-success").html('')}else{$("#allowed_ips_indicator").removeClass().addClass("text-warning").html('')}});$("#peer_name_textbox").on("keyup",function(){$(".peer_name").html($(this).val())});$add_peer.addEventListener("click",function(){let $bulk_add=$("#bulk_add");if($bulk_add.prop("checked")){if(!$("#new_add_amount").hasClass("is-invalid")){window.configurations.addPeersByBulk()}}else{let $public_key=$("#public_key");let $private_key=$("#private_key");let $allowed_ips=$("#allowed_ips");$allowed_ips.val(window.configurations.cleanIp($allowed_ips.val()));let $new_add_DNS=$("#new_add_DNS");$new_add_DNS.val(window.configurations.cleanIp($new_add_DNS.val()));let $new_add_endpoint_allowed_ip=$("#new_add_endpoint_allowed_ip");$new_add_endpoint_allowed_ip.val(window.configurations.cleanIp($new_add_endpoint_allowed_ip.val()));let $new_add_name=$("#new_add_name");let $new_add_MTU=$("#new_add_MTU");let $new_add_keep_alive=$("#new_add_keep_alive");let $enable_preshare_key=$("#enable_preshare_key");$add_peer.setAttribute("disabled","disabled");$add_peer.innerHTML="Adding...";if($allowed_ips.val()!==""&&$public_key.val()!==""&&$new_add_DNS.val()!==""&&$new_add_endpoint_allowed_ip.val()!==""){let conf=$add_peer.getAttribute("conf_id");let data_list=[$private_key,$allowed_ips,$new_add_name,$new_add_DNS,$new_add_endpoint_allowed_ip,$new_add_MTU,$new_add_keep_alive];data_list.forEach(ele=>ele.attr("disabled","disabled"));$.ajax({method:"POST",url:"/add_peer/"+conf,headers:{"Content-Type":"application/json"},data:JSON.stringify({private_key:$private_key.val(),public_key:$public_key.val(),allowed_ips:$allowed_ips.val(),name:$new_add_name.val(),DNS:$new_add_DNS.val(),endpoint_allowed_ip:$new_add_endpoint_allowed_ip.val(),MTU:$new_add_MTU.val(),keep_alive:$new_add_keep_alive.val(),enable_preshared_key:$enable_preshare_key.prop("checked"),preshared_key:$enable_preshare_key.val()}),success:function(response){if(response!=="true"){$("#add_peer_alert").html(response).removeClass("d-none");data_list.forEach(ele=>ele.removeAttr("disabled"));$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save"}else{window.configurations.loadPeers("");data_list.forEach(ele=>ele.removeAttr("disabled"));$("#add_peer_form").trigger("reset");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Save";window.configurations.showToast("Add peer successful!");window.configurations.addModal().toggle()}}})}else{$("#add_peer_alert").html("Please fill in all required box.").removeClass("d-none");$add_peer.removeAttribute("disabled");$add_peer.innerHTML="Add"}}});$("#new_add_amount").on("keyup",function(){let $bulk_amount_validation=$("#bulk_amount_validation");if($(this).val().length>0){if(isNaN($(this).val())){$(this).removeClass("is-valid").addClass("is-invalid");$bulk_amount_validation.html("Please enter a valid integer")}else if($(this).val()>available_ips.length){$(this).removeClass("is-valid").addClass("is-invalid");$bulk_amount_validation.html(`Cannot create more than ${available_ips.length} peers.`)}else if($(this).val()<1){$(this).removeClass("is-valid").addClass("is-invalid");$bulk_amount_validation.html("Please enter at least 1 or more.")}else{$(this).removeClass("is-invalid").addClass("is-valid")}}else{$(this).removeClass("is-invalid").removeClass("is-valid")}});$("#bulk_add").on("change",function(){let hide=$(".non-bulk").find("input");let amount=$("#new_add_amount");if($(this).prop("checked")===true){for(let i=0;i{document.querySelector("#add_modal").classList.add("ip_modal_open")}).on("hidden.bs.modal",()=>{document.querySelector("#add_modal").classList.remove("ip_modal_open");let ips=[];let $selected_ip_list=document.querySelector("#selected_ip_list");for(let i=0;i<$selected_ip_list.childElementCount;i++){ips.push($selected_ip_list.children[i].dataset.ip)}ips.forEach(ele=>window.configurations.triggerIp(ele))});$body.on("click",".available-ip-badge",function(){$(".available-ip-item[data-ip='"+$(this).data("ip")+"']").removeClass("active");$(this).remove()});$body.on("click",".available-ip-item",function(){window.configurations.triggerIp($(this).data("ip"))});$("#search_available_ip").on("click",function(){window.configurations.ipModal().toggle();let $allowed_ips=document.querySelector("#allowed_ips");if($allowed_ips.value.length>0){let s=$allowed_ips.value.split(",");for(let i=0;i{window.configurations.ipModal().toggle();let ips=[];let $selected_ip_list=$("#selected_ip_list");$selected_ip_list.children().each(function(){ips.push($(this).data("ip"))});$("#allowed_ips").val(ips.join(", "));ips.forEach(ele=>window.configurations.triggerIp(ele))});$body.on("click",".btn-qrcode-peer",function(){let src=$(this).data("imgsrc");$.ajax({url:src,method:"GET"}).done(function(res){$("#qrcode_img").attr("src",res);window.configurations.qrcodeModal().toggle()})});$body.on("click",".btn-delete-peer",function(){let peer_id=$(this).attr("id");$("#delete_peer").attr("peer_id",peer_id);window.configurations.deleteModal().toggle()});$("#delete_peer").on("click",function(){$(this).attr("disabled","disabled");$(this).html("Deleting...");let peer_id=$(this).attr("peer_id");let config=$(this).attr("conf_id");let peer_ids=[peer_id];window.configurations.deletePeers(config,peer_ids)});$body.on("click",".btn-setting-peer",function(){window.configurations.startProgressBar();let peer_id=$(this).attr("id");$("#save_peer_setting").attr("peer_id",peer_id);$.ajax({method:"POST",url:"/get_peer_data/"+$("#setting_modal").attr("conf_id"),headers:{"Content-Type":"application/json"},data:JSON.stringify({id:peer_id}),success:function(response){let peer_name=response.name===""?"Untitled":response.name;$("#setting_modal .peer_name").html(peer_name);$("#setting_modal #peer_name_textbox").val(response.name);$("#setting_modal #peer_private_key_textbox").val(response.private_key);$("#setting_modal #peer_DNS_textbox").val(response.DNS);$("#setting_modal #peer_allowed_ip_textbox").val(response.allowed_ip);$("#setting_modal #peer_endpoint_allowed_ips").val(response.endpoint_allowed_ip);$("#setting_modal #peer_mtu").val(response.mtu);$("#setting_modal #peer_keep_alive").val(response.keep_alive);$("#setting_modal #peer_preshared_key_textbox").val(response.preshared_key);window.configurations.settingModal().toggle();window.configurations.endProgressBar()}})});$("#setting_modal").on("hidden.bs.modal",function(){$("#setting_peer_alert").addClass("d-none")});$("#peer_private_key_textbox").on("change",function(){let $save_peer_setting=$("#save_peer_setting");if($(this).val().length>0){$.ajax({url:"/check_key_match/"+$save_peer_setting.attr("conf_id"),method:"POST",headers:{"Content-Type":"application/json"},data:JSON.stringify({private_key:$("#peer_private_key_textbox").val(),public_key:$save_peer_setting.attr("peer_id")})}).done(function(res){if(res.status==="failed"){$("#setting_peer_alert").html(res.status).removeClass("d-none")}else{$("#setting_peer_alert").addClass("d-none")}})}});$("#save_peer_setting").on("click",function(){$(this).attr("disabled","disabled");$(this).html("Saving...");let $peer_DNS_textbox=$("#peer_DNS_textbox");let $peer_allowed_ip_textbox=$("#peer_allowed_ip_textbox");let $peer_endpoint_allowed_ips=$("#peer_endpoint_allowed_ips");let $peer_name_textbox=$("#peer_name_textbox");let $peer_private_key_textbox=$("#peer_private_key_textbox");let $peer_preshared_key_textbox=$("#peer_preshared_key_textbox");let $peer_mtu=$("#peer_mtu");let $peer_keep_alive=$("#peer_keep_alive");if($peer_DNS_textbox.val()!==""&&$peer_allowed_ip_textbox.val()!==""&&$peer_endpoint_allowed_ips.val()!==""){let peer_id=$(this).attr("peer_id");let conf_id=$(this).attr("conf_id");let data_list=[$peer_name_textbox,$peer_DNS_textbox,$peer_private_key_textbox,$peer_preshared_key_textbox,$peer_allowed_ip_textbox,$peer_endpoint_allowed_ips,$peer_mtu,$peer_keep_alive];data_list.forEach(ele=>ele.attr("disabled","disabled"));$.ajax({method:"POST",url:"/save_peer_setting/"+conf_id,headers:{"Content-Type":"application/json"},data:JSON.stringify({id:peer_id,name:$peer_name_textbox.val(),DNS:$peer_DNS_textbox.val(),private_key:$peer_private_key_textbox.val(),allowed_ip:$peer_allowed_ip_textbox.val(),endpoint_allowed_ip:$peer_endpoint_allowed_ips.val(),MTU:$peer_mtu.val(),keep_alive:$peer_keep_alive.val(),preshared_key:$peer_preshared_key_textbox.val()}),success:function(response){if(response.status==="failed"){$("#setting_peer_alert").html(response.msg).removeClass("d-none")}else{window.configurations.settingModal().toggle();window.configurations.loadPeers($("#search_peer_textbox").val());$("#alertToast").toast("show");$("#alertToast .toast-body").html("Peer Saved!")}$("#save_peer_setting").removeAttr("disabled").html("Save");data_list.forEach(ele=>ele.removeAttr("disabled"))}})}else{$("#setting_peer_alert").html("Please fill in all required box.").removeClass("d-none");$("#save_peer_setting").removeAttr("disabled").html("Save")}});$(".peer_private_key_textbox_switch").on("click",function(){let $peer_private_key_textbox=$("#peer_private_key_textbox");let mode=$peer_private_key_textbox.attr("type")==="password"?"text":"password";let icon=$peer_private_key_textbox.attr("type")==="password"?"bi bi-eye-slash-fill":"bi bi-eye-fill";$peer_private_key_textbox.attr("type",mode);$(".peer_private_key_textbox_switch i").removeClass().addClass(icon)});let typingTimer;let doneTypingInterval=200;$("#search_peer_textbox").on("keyup",function(){clearTimeout(typingTimer);typingTimer=setTimeout(()=>{window.configurations.loadPeers($(this).val())},doneTypingInterval)}).on("keydown",function(){clearTimeout(typingTimer)});$body.on("change","#sort_by_dropdown",function(){$.ajax({method:"POST",data:JSON.stringify({sort:$("#sort_by_dropdown option:selected").val()}),headers:{"Content-Type":"application/json"},url:"/update_dashboard_sort",success:function(){window.configurations.loadPeers($("#search_peer_textbox").val())}})});$body.on("mouseenter",".key",function(){let label=$(this).parent().siblings().children()[1];label.style.opacity="100"}).on("mouseout",".key",function(){let label=$(this).parent().siblings().children()[1];label.style.opacity="0";setTimeout(function(){label.innerHTML="CLICK TO COPY"},200)}).on("click",".key",function(){let label=$(this).parent().siblings().children()[1];window.configurations.copyToClipboard($(this));label.innerHTML="COPIED!"});$body.on("click",".update_interval",function(){$(".interval-btn-group button").removeClass("active");let _new=$(this);_new.addClass("active");let interval=$(this).data("refresh-interval");$.ajax({method:"POST",data:"interval="+$(this).data("refresh-interval"),url:"/update_dashboard_refresh_interval",success:function(res){window.configurations.updateRefreshInterval(res,interval)}})});$body.on("click",".refresh",function(){window.configurations.loadPeers($("#search_peer_textbox").val())});$body.on("click",".display_mode",function(){$(".display-btn-group button").removeClass("active");$(this).addClass("active");let display_mode=$(this).data("display-mode");$.ajax({method:"GET",url:"/switch_display_mode/"+$(this).data("display-mode"),success:function(res){if(res==="true"){if(display_mode==="list"){Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-12")});window.configurations.showToast("Displaying as List")}else{Array($(".peer_list").children()).forEach(function(child){$(child).removeClass().addClass("col-sm-6 col-lg-4")});window.configurations.showToast("Displaying as Grids")}}}})});let $setting_btn_menu=$(".setting_btn_menu");$setting_btn_menu.css("top",($setting_btn_menu.height()+54)*-1);let $setting_btn=$(".setting_btn");$setting_btn.on("click",function(){if($setting_btn_menu.hasClass("show")){$setting_btn_menu.removeClass("showing");setTimeout(function(){$setting_btn_menu.removeClass("show")},201)}else{$setting_btn_menu.addClass("show");setTimeout(function(){$setting_btn_menu.addClass("showing")},10)}});$("html").on("click",function(r){if(document.querySelector(".setting_btn")!==r.target){if(!document.querySelector(".setting_btn").contains(r.target)){if(!document.querySelector(".setting_btn_menu").contains(r.target)){$setting_btn_menu.removeClass("showing");setTimeout(function(){$setting_btn_menu.removeClass("show")},310)}}}});$("#delete_peers_by_bulk_btn").on("click",()=>{let $delete_bulk_modal_list=$("#delete_bulk_modal .list-group");$delete_bulk_modal_list.html("");peers.forEach(peer=>{let name;if(peer.name===""){name="Untitled Peer"}else{name=peer.name}$delete_bulk_modal_list.append(''+name+"
"+peer.id+"
")});window.configurations.deleteBulkModal().toggle()});$body.on("click",".delete-bulk-peer-item",function(){window.configurations.toggleDeleteByBulkIP($(this))}).on("click",".delete-peer-bulk-badge",function(){window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='"+$(this).data("id")+"']"))});let $selected_peer_list=document.getElementById("selected_peer_list");let changeObserver=new MutationObserver(function(){if($selected_peer_list.hasChildNodes()){$("#confirm_delete_bulk_peers").removeAttr("disabled")}else{$("#confirm_delete_bulk_peers").attr("disabled","disabled")}});changeObserver.observe($selected_peer_list,{attributes:true,childList:true,characterData:true});let confirm_delete_bulk_peers_interval;$("#confirm_delete_bulk_peers").on("click",function(){let btn=$(this);if(confirm_delete_bulk_peers_interval!==undefined){clearInterval(confirm_delete_bulk_peers_interval);confirm_delete_bulk_peers_interval=undefined;btn.html("Delete")}else{let timer=5;btn.html(`Deleting in ${timer} secs... Click to cancel`);confirm_delete_bulk_peers_interval=setInterval(function(){timer-=1;btn.html(`Deleting in ${timer} secs... Click to cancel`);if(timer===0){btn.html(`Deleting...`);btn.attr("disabled","disabled");let ips=[];$selected_peer_list.childNodes.forEach(ele=>ips.push(ele.dataset.id));window.configurations.deletePeers(btn.data("conf"),ips);clearInterval(confirm_delete_bulk_peers_interval);confirm_delete_bulk_peers_interval=undefined}},1e3)}});$("#select_all_delete_bulk_peers").on("click",function(){$(".delete-bulk-peer-item").each(function(){if(!$(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal",function(){$(".delete-bulk-peer-item").each(function(){if($(this).hasClass("active")){window.configurations.toggleDeleteByBulkIP($(this))}})});$body.on("click",".btn-download-peer",function(e){e.preventDefault();let link=$(this).attr("href");$.ajax({url:link,method:"GET",success:function(res){window.configurations.downloadOneConfig(res)}})});$("#download_all_peers").on("click",function(){$.ajax({url:$(this).data("url"),method:"GET",success:function(res){if(res.peers.length>0){window.wireguard.generateZipFiles(res);window.configurations.showToast("Peers' zip file download successful!")}else{window.configurations.showToast("Oops! There are no peer can be download.")}}})}); \ No newline at end of file +!function () { let e, t = 0, a = $(".progress-bar"), i = { keyboard: !1, backdrop: "static" }, o = new bootstrap.Modal(document.getElementById("add_modal"), i), n = new bootstrap.Modal(document.getElementById("delete_bulk_modal"), i), l = new bootstrap.Modal(document.getElementById("available_ip_modal"), i), s = new bootstrap.Modal(document.getElementById("qrcode_modal"), i), r = new bootstrap.Modal(document.getElementById("setting_modal"), i), d = new bootstrap.Modal(document.getElementById("delete_modal"), i); function c() { e = setInterval((function () { f($("#search_peer_textbox").val()) }), t) } function u() { clearInterval(e) } function p() { a.css("width", "0%").css("opacity", "100").css("background", "rgb(255,69,69)").css("background", "linear-gradient(145deg, rgba(255,69,69,1) 0%, rgba(0,115,186,1) 100%)").css("width", "25%"), setTimeout((function () { _() }), 300) } function _() { a.css("transition", "3s ease-in-out").css("width", "75%") } function m() { a.css("transition", "0.3s ease-in-out").css("width", "100%"), setTimeout((function () { a.css("opacity", "0") }), 250) } function g(e, t) { let a = 10 ** t; return Math.round(e * a) / a } $("[data-toggle='tooltip']").tooltip(), $("[data-toggle='popover']").popover(); let v = new Date, h = 0, b = 0; function f(e) { p(), v = new Date, $.ajax({ method: "GET", url: `/get_config/${conf_name}?search=${encodeURIComponent(e)}`, headers: { "Content-Type": "application/json" } }).done((function (e) { document.querySelectorAll(".no-response").forEach((e => e.classList.remove("show"))), document.querySelector("#right_body").classList.remove("no-responding"), document.querySelector(".navbar").classList.remove("no-responding"), setTimeout((function () { document.querySelectorAll(".no-response").forEach((e => e.classList.remove("active"))) }), 1010), peers = e.peer_data, function (e) { if ("" === e.listen_port && "stopped" === e.status) { let e = document.createElement("div"); e.classList.add("alert"), e.classList.add("alert-warning"), e.setAttribute("role", "alert"), e.innerHTML = "Peer QR Code and configuration file download required a specified Listen Port.", document.querySelector("#config_info_alert").appendChild(e) } if ("N/A" === e.conf_address) { let e = document.createElement("div"); e.classList.add("alert"), e.classList.add("alert-warning"), e.setAttribute("role", "alert"), e.innerHTML = "Configuration Address need to be specified to have peers connect to it.", document.querySelector("#config_info_alert").appendChild(e) } }(e), function (e) { let t = document.getElementById("conf_status_btn"); "checked" === e.checked ? t.innerHTML = ` ON` : t.innerHTML = ` OFF`, t.classList.remove("info_loading"), document.querySelectorAll("#sort_by_dropdown option").forEach((e => e.removeAttribute("selected"))), document.querySelector(`#sort_by_dropdown option[value="${e.sort_tag}"]`).setAttribute("selected", "selected"), document.querySelectorAll(".interval-btn-group button").forEach((e => e.classList.remove("active"))), document.querySelector(`button[data-refresh-interval="${e.dashboard_refresh_interval}"]`).classList.add("active"), document.querySelectorAll(".display-btn-group button").forEach((e => e.classList.remove("active"))), document.querySelector(`button[data-display-mode="${e.peer_display_mode}"]`).classList.add("active"), document.querySelector("#conf_status").innerHTML = `${e.status}`, document.querySelector("#conf_connected_peers").innerHTML = e.running_peer, document.querySelector("#conf_total_data_usage").innerHTML = `${e.total_data_usage[0]} GB`, document.querySelector("#conf_total_data_received").innerHTML = `${e.total_data_usage[2]} GB`, document.querySelector("#conf_total_data_sent").innerHTML = `${e.total_data_usage[1]} GB`, document.querySelector("#conf_public_key").innerHTML = e.public_key, document.querySelector("#conf_listen_port").innerHTML = "" === e.listen_port ? "N/A" : e.listen_port, document.querySelector("#conf_address").innerHTML = e.conf_address, document.querySelectorAll(".info h6").forEach((e => e.classList.remove("info_loading"))) }(e), function (e) { let a = ""; if (0 === e.peer_data.length) document.querySelector(".peer_list").innerHTML = '

Oops! No peers found ‘︿’

'; else { let i = "list" === e.peer_display_mode ? "col-12" : "col-sm-6 col-lg-4"; e.peer_data.forEach((function (t) { let o = 0, n = 0; o += t.cumu_receive, n += t.cumu_sent; let l = '
', s = '
' + ("" === t.name ? "Untitled" : t.name) + '
', r = '

' + g(t.total_receive + o, 4) + ' GB

' + g(t.total_sent + n, 4) + " GB

", d = '
PEERCLICK TO COPY
' + t.id + "
", c = '
ALLOWED IP
' + t.allowed_ips + "
", u = '
LATEST HANDSHAKE
' + t.latest_handshake + "
", p = '
END POINT
' + t.endpoint + "
", _ = '

'; "" !== t.private_key && (_ += ''), _ += "
"; let m = '
' + s + l + r + d + c + u + l + p + l + _ + "
"; a += m })), document.querySelector(".peer_list").innerHTML = a, e.dashboard_refresh_interval !== t && (t = e.dashboard_refresh_interval, u(), c()) } }(e), $(".dot.dot-running").attr("title", "Peer Connected").tooltip(), $(".dot.dot-stopped").attr("title", "Peer Disconnected").tooltip(), $("i[data-toggle='tooltip']").tooltip(), m(); let a = new Date - v; h += a, b += 1, console.log(`Average ${h / b}ms`), $("#peer_loading_time").html(`Peer Loading Time: ${a}ms`) })).fail((function () { document.querySelectorAll(".no-response").forEach((e => e.classList.add("active"))), setTimeout((function () { document.querySelectorAll(".no-response").forEach((e => e.classList.add("show"))), document.querySelector("#right_body").classList.add("no-responding"), document.querySelector(".navbar").classList.add("no-responding") }), 10) })) } function w(e) { $("#alertToast").toast("show"), $("#alertToast .toast-body").html(e) } window.configurations = { addModal: () => o, deleteBulkModal: () => n, deleteModal: () => d, ipModal: () => l, qrcodeModal: () => s, settingModal: () => r, loadPeers: e => { f(e) }, addPeersByBulk: () => { !function () { let e = $("#new_add_amount"); $add_peer.setAttribute("disabled", "disabled"), $add_peer.innerHTML = `Adding ${e.val()} peers...`; let t = $("#new_add_DNS"); t.val(window.configurations.cleanIp(t.val())); let a = $("#new_add_endpoint_allowed_ip"); a.val(window.configurations.cleanIp(a.val())); let i = $("#new_add_MTU"), o = $("#new_add_keep_alive"), n = $("#enable_preshare_key"), l = [t, a, i, o]; if (e.val() > 0 && !e.hasClass("is-invalid")) if ("" !== t.val() && "" !== a.val()) { let s = $add_peer.getAttribute("conf_id"), r = []; for (let t = 0; t < e.val(); t++)r.push(window.wireguard.generateKeypair()); $.ajax({ method: "POST", url: "/add_peer_bulk/" + s, headers: { "Content-Type": "application/json" }, data: JSON.stringify({ DNS: t.val(), endpoint_allowed_ips: a.val(), MTU: i.val(), keep_alive: o.val(), enable_preshared_key: n.prop("checked"), keys: r, amount: e.val() }), success: function (t) { "true" !== t ? ($("#add_peer_alert").html(t).removeClass("d-none"), l.forEach((e => e.removeAttr("disabled"))), $add_peer.removeAttribute("disabled"), $add_peer.innerHTML = "Save") : (window.configurations.loadPeers(""), l.forEach((e => e.removeAttr("disabled"))), $("#add_peer_form").trigger("reset"), $add_peer.removeAttribute("disabled"), $add_peer.innerHTML = "Save", window.configurations.showToast(e.val() + " peers added successful!"), window.configurations.addModal().toggle()) } }) } else $("#add_peer_alert").html("Please fill in all required box.").removeClass("d-none"), $add_peer.removeAttribute("disabled"), $add_peer.innerHTML = "Add"; else $add_peer.removeAttribute("disabled"), $add_peer.innerHTML = "Add" }() }, deletePeers: (e, t) => { !function (e, t) { $.ajax({ method: "POST", url: "/remove_peer/" + e, headers: { "Content-Type": "application/json" }, data: JSON.stringify({ action: "delete", peer_ids: t }), success: function (e) { if ("true" !== e) { if (window.configurations.deleteModal()._isShown && ($("#remove_peer_alert").html(e + $("#add_peer_alert").html()).removeClass("d-none"), $("#delete_peer").removeAttr("disabled").html("Delete")), window.configurations.deleteBulkModal()._isShown) { let t = $("#bulk_remove_peer_alert"); t.html(e + t.html()).removeClass("d-none"), $("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete") } } else window.configurations.deleteModal()._isShown && window.configurations.deleteModal().toggle(), window.configurations.deleteBulkModal()._isShown && ($("#confirm_delete_bulk_peers").removeAttr("disabled").html("Delete"), $("#selected_peer_list").html(""), $(".delete-bulk-peer-item.active").removeClass("active"), window.configurations.deleteBulkModal().toggle()), window.configurations.loadPeers($("#search_peer_textbox").val()), $("#alertToast").toast("show"), $("#alertToast .toast-body").html("Peer deleted!"), $("#delete_peer").removeAttr("disabled").html("Delete") } }) }(e, t) }, getAvailableIps: () => { $.ajax({ url: `/available_ips/${$add_peer.getAttribute("conf_id")}`, method: "GET" }).done((function (e) { available_ips = e; let t = document.querySelector("#available_ip_modal .modal-body .list-group"); t.innerHTML = "", document.querySelector("#allowed_ips").value = available_ips[0], available_ips.forEach((e => t.innerHTML += `${e}`)) })) }, generateKeyPair: () => { !function () { let e = window.wireguard.generateKeypair(); document.querySelector("#private_key").value = e.privateKey, document.querySelector("#public_key").value = e.publicKey, document.querySelector("#add_peer_alert").classList.add("d-none"), document.querySelector("#re_generate_key i").classList.remove("rotating"), document.querySelector("#enable_preshare_key").value = e.presharedKey }() }, showToast: e => { w(e) }, updateRefreshInterval: (e, a) => { !function (e, a) { "true" === e ? (t = a, u(), c(), w("Refresh Interval set to " + Math.round(a / 1e3) + " seconds")) : ($(".interval-btn-group button").removeClass("active"), $('.interval-btn-group button[data-refresh-interval="' + t + '"]').addClass("active"), w("Refresh Interval set unsuccessful")) }(e, a) }, copyToClipboard: e => { !function (e) { let t = $(""); $body.append(t), t.val($(e).text()).trigger("select"), document.execCommand("copy"), t.remove() }(e) }, toggleDeleteByBulkIP: e => { !function (e) { let t = $("#selected_peer_list"), a = e.data("id"), i = "" === e.data("name") ? "Untitled Peer" : e.data("name"); e.hasClass("active") ? (e.removeClass("active"), $("#selected_peer_list .badge[data-id='" + a + "']").remove()) : (e.addClass("active"), t.append('' + i + " - " + a + "")) }(e) }, downloadOneConfig: e => { !function (e) { let t = document.createElement("a"); t.download = e.filename; let a = new Blob([e.content], { type: "text/conf" }); t.href = window.URL.createObjectURL(a), t.click() }(e) }, triggerIp: e => { !function (e) { let t = document.querySelector(`.available-ip-item[data-ip='${e}']`); t && (t.classList.contains("active") ? (t.classList.remove("active"), document.querySelector(`#selected_ip_list .badge[data-ip='${e}']`).remove()) : (t.classList.add("active"), document.querySelector("#selected_ip_list").innerHTML += `${e}`)) }(e) }, cleanIp: e => function (e) { let t = e.split(","); for (let e = 0; e < t.length; e++)t[e] = t[e].trim(" "); return t.filter(Boolean).join(",") }(e), startProgressBar: () => { p() }, stillLoadingProgressBar: () => { _() }, endProgressBar: () => { m() } } }(); let typingTimer, $body = $("body"), available_ips = [], $add_peer = document.getElementById("save_peer"); document.querySelector(".add_btn").addEventListener("click", (() => { window.configurations.addModal().toggle() })), document.querySelector(".info").addEventListener("click", (e => { let t = document.querySelector(".switch"); t.contains(e.target) && (t.style.display = "none", document.querySelector("div[role=status]").style.display = "inline-block", location.replace(`/switch/${t.getAttribute("id")}`)) })), document.querySelector("#private_key").addEventListener("change", (e => { let t = document.querySelector("#public_key"); 44 === e.target.value.length ? (t.value = window.wireguard.generatePublicKey(e.target.value), t.setAttribute("disabled", "disabled")) : (t.attributes.removeNamedItem("disabled"), t.value = "") })), $("#add_modal").on("show.bs.modal", (function () { window.configurations.generateKeyPair(), window.configurations.getAvailableIps() })).on("hide.bs.modal", (function () { $("#allowed_ips_indicator").html("") })), $("#re_generate_key").on("click", (function () { $("#public_key").attr("disabled", "disabled"), $("#re_generate_key i").addClass("rotating"), window.configurations.generateKeyPair() })), $("#allowed_ips").on("keyup", (function () { let e = window.configurations.cleanIp($(this).val()); e = e.split(","), available_ips.includes(e[e.length - 1]) ? $("#allowed_ips_indicator").removeClass().addClass("text-success").html('') : $("#allowed_ips_indicator").removeClass().addClass("text-warning").html('') })), $("#peer_name_textbox").on("keyup", (function () { $(".peer_name").html($(this).val()) })), $add_peer.addEventListener("click", (function () { if ($("#bulk_add").prop("checked")) $("#new_add_amount").hasClass("is-invalid") || window.configurations.addPeersByBulk(); else { let e = $("#public_key"), t = $("#private_key"), a = $("#allowed_ips"); a.val(window.configurations.cleanIp(a.val())); let i = $("#new_add_DNS"); i.val(window.configurations.cleanIp(i.val())); let o = $("#new_add_endpoint_allowed_ip"); o.val(window.configurations.cleanIp(o.val())); let n = $("#new_add_name"), l = $("#new_add_MTU"), s = $("#new_add_keep_alive"), r = $("#enable_preshare_key"); if ($add_peer.setAttribute("disabled", "disabled"), $add_peer.innerHTML = "Adding...", "" !== a.val() && "" !== e.val() && "" !== i.val() && "" !== o.val()) { let d = $add_peer.getAttribute("conf_id"), c = [t, a, n, i, o, l, s]; c.forEach((e => e.attr("disabled", "disabled"))), $.ajax({ method: "POST", url: "/add_peer/" + d, headers: { "Content-Type": "application/json" }, data: JSON.stringify({ private_key: t.val(), public_key: e.val(), allowed_ips: a.val(), name: n.val(), DNS: i.val(), endpoint_allowed_ips: o.val(), MTU: l.val(), keep_alive: s.val(), enable_preshared_key: r.prop("checked"), preshared_key: r.val() }), success: function (e) { "true" !== e ? ($("#add_peer_alert").html(e).removeClass("d-none"), c.forEach((e => e.removeAttr("disabled"))), $add_peer.removeAttribute("disabled"), $add_peer.innerHTML = "Save") : (window.configurations.loadPeers(""), c.forEach((e => e.removeAttr("disabled"))), $("#add_peer_form").trigger("reset"), $add_peer.removeAttribute("disabled"), $add_peer.innerHTML = "Save", window.configurations.showToast("Add peer successful!"), window.configurations.addModal().toggle()) } }) } else $("#add_peer_alert").html("Please fill in all required box.").removeClass("d-none"), $add_peer.removeAttribute("disabled"), $add_peer.innerHTML = "Add" } })), $("#new_add_amount").on("keyup", (function () { let e = $("#bulk_amount_validation"); $(this).val().length > 0 ? isNaN($(this).val()) ? ($(this).removeClass("is-valid").addClass("is-invalid"), e.html("Please enter a valid integer")) : $(this).val() > available_ips.length ? ($(this).removeClass("is-valid").addClass("is-invalid"), e.html(`Cannot create more than ${available_ips.length} peers.`)) : $(this).val() < 1 ? ($(this).removeClass("is-valid").addClass("is-invalid"), e.html("Please enter at least 1 or more.")) : $(this).removeClass("is-invalid").addClass("is-valid") : $(this).removeClass("is-invalid").removeClass("is-valid") })), $("#bulk_add").on("change", (function () { let e = $(".non-bulk").find("input"), t = $("#new_add_amount"); if (!0 === $(this).prop("checked")) { for (let t = 0; t < e.length; t++)$(e[t]).attr("disabled", "disabled"); t.removeAttr("disabled") } else { for (let t = 0; t < e.length; t++)"public_key" !== $(e[t]).attr("id") && $(e[t]).removeAttr("disabled"); t.attr("disabled", "disabled") } })), $("#available_ip_modal").on("show.bs.modal", (() => { document.querySelector("#add_modal").classList.add("ip_modal_open") })).on("hidden.bs.modal", (() => { document.querySelector("#add_modal").classList.remove("ip_modal_open"); let e = [], t = document.querySelector("#selected_ip_list"); for (let a = 0; a < t.childElementCount; a++)e.push(t.children[a].dataset.ip); e.forEach((e => window.configurations.triggerIp(e))) })), $body.on("click", ".available-ip-badge", (function () { $(".available-ip-item[data-ip='" + $(this).data("ip") + "']").removeClass("active"), $(this).remove() })), $body.on("click", ".available-ip-item", (function () { window.configurations.triggerIp($(this).data("ip")) })), $("#search_available_ip").on("click", (function () { window.configurations.ipModal().toggle(); let e = document.querySelector("#allowed_ips"); if (e.value.length > 0) { let t = e.value.split(","); for (let e = 0; e < t.length; e++)t[e] = t[e].trim(), window.configurations.triggerIp(t[e]) } })).tooltip(), $("#confirm_ip").on("click", (() => { window.configurations.ipModal().toggle(); let e = []; $("#selected_ip_list").children().each((function () { e.push($(this).data("ip")) })), $("#allowed_ips").val(e.join(", ")), e.forEach((e => window.configurations.triggerIp(e))) })), $body.on("click", ".btn-qrcode-peer", (function () { let e = $(this).data("imgsrc"); $.ajax({ url: e, method: "GET" }).done((function (e) { $("#qrcode_img").attr("src", e), window.configurations.qrcodeModal().toggle() })) })), $body.on("click", ".btn-delete-peer", (function () { let e = $(this).attr("id"); $("#delete_peer").attr("peer_id", e), window.configurations.deleteModal().toggle() })), $("#delete_peer").on("click", (function () { $(this).attr("disabled", "disabled"), $(this).html("Deleting..."); let e = $(this).attr("peer_id"), t = $(this).attr("conf_id"), a = [e]; window.configurations.deletePeers(t, a) })), $body.on("click", ".btn-setting-peer", (function () { window.configurations.startProgressBar(); let e = $(this).attr("id"); $("#save_peer_setting").attr("peer_id", e), $.ajax({ method: "POST", url: "/get_peer_data/" + $("#setting_modal").attr("conf_id"), headers: { "Content-Type": "application/json" }, data: JSON.stringify({ id: e }), success: function (e) { let t = "" === e.name ? "Untitled" : e.name; $("#setting_modal .peer_name").html(t), $("#setting_modal #peer_name_textbox").val(e.name), $("#setting_modal #peer_private_key_textbox").val(e.private_key), $("#setting_modal #peer_DNS_textbox").val(e.DNS), $("#setting_modal #peer_allowed_ip_textbox").val(e.allowed_ips), $("#setting_modal #peer_endpoint_allowed_ips").val(e.endpoint_allowed_ips), $("#setting_modal #peer_mtu").val(e.mtu), $("#setting_modal #peer_keep_alive").val(e.keepalive), $("#setting_modal #peer_preshared_key_textbox").val(e.preshared_key), window.configurations.settingModal().toggle(), window.configurations.endProgressBar() } }) })), $("#setting_modal").on("hidden.bs.modal", (function () { $("#setting_peer_alert").addClass("d-none") })), $("#peer_private_key_textbox").on("change", (function () { let e = $("#save_peer_setting"); $(this).val().length > 0 && $.ajax({ url: "/check_key_match/" + e.attr("conf_id"), method: "POST", headers: { "Content-Type": "application/json" }, data: JSON.stringify({ private_key: $("#peer_private_key_textbox").val(), public_key: e.attr("peer_id") }) }).done((function (e) { "failed" === e.status ? $("#setting_peer_alert").html(e.status).removeClass("d-none") : $("#setting_peer_alert").addClass("d-none") })) })), $("#save_peer_setting").on("click", (function () { $(this).attr("disabled", "disabled"), $(this).html("Saving..."); let e = $("#peer_DNS_textbox"), t = $("#peer_allowed_ip_textbox"), a = $("#peer_endpoint_allowed_ips"), i = $("#peer_name_textbox"), o = $("#peer_private_key_textbox"), n = $("#peer_preshared_key_textbox"), l = $("#peer_mtu"), s = $("#peer_keep_alive"); if ("" !== e.val() && "" !== t.val() && "" !== a.val()) { let r = $(this).attr("peer_id"), d = $(this).attr("conf_id"), c = [i, e, o, n, t, a, l, s]; c.forEach((e => e.attr("disabled", "disabled"))), $.ajax({ method: "POST", url: "/save_peer_setting/" + d, headers: { "Content-Type": "application/json" }, data: JSON.stringify({ id: r, name: i.val(), DNS: e.val(), private_key: o.val(), allowed_ips: t.val(), endpoint_allowed_ips: a.val(), MTU: l.val(), keep_alive: s.val(), preshared_key: n.val() }), success: function (e) { "failed" === e.status ? $("#setting_peer_alert").html(e.msg).removeClass("d-none") : (window.configurations.settingModal().toggle(), window.configurations.loadPeers($("#search_peer_textbox").val()), $("#alertToast").toast("show"), $("#alertToast .toast-body").html("Peer Saved!")), $("#save_peer_setting").removeAttr("disabled").html("Save"), c.forEach((e => e.removeAttr("disabled"))) } }) } else $("#setting_peer_alert").html("Please fill in all required box.").removeClass("d-none"), $("#save_peer_setting").removeAttr("disabled").html("Save") })), $(".peer_private_key_textbox_switch").on("click", (function () { let e = $("#peer_private_key_textbox"), t = "password" === e.attr("type") ? "text" : "password", a = "password" === e.attr("type") ? "bi bi-eye-slash-fill" : "bi bi-eye-fill"; e.attr("type", t), $(".peer_private_key_textbox_switch i").removeClass().addClass(a) })); let doneTypingInterval = 200; $("#search_peer_textbox").on("keyup", (function () { clearTimeout(typingTimer), typingTimer = setTimeout((() => { window.configurations.loadPeers($(this).val()) }), doneTypingInterval) })).on("keydown", (function () { clearTimeout(typingTimer) })), $body.on("change", "#sort_by_dropdown", (function () { $.ajax({ method: "POST", data: JSON.stringify({ sort: $("#sort_by_dropdown option:selected").val() }), headers: { "Content-Type": "application/json" }, url: "/update_dashboard_sort", success: function () { window.configurations.loadPeers($("#search_peer_textbox").val()) } }) })), $body.on("mouseenter", ".key", (function () { $(this).parent().siblings().children()[1].style.opacity = "100" })).on("mouseout", ".key", (function () { let e = $(this).parent().siblings().children()[1]; e.style.opacity = "0", setTimeout((function () { e.innerHTML = "CLICK TO COPY" }), 200) })).on("click", ".key", (function () { let e = $(this).parent().siblings().children()[1]; window.configurations.copyToClipboard($(this)), e.innerHTML = "COPIED!" })), $body.on("click", ".update_interval", (function () { $(".interval-btn-group button").removeClass("active"), $(this).addClass("active"); let e = $(this).data("refresh-interval"); $.ajax({ method: "POST", data: "interval=" + $(this).data("refresh-interval"), url: "/update_dashboard_refresh_interval", success: function (t) { window.configurations.updateRefreshInterval(t, e) } }) })), $body.on("click", ".refresh", (function () { window.configurations.loadPeers($("#search_peer_textbox").val()) })), $body.on("click", ".display_mode", (function () { $(".display-btn-group button").removeClass("active"), $(this).addClass("active"); let e = $(this).data("display-mode"); $.ajax({ method: "GET", url: "/switch_display_mode/" + $(this).data("display-mode"), success: function (t) { "true" === t && ("list" === e ? (Array($(".peer_list").children()).forEach((function (e) { $(e).removeClass().addClass("col-12") })), window.configurations.showToast("Displaying as List")) : (Array($(".peer_list").children()).forEach((function (e) { $(e).removeClass().addClass("col-sm-6 col-lg-4") })), window.configurations.showToast("Displaying as Grids"))) } }) })); let $setting_btn_menu = $(".setting_btn_menu"); $setting_btn_menu.css("top", -1 * ($setting_btn_menu.height() + 54)); let $setting_btn = $(".setting_btn"); $setting_btn.on("click", (function () { $setting_btn_menu.hasClass("show") ? ($setting_btn_menu.removeClass("showing"), setTimeout((function () { $setting_btn_menu.removeClass("show") }), 201)) : ($setting_btn_menu.addClass("show"), setTimeout((function () { $setting_btn_menu.addClass("showing") }), 10)) })), $("html").on("click", (function (e) { document.querySelector(".setting_btn") !== e.target && (document.querySelector(".setting_btn").contains(e.target) || document.querySelector(".setting_btn_menu").contains(e.target) || ($setting_btn_menu.removeClass("showing"), setTimeout((function () { $setting_btn_menu.removeClass("show") }), 310))) })), $("#delete_peers_by_bulk_btn").on("click", (() => { let e = $("#delete_bulk_modal .list-group"); e.html(""), peers.forEach((t => { let a; a = "" === t.name ? "Untitled Peer" : t.name, e.append('' + a + "
" + t.id + "
") })), window.configurations.deleteBulkModal().toggle() })), $body.on("click", ".delete-bulk-peer-item", (function () { window.configurations.toggleDeleteByBulkIP($(this)) })).on("click", ".delete-peer-bulk-badge", (function () { window.configurations.toggleDeleteByBulkIP($(".delete-bulk-peer-item[data-id='" + $(this).data("id") + "']")) })); let confirm_delete_bulk_peers_interval, $selected_peer_list = document.getElementById("selected_peer_list"), changeObserver = new MutationObserver((function () { $selected_peer_list.hasChildNodes() ? $("#confirm_delete_bulk_peers").removeAttr("disabled") : $("#confirm_delete_bulk_peers").attr("disabled", "disabled") })); changeObserver.observe($selected_peer_list, { attributes: !0, childList: !0, characterData: !0 }), $("#confirm_delete_bulk_peers").on("click", (function () { let e = $(this); if (void 0 !== confirm_delete_bulk_peers_interval) clearInterval(confirm_delete_bulk_peers_interval), confirm_delete_bulk_peers_interval = void 0, e.html("Delete"); else { let t = 5; e.html(`Deleting in ${t} secs... Click to cancel`), confirm_delete_bulk_peers_interval = setInterval((function () { if (t -= 1, e.html(`Deleting in ${t} secs... Click to cancel`), 0 === t) { e.html("Deleting..."), e.attr("disabled", "disabled"); let t = []; $selected_peer_list.childNodes.forEach((e => t.push(e.dataset.id))), window.configurations.deletePeers(e.data("conf"), t), clearInterval(confirm_delete_bulk_peers_interval), confirm_delete_bulk_peers_interval = void 0 } }), 1e3) } })), $("#select_all_delete_bulk_peers").on("click", (function () { $(".delete-bulk-peer-item").each((function () { $(this).hasClass("active") || window.configurations.toggleDeleteByBulkIP($(this)) })) })), $(window.configurations.deleteBulkModal()._element).on("hidden.bs.modal", (function () { $(".delete-bulk-peer-item").each((function () { $(this).hasClass("active") && window.configurations.toggleDeleteByBulkIP($(this)) })) })), $body.on("click", ".btn-download-peer", (function (e) { e.preventDefault(); let t = $(this).attr("href"); $.ajax({ url: t, method: "GET", success: function (e) { window.configurations.downloadOneConfig(e) } }) })), $("#download_all_peers").on("click", (function () { $.ajax({ url: $(this).data("url"), method: "GET", success: function (e) { e.peers.length > 0 ? (window.wireguard.generateZipFiles(e), window.configurations.showToast("Peers' zip file download successful!")) : window.configurations.showToast("Oops! There are no peer can be download.") } }) })); \ No newline at end of file diff --git a/src/templates/configuration.html b/src/templates/configuration.html index a7f2ce0..8b01eaa 100644 --- a/src/templates/configuration.html +++ b/src/templates/configuration.html @@ -1,8 +1,9 @@ {% with title=title%} - {% include "header.html"%} +{% include "header.html"%} {% endwith %} +
@@ -10,15 +11,15 @@

Oops!
I can't connect to the server.

- {% include "navbar.html" %} -
- {% include "sidebar.html" %} + {% include "navbar.html" %} +
+ {% include "sidebar.html" %}
-
+
@@ -30,7 +31,8 @@
SWITCH
- @@ -49,7 +51,8 @@
TOTAL RECEIVED -
+
+
TOTAL SENT @@ -59,17 +62,20 @@
PUBLIC KEY - CLICK TO COPY + CLICK TO COPY
LISTEN PORT -
+
-
+
ADDRESS -
+
+
@@ -77,7 +83,7 @@
-
+
- - + +
- +

- -
+ +
@@ -161,17 +191,20 @@
- +
-
- - -
+
+ + +
-
+
@@ -182,98 +215,110 @@
-
-

+

-
+
-
- - +
+ +
-
+
-
+
- -
+ +
- +
- -
- -
-
-
- + +
+ +
+
+
+
@@ -355,57 +403,60 @@
+
-
{% include "tools.html" %} @@ -418,9 +469,10 @@ let load_interval = 0; let conf_name = "{{ conf_data['name'] }}" let peers = []; - $(".sb-"+conf_name+"-url").addClass("active"); - $(function(){ - configurations.loadPeers($('#search_peer_textbox').val()); - }); + $(".sb-" + conf_name + "-url").addClass("active"); + $(function () { + configurations.loadPeers($('#search_peer_textbox').val()); + }); - \ No newline at end of file + + \ No newline at end of file diff --git a/src/templates/settings.html b/src/templates/settings.html index 1f6c267..fe29770 100644 --- a/src/templates/settings.html +++ b/src/templates/settings.html @@ -1,22 +1,23 @@ {% with %} - {% set title="Settings" %} - {% include "header.html" %} +{% set title="Settings" %} +{% include "header.html" %} {% endwith %} + -{% include "navbar.html" %} -
- {% include "sidebar.html" %} -
-
- {% if message != "" %} + {% include "navbar.html" %} +
+ {% include "sidebar.html" %} +
+
+ {% if message != "" %} - {% endif %} -

Settings

-
- {% if required_auth == "true" %} + {% endif %} +

Settings

+
+ {% if required_auth == "true" %}
Peer Default Settings
@@ -26,32 +27,30 @@
+ name="peer_global_DNS" value="{{ peer_global_DNS }}" required>
- + + name="peer_endpoint_allowed_ips" value="{{ peer_endpoint_allowed_ips }}" + required>
- +
+ name="peer_keep_alive" value="{{ peer_keepalive }}">
- + + name="peer_remote_endpoint" value="{{ peer_remote_endpoint }}" required>
@@ -67,8 +66,9 @@
-

Remember to remove / at the end of your path. e.g /etc/wireguard + value="{{ wg_conf_path }}"> +

Remember to remove / at the end of your path. e.g + /etc/wireguard

@@ -83,7 +83,7 @@
+ value="{{ session['username'] }}" required>
@@ -106,61 +106,65 @@
- {% endif %} -
-
Dashboard Configuration
-
-
-
-
-
- - -

0.0.0.0 means it can be access by anyone with your server - IP Address.

+ {% endif %} +
+
Dashboard Configuration
+
+ +
+
+
+ + +

0.0.0.0 means it can be access by anyone with + your server + IP Address.

+
+
+ + +
-
- - -
-
- -
- + +
+ +
-
-
- -
+ +
- -{% include "tools.html" %} + {% include "tools.html" %} {% include "footer.html" %} @@ -201,4 +205,5 @@ }); + \ No newline at end of file diff --git a/src/util.py b/src/util.py index c70d419..b2c3930 100644 --- a/src/util.py +++ b/src/util.py @@ -14,16 +14,21 @@ Helper Functions """ -def adapt_for_rest(x): - x["allowed_ip"] = x.pop("allowed_ips") - x["endpoint_allowed_ip"] = x.pop("endpoint_allowed_ips") - for i in ["latest_handshake", "endpoint", "allowed_ip"]: - if not x[i]: - x[i] = "N/A" - return x +def get_interface_file_path(interface_name: str, base_dir: str) -> str: + return os.path.join(base_dir, f"{interface_name}.conf") -def connect_db(dashboard_configuration_dir): +def adapt_for_rest(peer_dict: dict) -> dict: + """ + Renames necessary entries and replaces falsy values. Returns the modified dict. + """ + for i in ["latest_handshake", "endpoint", "allowed_ips"]: + if not peer_dict[i]: + peer_dict[i] = "(None)" + return peer_dict + + +def connect_db(dashboard_configuration_dir: str): """ Connect to the database @return: sqlite3.Connection @@ -35,7 +40,7 @@ def connect_db(dashboard_configuration_dir): return con -def read_dashboard_conf(dashboard_conf_file_path): +def read_dashboard_conf(dashboard_conf_file_path: str): """ Get dashboard configuration @return: configparser.ConfigParser @@ -45,7 +50,7 @@ def read_dashboard_conf(dashboard_conf_file_path): return r_config -def write_dashboard_conf(config, dashboard_conf_file_path): +def write_dashboard_conf(config: str, dashboard_conf_file_path: str): """ Write to configuration @param config: Input configuration @@ -54,7 +59,9 @@ def write_dashboard_conf(config, dashboard_conf_file_path): config.write(conf_object) -def wg_peer_data_to_db(interface_name, wg_conf_dir, dashboard_conf_file_path): +def wg_peer_data_to_db( + interface_name: str, wg_conf_dir: str, dashboard_conf_file_path: str +): """ Look for new peers from WireGuard @param interface_name: Configuration name @@ -110,9 +117,7 @@ def wg_peer_data_to_db(interface_name, wg_conf_dir, dashboard_conf_file_path): handshakes = wg.get_interface_peers_latest_handshakes(interface_name) transfers = wg.get_interface_peers_net_stats(interface_name) endpoints = wg.get_interface_peers_endpoints(interface_name) - allowed_ips = wg.get_interface_peers_allowed_ips( - interface_and_peer_data, interface_name - ) + allowed_ips = wg.get_interface_peers_allowed_ips(interface_and_peer_data) keys = set() for x in [handshakes, transfers, endpoints, allowed_ips]: keys.update(x.keys()) @@ -127,7 +132,11 @@ def wg_peer_data_to_db(interface_name, wg_conf_dir, dashboard_conf_file_path): def update_db_and_get_peers( - interface_name, search, sort_t, wg_conf_dir, dashboard_conf_file_path + interface_name: str, + search: str, + sort_t: str, + wg_conf_dir: str, + dashboard_conf_file_path: str, ): """ Get all peers. @@ -162,7 +171,7 @@ def update_db_and_get_peers( return result -def get_conf_list(wg_conf_dir): +def get_conf_list(wg_conf_dir: str): """Get all wireguard interfaces with status. @return: Return a list of dicts with interfaces and its statuses @rtype: list @@ -188,7 +197,7 @@ def get_conf_list(wg_conf_dir): return conf -def f_check_key_match(private_key, public_key, interface_name): +def f_check_key_match(private_key: str, public_key: str, interface_name: str): """ Check if private key and public key match @param private_key: Private key @@ -216,7 +225,7 @@ def f_check_key_match(private_key, public_key, interface_name): return {"status": "success"} -def check_repeat_allowed_ips(public_key, ip, interface_name): +def check_repeat_allowed_ips(public_key: str, ip: str, interface_name: str): """ Check if there are repeated IPs @param public_key: Public key of the peer @@ -238,7 +247,7 @@ def check_repeat_allowed_ips(public_key, ip, interface_name): return {"status": "success"} -def f_available_ips(interface_name, wg_conf_dir): +def f_available_ips(interface_name: str, wg_conf_dir: str): """ Get a list of available IPs @param interface_name: Configuration Name @@ -289,7 +298,7 @@ def ensure_subnet(ipv4: str, default_subnet: str = "24") -> str: # Regex Match -def regex_match(regex, text): +def regex_match(regex: str, text: str): pattern = re.compile(regex) return pattern.search(text) is not None diff --git a/src/wg.py b/src/wg.py index 0d7586f..4dbf51b 100644 --- a/src/wg.py +++ b/src/wg.py @@ -7,15 +7,21 @@ import db import os import ifcfg import re +import util def _is_comment_line(line: str) -> bool: - """Returns true if the passed string is a comment""" + """ + Returns true if the passed string is a comment in an INI style file. + """ line = line.strip() return line.startswith("#") or line.startswith(";") -def _parse_peer_or_interface(lines, i, limit): +def _parse_peer_or_interface(lines: list[str], i: int, limit: int) -> dict: + """ + Parses a [Peer] or [Interface] section of an interface config file into a `dict`. + """ data = {} while i < limit: line = lines[i].strip() @@ -30,23 +36,32 @@ def _parse_peer_or_interface(lines, i, limit): def set_peer_options( - interface_name, public_key, allowed_ips, preshared_key_filename=None + interface_name: str, + public_key: str, + allowed_ips: str, + preshared_key_filename: str = None, ): + """ + Sets the given options for the specified `interface_name` and peer (`public_key`) + """ if preshared_key_filename: - status = subprocess.check_output( + subprocess.check_output( f"wg set {interface_name} peer {public_key} allowed-ips {allowed_ips} preshared-key {preshared_key_filename}", shell=True, stderr=subprocess.STDOUT, ) else: - status = subprocess.check_output( + subprocess.check_output( f"wg set {interface_name} peer {public_key} allowed-ips {allowed_ips}", shell=True, stderr=subprocess.STDOUT, ) -def remove_peer_from_interface(interface_name, public_key): +def remove_peer_from_interface(interface_name: str, public_key: str): + """ + Removes the specified peer (`public_key`) from `interface_name` + """ subprocess.check_output( f"wg set {interface_name} peer {public_key} remove", shell=True, @@ -54,7 +69,7 @@ def remove_peer_from_interface(interface_name, public_key): ) -def get_interface_listen_port(interface_name, base_dir): +def get_interface_listen_port(interface_name: str, base_dir: str) -> str: """ Get listen port number. @param interface_name: Name of WG interface @@ -80,7 +95,7 @@ def get_interface_listen_port(interface_name, base_dir): return port -def get_interface_public_key(interface_name, base_dir): +def get_interface_public_key(interface_name: str, base_dir: str) -> str: """ Get public key for configuration. @param interface_name: Name of WG interface @@ -122,7 +137,7 @@ def get_interface_total_net_stats(interface_name): return [total, upload_total, download_total] -def get_interface_status(interface_name): +def get_interface_status(interface_name: str) -> str: """ Check if the configuration is running or not @param interface_name: @@ -206,7 +221,7 @@ def read_interface_config_file(interface_name: str, base_dir: str) -> dict: """ app.logger.debug(f"read_conf_file({interface_name})") - config_file = os.path.join(base_dir, f"{interface_name}.conf") + config_file = util.get_interface_file_path(interface_name, base_dir) with open(config_file, "r", encoding="utf-8") as file_object: file = list(file_object.readlines()) result = {"Interface": {}, "Peers": []} @@ -229,7 +244,10 @@ def read_interface_config_file(interface_name: str, base_dir: str) -> dict: def switch_interface(interface_name: str, base_dir: str): - config_file = os.path.join(base_dir, f"{interface_name}.conf") + """ + Switches `interface_name` around (up if it is down, down if it is up) + """ + config_file = util.get_interface_file_path(interface_name, base_dir) status = get_interface_status(interface_name) if status == "running": check = subprocess.check_output( @@ -242,14 +260,20 @@ def switch_interface(interface_name: str, base_dir: str): def enable_interface(interface_name: str, base_dir: str): - config_file = os.path.join(base_dir, f"{interface_name}.conf") + """ + Brings `interface_name` up (enables it) + """ + config_file = util.get_interface_file_path(interface_name, base_dir) check = subprocess.check_output( "wg-quick up " + config_file, shell=True, stderr=subprocess.STDOUT ) def disable_interface(interface_name: str, base_dir: str): - config_file = os.path.join(base_dir, f"{interface_name}.conf") + """ + Brings `interface_name` down (disables it) + """ + config_file = util.get_interface_file_path(interface_name, base_dir) check = subprocess.check_output( "wg-quick down " + config_file, shell=True, stderr=subprocess.STDOUT ) @@ -297,7 +321,7 @@ def get_interface_peers_latest_handshakes(interface_name) -> dict: return result -def get_interface_peers_net_stats(interface_name) -> dict: +def get_interface_peers_net_stats(interface_name: str) -> dict: """ Get transfer from all peers of a configuration @param interface_name: Configuration name @@ -354,14 +378,17 @@ def get_interface_peers_net_stats(interface_name) -> dict: return result -def quick_save_interface_config(interface_name, base_dir): - config_file = os.path.join(base_dir, f"{interface_name}.conf") +def quick_save_interface_config(interface_name: str, base_dir: str): + """ + Executes `wg-quick save` for `interface_name` + """ + config_file = util.get_interface_file_path(interface_name, base_dir) status = subprocess.check_output( "wg-quick save " + config_file, shell=True, stderr=subprocess.STDOUT ) -def gen_public_key(private_key): +def gen_public_key(private_key: str): """Generate the public key. @param private_key: Private key @@ -390,7 +417,7 @@ def gen_public_key(private_key): } -def get_interface_peers_endpoints(interface_name) -> dict: +def get_interface_peers_endpoints(interface_name: str) -> dict: """ Get endpoint from all peers of a configuration @param interface_name: Configuration name @@ -414,7 +441,7 @@ def get_interface_peers_endpoints(interface_name) -> dict: return result -def get_interface_peers_allowed_ips(conf_peer_data, interface_name) -> dict: +def get_interface_peers_allowed_ips(conf_peer_data: str) -> dict: """ Get allowed ips from all peers of a configuration @param conf_peer_data: Configuration peer data