1
0
mirror of https://github.com/donaldzou/WGDashboard.git synced 2024-11-19 05:50:10 +01:00

general refactoring

This commit is contained in:
Galonza Peter 2021-12-26 13:04:39 +03:00
commit d0ad4e05bf
4 changed files with 106 additions and 145 deletions

1
.gitignore vendored
View File

@ -14,4 +14,3 @@ private_key.txt
public_key.txt public_key.txt
venv/** venv/**
log/** log/**
*~

View File

@ -8,7 +8,6 @@ import hashlib
import ipaddress import ipaddress
import json import json
# Python Built-in Library # Python Built-in Library
import logging
import os import os
import secrets import secrets
import subprocess import subprocess
@ -59,7 +58,8 @@ def get_dashboard_conf():
def set_dashboard_conf(config): def set_dashboard_conf(config):
config.write(open(dashboard_conf, "w")) with open(dashboard_conf, "w") as conf_object:
config.write(conf_object)
# Get all keys from a configuration # Get all keys from a configuration
@ -101,8 +101,8 @@ def get_conf_running_peer_number(config_name):
# Read [Interface] section from configuration file # Read [Interface] section from configuration file
def read_conf_file_interface(config_name): def read_conf_file_interface(config_name):
conf_location = wg_conf_path + "/" + config_name + ".conf" conf_location = wg_conf_path + "/" + config_name + ".conf"
f = open(conf_location, 'r') with open(conf_location, 'r') as file_object:
file = f.read().split("\n") file = file_object.read().split("\n")
data = {} data = {}
for i in range(len(file)): for i in range(len(file)):
if not regex_match("#(.*)", file[i]): if not regex_match("#(.*)", file[i]):
@ -111,7 +111,6 @@ def read_conf_file_interface(config_name):
tmp = re.split(r'\s*=\s*', file[i], 1) tmp = re.split(r'\s*=\s*', file[i], 1)
if len(tmp) == 2: if len(tmp) == 2:
data[tmp[0]] = tmp[1] data[tmp[0]] = tmp[1]
f.close()
return data return data
@ -119,8 +118,8 @@ def read_conf_file_interface(config_name):
def read_conf_file(config_name): def read_conf_file(config_name):
# Read Configuration File Start # Read Configuration File Start
conf_location = wg_conf_path + "/" + config_name + ".conf" conf_location = wg_conf_path + "/" + config_name + ".conf"
f = open(conf_location, 'r') with open(conf_location, 'r') as file_object:
file = f.read().split("\n") file = file_object.read().split("\n")
conf_peer_data = { conf_peer_data = {
"Interface": {}, "Interface": {},
"Peers": [] "Peers": []
@ -150,7 +149,6 @@ def read_conf_file(config_name):
if len(tmp) == 2: if len(tmp) == 2:
conf_peer_data["Peers"][peer][tmp[0]] = tmp[1] conf_peer_data["Peers"][peer][tmp[0]] = tmp[1]
f.close()
# Read Configuration File End # Read Configuration File End
return conf_peer_data return conf_peer_data
@ -404,13 +402,11 @@ def get_conf_list():
# Generate private key # Generate private key
def gen_private_key(): def gen_private_key():
private = open('private_key.txt') with open('private_key.txt') as file_object:
private_key = private.readline().strip() private_key = file_object.readline().strip()
public = open('public_key.txt') with open('public_key.txt') as file_object:
public_key = public.readline().strip() public_key = file_object.readline().strip()
data = {"private_key": private_key, "public_key": public_key} data = {"private_key": private_key, "public_key": public_key}
private.close()
public.close()
os.remove('private_key.txt') os.remove('private_key.txt')
os.remove('public_key.txt') os.remove('public_key.txt')
return data return data
@ -418,12 +414,11 @@ def gen_private_key():
# Generate public key # Generate public key
def gen_public_key(private_key): def gen_public_key(private_key):
pri_key_file = open('private_key.txt', 'w') with open('private_key.txt', 'w') as file_object:
pri_key_file.write(private_key) file_object.write(private_key)
pri_key_file.close()
try: try:
public = open('public_key.txt') with open('public_key.txt') as file_object:
public_key = public.readline().strip() public_key = file_object.readline().strip()
os.remove('private_key.txt') os.remove('private_key.txt')
os.remove('public_key.txt') os.remove('public_key.txt')
return {"status": 'success', "msg": "", "data": public_key} return {"status": 'success', "msg": "", "data": public_key}
@ -593,14 +588,14 @@ def update_acct():
config.read(dashboard_conf) config.read(dashboard_conf)
config.set("Account", "username", request.form['username']) config.set("Account", "username", request.form['username'])
try: try:
config.write(open(dashboard_conf, "w")) with open(dashboard_conf, "w") as config_object:
config.write(config_object)
config.clear()
session['message'] = "Username update successfully!" session['message'] = "Username update successfully!"
session['message_status'] = "success" session['message_status'] = "success"
session['username'] = request.form['username'] session['username'] = request.form['username']
config.clear()
return redirect(url_for("settings")) return redirect(url_for("settings"))
except Exception as exc: except Exception:
logging.error(exc)
session['message'] = "Username update failed." session['message'] = "Username update failed."
session['message_status'] = "danger" session['message_status'] = "danger"
config.clear() config.clear()
@ -635,22 +630,12 @@ def update_peer_default_config():
session['message_status'] = "danger" session['message_status'] = "danger"
return redirect(url_for("settings")) return redirect(url_for("settings"))
# Check MTU Format # Check MTU Format
if len(request.form['peer_mtu']) > 0: if not len(request.form['peer_mtu']) > 0 or not request.form['peer_mtu'].isdigit():
try:
# TODO need to using
mtu = int(request.form['peer_mtu'])
except Exception as exc:
logging.info(exc)
session['message'] = "MTU format is incorrect." session['message'] = "MTU format is incorrect."
session['message_status'] = "danger" session['message_status'] = "danger"
return redirect(url_for("settings")) return redirect(url_for("settings"))
# Check keepalive Format # Check keepalive Format
if len(request.form['peer_keep_alive']) > 0: if not len(request.form['peer_keep_alive']) > 0 or not request.form['peer_keep_alive'].isdigit():
try:
# TODO need to using
mtu = int(request.form['peer_keep_alive'])
except Exception as exc:
logging.error(exc)
session['message'] = "Persistent keepalive format is incorrect." session['message'] = "Persistent keepalive format is incorrect."
session['message_status'] = "danger" session['message_status'] = "danger"
return redirect(url_for("settings")) return redirect(url_for("settings"))
@ -668,13 +653,13 @@ def update_peer_default_config():
config.set("Peers", "peer_global_DNS", dns_addresses) config.set("Peers", "peer_global_DNS", dns_addresses)
try: try:
config.write(open(dashboard_conf, "w")) with open(dashboard_conf, "w") as conf_object:
config.write(conf_object)
session['message'] = "Peer Default Settings update successfully!" session['message'] = "Peer Default Settings update successfully!"
session['message_status'] = "success" session['message_status'] = "success"
config.clear() config.clear()
return redirect(url_for("settings")) return redirect(url_for("settings"))
except Exception as exc: except Exception:
logging.error(exc)
session['message'] = "Peer Default Settings update failed." session['message'] = "Peer Default Settings update failed."
session['message_status'] = "danger" session['message_status'] = "danger"
config.clear() config.clear()
@ -691,13 +676,13 @@ def update_pwd():
request.form['repnewpass'].encode()).hexdigest(): request.form['repnewpass'].encode()).hexdigest():
config.set("Account", "password", hashlib.sha256(request.form['repnewpass'].encode()).hexdigest()) config.set("Account", "password", hashlib.sha256(request.form['repnewpass'].encode()).hexdigest())
try: try:
config.write(open(dashboard_conf, "w")) with open(dashboard_conf, "w") as conf_object:
config.write(conf_object)
session['message'] = "Password update successfully!" session['message'] = "Password update successfully!"
session['message_status'] = "success" session['message_status'] = "success"
config.clear() config.clear()
return redirect(url_for("settings")) return redirect(url_for("settings"))
except Exception as exc: except Exception:
logging.error(exc)
session['message'] = "Password update failed" session['message'] = "Password update failed"
session['message_status'] = "danger" session['message_status'] = "danger"
config.clear() config.clear()
@ -721,7 +706,8 @@ def update_app_ip_port():
config.read(dashboard_conf) config.read(dashboard_conf)
config.set("Server", "app_ip", request.form['app_ip']) config.set("Server", "app_ip", request.form['app_ip'])
config.set("Server", "app_port", request.form['app_port']) config.set("Server", "app_port", request.form['app_port'])
config.write(open(dashboard_conf, "w")) with open(dashboard_conf, "w") as config_object:
config.write(config_object)
config.clear() config.clear()
os.system('bash wgd.sh restart') os.system('bash wgd.sh restart')
@ -732,10 +718,11 @@ def update_wg_conf_path():
config = configparser.ConfigParser(strict=False) config = configparser.ConfigParser(strict=False)
config.read(dashboard_conf) config.read(dashboard_conf)
config.set("Server", "wg_conf_path", request.form['wg_conf_path']) config.set("Server", "wg_conf_path", request.form['wg_conf_path'])
config.write(open(dashboard_conf, "w")) with open(dashboard_conf, "w") as config_object:
config.write(config_object)
config.clear()
session['message'] = "WireGuard Configuration Path Update Successfully!" session['message'] = "WireGuard Configuration Path Update Successfully!"
session['message_status'] = "success" session['message_status'] = "success"
config.clear()
os.system('bash wgd.sh restart') os.system('bash wgd.sh restart')
@ -754,7 +741,8 @@ def update_dashbaord_sort():
config.set("Server", "dashboard_sort", data['sort']) config.set("Server", "dashboard_sort", data['sort'])
else: else:
config.set("Server", "dashboard_sort", 'status') config.set("Server", "dashboard_sort", 'status')
config.write(open(dashboard_conf, "w")) with open(dashboard_conf, "w") as config_object:
config.write(config_object)
config.clear() config.clear()
return "true" return "true"
@ -765,7 +753,8 @@ def update_dashboard_refresh_interval():
config = configparser.ConfigParser(strict=False) config = configparser.ConfigParser(strict=False)
config.read(dashboard_conf) config.read(dashboard_conf)
config.set("Server", "dashboard_refresh_interval", str(request.form['interval'])) config.set("Server", "dashboard_refresh_interval", str(request.form['interval']))
config.write(open(dashboard_conf, "w")) with open(dashboard_conf, "w") as config_object:
config.write(config_object)
config.clear() config.clear()
return "true" return "true"
@ -895,21 +884,11 @@ def add_peer(config_name):
db.close() db.close()
sem.release() sem.release()
return "Endpoint Allowed IPs format is incorrect." return "Endpoint Allowed IPs format is incorrect."
if len(data['MTU']) != 0: if len(data['MTU']) == 0 or not data['MTU'].isdigit():
try:
# TODO need to using
mtu = int(data['MTU'])
except Exception as exc:
logging.error(exc)
db.close() db.close()
sem.release() sem.release()
return "MTU format is not correct." return "MTU format is not correct."
if len(data['keep_alive']) != 0: if len(data['keep_alive']) == 0 or not data['keep_alive'].isdigit():
try:
# TODO need to using
keep_alive = int(data['keep_alive'])
except Exception as exc:
logging.error(exc)
db.close() db.close()
sem.release() sem.release()
return "Persistent Keepalive format is not correct." return "Persistent Keepalive format is not correct."
@ -988,21 +967,11 @@ def save_peer_setting(config_name):
db.close() db.close()
sem.release() sem.release()
return jsonify({"status": "failed", "msg": "DNS format is incorrect."}) return jsonify({"status": "failed", "msg": "DNS format is incorrect."})
if len(data['MTU']) != 0: if len(data['MTU']) == 0 or not data['MTU'].isdigit():
try:
# TODO need to use
mtu = int(data['MTU'])
except Exception as exc:
logging.error(exc)
db.close() db.close()
sem.release() sem.release()
return jsonify({"status": "failed", "msg": "MTU format is not correct."}) return jsonify({"status": "failed", "msg": "MTU format is not correct."})
if len(data['keep_alive']) != 0: if len(data['keep_alive']) == 0 or not data['keep_alive'].isdigit():
try:
# TODO need to using
keep_alive = int(data['keep_alive'])
except Exception as exc:
logging.error(exc)
db.close() db.close()
sem.release() sem.release()
return jsonify({"status": "failed", "msg": "Persistent Keepalive format is not correct."}) return jsonify({"status": "failed", "msg": "Persistent Keepalive format is not correct."})
@ -1187,7 +1156,8 @@ def switch_display_mode(mode):
if mode in ['list', 'grid']: if mode in ['list', 'grid']:
config.read(dashboard_conf) config.read(dashboard_conf)
config.set("Peers", "peer_display_mode", mode) config.set("Peers", "peer_display_mode", mode)
config.write(open(dashboard_conf, "w")) with open(dashboard_conf, "w") as config_object:
config.write(config_object)
return "true" return "true"
else: else:
return "false" return "false"
@ -1239,8 +1209,7 @@ def ping_ip():
if returnjson['package_loss'] == 1.0: if returnjson['package_loss'] == 1.0:
returnjson['package_loss'] = returnjson['package_sent'] returnjson['package_loss'] = returnjson['package_sent']
return jsonify(returnjson) return jsonify(returnjson)
except Exception as exc: except Exception:
logging.error(exc)
return "Error" return "Error"
@ -1258,8 +1227,7 @@ def traceroute_ip():
"max_rtt": hop.max_rtt}) "max_rtt": hop.max_rtt})
last_distance = hop.distance last_distance = hop.distance
return jsonify(returnjson) return jsonify(returnjson)
except Exception as exc: except Exception:
logging.error(exc)
return "Error" return "Error"
@ -1314,7 +1282,8 @@ def init_dashboard():
config['Peers']['peer_MTU'] = "1420" config['Peers']['peer_MTU'] = "1420"
if 'peer_keep_alive' not in config['Peers']: if 'peer_keep_alive' not in config['Peers']:
config['Peers']['peer_keep_alive'] = "21" config['Peers']['peer_keep_alive'] = "21"
config.write(open(dashboard_conf, "w")) with open(dashboard_conf, "w") as config_object:
config.write(config_object)
config.clear() config.clear()

View File

@ -1 +0,0 @@
You can delete this later ;)

View File

@ -32,37 +32,25 @@ _check_and_set_venv(){
} }
install_wgd(){ install_wgd(){
# Check Python3 version printf "| Starting to install WGDashboard |\n"
version_pass=$(python3 -c 'import sys; print("1") if (sys.version_info.major == 3 and sys.version_info.minor >= 8) else print("0");') version_pass=$(python3 -c 'import sys; print("1") if (sys.version_info.major == 3 and sys.version_info.minor >= 7) else print("0");')
if [ $version_pass == "0" ] if [ $version_pass == "0" ]
then printf "| WGDashboard required Python3.8+ |\n" then printf "| WGDashboard required Python 3.7 or above |\n"
printf "%s\n" "$dashes" printf "%s\n" "$dashes"
exit 1 exit 1
fi fi
rm db/hi.txt > /dev/null 2>&1 if [ ! -d "db" ]
then mkdir "db"
fi
if [ ! -d "log" ] if [ ! -d "log" ]
then mkdir "log" then mkdir "log"
fi fi
printf "| Upgrading pip |\n"
python3 -m pip install -U pip
printf "| Installing latest Python dependencies |\n" printf "| Installing latest Python dependencies |\n"
python3 -m pip install -U -r requirements.txt
# set up the local environment
_check_and_set_venv
${VIRTUAL_ENV}/bin/python3 -m pip -U pip
${VIRTUAL_ENV}/bin/python3 -m pip install -U -r requirements.txt
printf "| WGDashboard installed successfully! |\n" printf "| WGDashboard installed successfully! |\n"
printf "| Enter ./wgd start to start the dashboard |\n"
printf "| Preparing the systemctl unit file |\n"
sed -i "s#{{APP_ROOT}}#${APP_ROOT}#" wg-dashboard.service
sed -i "s#{{VIRTUAL_ENV}}#${VIRTUAL_ENV}#" wg-dashboard.service
# cat wg-dashboard.service | sudo SYSTEMD_EDITOR=tee systemctl edit --force --full wg-dashboard.service
systemctl daemon-reload
printf "| Consider 'systemctl enable wg-dashboard' |\n"
printf " and 'systemctl start wg-dashboard'\n"
printf " use '${0} stop' before starting with systemctl\n"
echo
printf "| Now starting Dashboard in background |\n"
start_wgd
} }
@ -76,7 +64,6 @@ check_wgd_status(){
} }
start_wgd () { start_wgd () {
_check_and_set_venv
printf "%s\n" "$dashes" printf "%s\n" "$dashes"
printf "| Starting WGDashboard in the background. |\n" printf "| Starting WGDashboard in the background. |\n"
if [ ! -d "log" ] if [ ! -d "log" ]
@ -94,7 +81,6 @@ stop_wgd() {
start_wgd_debug() { start_wgd_debug() {
printf "%s\n" "$dashes" printf "%s\n" "$dashes"
_check_and_set_venv
printf "| Starting WGDashboard in the foreground. |\n" printf "| Starting WGDashboard in the foreground. |\n"
python3 "$app_name" python3 "$app_name"
printf "%s\n" "$dashes" printf "%s\n" "$dashes"
@ -107,15 +93,21 @@ update_wgd() {
read up read up
if [ "$up" = "Y" ]; then if [ "$up" = "Y" ]; then
printf "| Shutting down WGDashboard... |\n" printf "| Shutting down WGDashboard... |\n"
kill "$(ps aux | grep "[p]ython3 $app_name" | awk '{print $2}')" if check_wgd_status; then
stop_wgd
fi
mv wgd.sh wgd.sh.old
printf "| Downloading %s from GitHub... |\n" "$new_ver" printf "| Downloading %s from GitHub... |\n" "$new_ver"
git stash > /dev/null 2>&1 git stash > /dev/null 2>&1
git pull https://github.com/donaldzou/wireguard-dashboard.git $new_ver --force > /dev/null 2>&1 git pull
# git pull https://github.com/donaldzou/wireguard-dashboard.git $new_ver --force > /dev/null 2>&1
printf "| Upgrading pip |\n"
python3 -m pip install -U pip
printf "| Installing latest Python dependencies |\n" printf "| Installing latest Python dependencies |\n"
_check_and_set_venv python3 -m pip install -U -r requirements.txt
python3 -m pip install -r requirements.txt > /dev/null 2>&1
printf "| Update Successfully! |\n" printf "| Update Successfully! |\n"
start_wgd printf "%s\n" "$dashes"
rm wgd.sh.old
else else
printf "%s\n" "$dashes" printf "%s\n" "$dashes"
printf "| Update Canceled. |\n" printf "| Update Canceled. |\n"
@ -150,7 +142,9 @@ if [ "$#" != 1 ];
elif [ "$1" = "update" ]; then elif [ "$1" = "update" ]; then
update_wgd update_wgd
elif [ "$1" = "install" ]; then elif [ "$1" = "install" ]; then
printf "%s\n" "$dashes"
install_wgd install_wgd
printf "%s\n" "$dashes"
elif [ "$1" = "restart" ]; then elif [ "$1" = "restart" ]; then
if check_wgd_status; then if check_wgd_status; then
printf "%s\n" "$dashes" printf "%s\n" "$dashes"