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

Update dashboard.py

Wrapped all reading and writing to dashboard configuration into functions
This commit is contained in:
Donald Cheng Hong Zou 2021-12-29 15:29:29 -05:00
parent b5b30c8119
commit 8d7c39bac4

View File

@ -57,7 +57,6 @@ def get_dashboard_conf():
""" """
Dashboard Configuration Related Dashboard Configuration Related
""" """
config = configparser.ConfigParser(strict=False) config = configparser.ConfigParser(strict=False)
config.read(DASHBOARD_CONF) config.read(DASHBOARD_CONF)
return config return config
@ -519,8 +518,7 @@ Flask Functions
# Before request # Before request
@app.before_request @app.before_request
def auth_req(): def auth_req():
conf = configparser.ConfigParser(strict=False) conf = get_dashboard_conf()
conf.read(DASHBOARD_CONF)
req = conf.get("Server", "auth_req") req = conf.get("Server", "auth_req")
session['update'] = UPDATE session['update'] = UPDATE
session['dashboard_version'] = DASHBOARD_VERSION session['dashboard_version'] = DASHBOARD_VERSION
@ -535,12 +533,14 @@ def auth_req():
session['message'] = "You need to sign in first!" session['message'] = "You need to sign in first!"
else: else:
session['message'] = "" session['message'] = ""
conf.clear()
return redirect(url_for("signin")) return redirect(url_for("signin"))
else: else:
if request.endpoint in ['signin', 'signout', 'auth', 'settings', 'update_acct', 'update_pwd', if request.endpoint in ['signin', 'signout', 'auth', 'settings', 'update_acct', 'update_pwd',
'update_app_ip_port', 'update_wg_conf_path']: 'update_app_ip_port', 'update_wg_conf_path']:
conf.clear()
return redirect(url_for("index")) return redirect(url_for("index"))
conf.clear()
return None return None
@ -571,8 +571,7 @@ def signout():
# Authentication # Authentication
@app.route('/auth', methods=['POST']) @app.route('/auth', methods=['POST'])
def auth(): def auth():
config = configparser.ConfigParser(strict=False) config = get_dashboard_conf()
config.read(DASHBOARD_CONF)
password = hashlib.sha256(request.form['password'].encode()) password = hashlib.sha256(request.form['password'].encode())
if password.hexdigest() == config["Account"]["password"] \ if password.hexdigest() == config["Account"]["password"] \
and request.form['username'] == config["Account"]["username"]: and request.form['username'] == config["Account"]["username"]:
@ -600,11 +599,9 @@ def settings():
""" """
Setting Page Related Setting Page Related
""" """
message = "" message = ""
status = "" status = ""
config = configparser.ConfigParser(strict=False) config = get_dashboard_conf()
config.read(DASHBOARD_CONF)
if "message" in session and "message_status" in session: if "message" in session and "message_status" in session:
message = session['message'] message = session['message']
status = session['message_status'] status = session['message_status']
@ -628,12 +625,10 @@ def update_acct():
session['message'] = "Username cannot be empty." session['message'] = "Username cannot be empty."
session['message_status'] = "danger" session['message_status'] = "danger"
return redirect(url_for("settings")) return redirect(url_for("settings"))
config = configparser.ConfigParser(strict=False) config = get_dashboard_conf()
config.read(DASHBOARD_CONF)
config.set("Account", "username", request.form['username']) config.set("Account", "username", request.form['username'])
try: try:
with open(DASHBOARD_CONF, "w", encoding='utf-8') as config_object: set_dashboard_conf(config)
config.write(config_object)
config.clear() config.clear()
session['message'] = "Username update successfully!" session['message'] = "Username update successfully!"
session['message_status'] = "success" session['message_status'] = "success"
@ -649,56 +644,57 @@ def update_acct():
# Update peer default settting # Update peer default settting
@app.route('/update_peer_default_config', methods=['POST']) @app.route('/update_peer_default_config', methods=['POST'])
def update_peer_default_config(): def update_peer_default_config():
config = configparser.ConfigParser(strict=False) config = get_dashboard_conf()
config.read(DASHBOARD_CONF)
if len(request.form['peer_endpoint_allowed_ip']) == 0 or \ if len(request.form['peer_endpoint_allowed_ip']) == 0 or \
len(request.form['peer_global_DNS']) == 0 or \ len(request.form['peer_global_DNS']) == 0 or \
len(request.form['peer_remote_endpoint']) == 0: len(request.form['peer_remote_endpoint']) == 0:
session['message'] = "Please fill in all required boxes." session['message'] = "Please fill in all required boxes."
session['message_status'] = "danger" session['message_status'] = "danger"
config.clear()
return redirect(url_for("settings")) return redirect(url_for("settings"))
# Check DNS Format # Check DNS Format
dns_addresses = request.form['peer_global_DNS'] dns_addresses = request.form['peer_global_DNS']
if not check_DNS(dns_addresses): if not check_DNS(dns_addresses):
session['message'] = "Peer DNS Format Incorrect." session['message'] = "Peer DNS Format Incorrect."
session['message_status'] = "danger" session['message_status'] = "danger"
config.clear()
return redirect(url_for("settings")) return redirect(url_for("settings"))
dns_addresses = dns_addresses.replace(" ", "").split(',') dns_addresses = dns_addresses.replace(" ", "").split(',')
dns_addresses = ",".join(dns_addresses) dns_addresses = ",".join(dns_addresses)
# Check Endpoint Allowed IPs # Check Endpoint Allowed IPs
ip = request.form['peer_endpoint_allowed_ip'] ip = request.form['peer_endpoint_allowed_ip']
if not check_Allowed_IPs(ip): if not check_Allowed_IPs(ip):
session['message'] = "Peer Endpoint Allowed IPs Format Incorrect. " \ session['message'] = "Peer Endpoint Allowed IPs Format Incorrect. " \
"Example: 192.168.1.1/32 or 192.168.1.1/32,192.168.1.2/32" "Example: 192.168.1.1/32 or 192.168.1.1/32,192.168.1.2/32"
session['message_status'] = "danger" session['message_status'] = "danger"
config.clear()
return redirect(url_for("settings")) return redirect(url_for("settings"))
# Check MTU Format # Check MTU Format
if not len(request.form['peer_mtu']) > 0 or not request.form['peer_mtu'].isdigit(): if not len(request.form['peer_mtu']) > 0 or not request.form['peer_mtu'].isdigit():
session['message'] = "MTU format is incorrect." session['message'] = "MTU format is incorrect."
session['message_status'] = "danger" session['message_status'] = "danger"
config.clear()
return redirect(url_for("settings")) return redirect(url_for("settings"))
# Check keepalive Format # Check keepalive Format
if not len(request.form['peer_keep_alive']) > 0 or not request.form['peer_keep_alive'].isdigit(): if not len(request.form['peer_keep_alive']) > 0 or not request.form['peer_keep_alive'].isdigit():
session['message'] = "Persistent keepalive format is incorrect." session['message'] = "Persistent keepalive format is incorrect."
session['message_status'] = "danger" session['message_status'] = "danger"
config.clear()
return redirect(url_for("settings")) return redirect(url_for("settings"))
# Check peer remote endpoint # Check peer remote endpoint
if not check_remote_endpoint(request.form['peer_remote_endpoint']): if not check_remote_endpoint(request.form['peer_remote_endpoint']):
session['message'] = "Peer Remote Endpoint format is incorrect. It can only be a valid " \ session['message'] = "Peer Remote Endpoint format is incorrect. It can only be a valid " \
"IP address or valid domain (without http:// or https://). " "IP address or valid domain (without http:// or https://). "
session['message_status'] = "danger" session['message_status'] = "danger"
config.clear()
return redirect(url_for("settings")) return redirect(url_for("settings"))
config.set("Peers", "remote_endpoint", request.form['peer_remote_endpoint']) config.set("Peers", "remote_endpoint", request.form['peer_remote_endpoint'])
config.set("Peers", "peer_keep_alive", request.form['peer_keep_alive']) config.set("Peers", "peer_keep_alive", request.form['peer_keep_alive'])
config.set("Peers", "peer_mtu", request.form['peer_mtu']) config.set("Peers", "peer_mtu", request.form['peer_mtu'])
config.set("Peers", "peer_endpoint_allowed_ip", ','.join(clean_IP_with_range(ip))) config.set("Peers", "peer_endpoint_allowed_ip", ','.join(clean_IP_with_range(ip)))
config.set("Peers", "peer_global_DNS", dns_addresses) config.set("Peers", "peer_global_DNS", dns_addresses)
try: try:
with open(DASHBOARD_CONF, "w", encoding='utf-8') as conf_object: set_dashboard_conf(config)
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()
@ -713,15 +709,13 @@ def update_peer_default_config():
# Update dashboard password # Update dashboard password
@app.route('/update_pwd', methods=['POST']) @app.route('/update_pwd', methods=['POST'])
def update_pwd(): def update_pwd():
config = configparser.ConfigParser(strict=False) config = get_dashboard_conf()
config.read(DASHBOARD_CONF)
if hashlib.sha256(request.form['currentpass'].encode()).hexdigest() == config.get("Account", "password"): if hashlib.sha256(request.form['currentpass'].encode()).hexdigest() == config.get("Account", "password"):
if hashlib.sha256(request.form['newpass'].encode()).hexdigest() == hashlib.sha256( if hashlib.sha256(request.form['newpass'].encode()).hexdigest() == hashlib.sha256(
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:
with open(DASHBOARD_CONF, "w", encoding='utf-8') as conf_object: set_dashboard_conf(config)
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()
@ -746,12 +740,10 @@ def update_pwd():
# Update dashboard IP and port # Update dashboard IP and port
@app.route('/update_app_ip_port', methods=['POST']) @app.route('/update_app_ip_port', methods=['POST'])
def update_app_ip_port(): def update_app_ip_port():
config = configparser.ConfigParser(strict=False) config = get_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'])
with open(DASHBOARD_CONF, "w", encoding='utf-8') as config_object: set_dashboard_conf(config)
config.write(config_object)
config.clear() config.clear()
os.system('bash wgd.sh restart') os.system('bash wgd.sh restart')
@ -759,11 +751,9 @@ def update_app_ip_port():
# Update WireGuard configuration file path # Update WireGuard configuration file path
@app.route('/update_wg_conf_path', methods=['POST']) @app.route('/update_wg_conf_path', methods=['POST'])
def update_wg_conf_path(): def update_wg_conf_path():
config = configparser.ConfigParser(strict=False) config = get_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'])
with open(DASHBOARD_CONF, "w", encoding='utf-8') as config_object: set_dashboard_conf(config)
config.write(config_object)
config.clear() config.clear()
session['message'] = "WireGuard Configuration Path Update Successfully!" session['message'] = "WireGuard Configuration Path Update Successfully!"
session['message_status'] = "success" session['message_status'] = "success"
@ -776,17 +766,14 @@ def update_dashbaord_sort():
""" """
Configuration Page Related Configuration Page Related
""" """
config = get_dashboard_conf()
config = configparser.ConfigParser(strict=False)
config.read(DASHBOARD_CONF)
data = request.get_json() data = request.get_json()
sort_tag = ['name', 'status', 'allowed_ip'] sort_tag = ['name', 'status', 'allowed_ip']
if data['sort'] in sort_tag: if data['sort'] in sort_tag:
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')
with open(DASHBOARD_CONF, "w", encoding='utf-8') as config_object: set_dashboard_conf(config)
config.write(config_object)
config.clear() config.clear()
return "true" return "true"
@ -796,11 +783,9 @@ def update_dashbaord_sort():
def update_dashboard_refresh_interval(): def update_dashboard_refresh_interval():
preset_interval = ["5000", "10000", "30000", "60000"] preset_interval = ["5000", "10000", "30000", "60000"]
if request.form["interval"] in preset_interval: if request.form["interval"] in preset_interval:
config = configparser.ConfigParser(strict=False) config = get_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']))
with open(DASHBOARD_CONF, "w", encoding='utf-8') as config_object: set_dashboard_conf(config)
config.write(config_object)
config.clear() config.clear()
return "true" return "true"
else: else:
@ -810,8 +795,7 @@ def update_dashboard_refresh_interval():
# Configuration Page # Configuration Page
@app.route('/configuration/<config_name>', methods=['GET']) @app.route('/configuration/<config_name>', methods=['GET'])
def configuration(config_name): def configuration(config_name):
config = configparser.ConfigParser(strict=False) config = get_dashboard_conf()
config.read(DASHBOARD_CONF)
conf_data = { conf_data = {
"name": config_name, "name": config_name,
"status": get_conf_status(config_name), "status": get_conf_status(config_name),
@ -821,18 +805,23 @@ def configuration(config_name):
conf_data['checked'] = "nope" conf_data['checked'] = "nope"
else: else:
conf_data['checked'] = "checked" conf_data['checked'] = "checked"
config = configparser.ConfigParser(strict=False)
config.read(DASHBOARD_CONF)
config_list = get_conf_list() config_list = get_conf_list()
if config_name not in [conf['conf'] for conf in config_list]: if config_name not in [conf['conf'] for conf in config_list]:
return render_template('index.html', conf=get_conf_list()) return render_template('index.html', conf=get_conf_list())
refresh_interval = int(config.get("Server", "dashboard_refresh_interval"))
dns_address = config.get("Peers", "peer_global_DNS")
allowed_ip = config.get("Peers", "peer_endpoint_allowed_ip")
peer_mtu = config.get("Peers", "peer_MTU")
peer_keep_alive = config.get("Peers", "peer_keep_alive")
config.clear()
return render_template('configuration.html', conf=get_conf_list(), conf_data=conf_data, return render_template('configuration.html', conf=get_conf_list(), conf_data=conf_data,
dashboard_refresh_interval=int(config.get("Server", "dashboard_refresh_interval")), dashboard_refresh_interval=refresh_interval,
DNS=config.get("Peers", "peer_global_DNS"), DNS=dns_address,
endpoint_allowed_ip=config.get("Peers", "peer_endpoint_allowed_ip"), endpoint_allowed_ip=allowed_ip,
title=config_name, title=config_name,
mtu=config.get("Peers", "peer_MTU"), mtu=peer_mtu,
keep_alive=config.get("Peers", "peer_keep_alive")) keep_alive=peer_keep_alive)
# Get configuration details # Get configuration details
@ -843,8 +832,7 @@ def get_conf(config_name):
if len(search) == 0: if len(search) == 0:
search = "" search = ""
search = urllib.parse.unquote(search) search = urllib.parse.unquote(search)
config = configparser.ConfigParser(strict=False) config = get_dashboard_conf()
config.read(DASHBOARD_CONF)
sort = config.get("Server", "dashboard_sort") sort = config.get("Server", "dashboard_sort")
peer_display_mode = config.get("Peers", "peer_display_mode") peer_display_mode = config.get("Peers", "peer_display_mode")
if "Address" not in config_interface: if "Address" not in config_interface:
@ -870,6 +858,7 @@ def get_conf(config_name):
else: else:
conf_data['checked'] = "checked" conf_data['checked'] = "checked"
print(config.get("Peers","remote_endpoint")) print(config.get("Peers","remote_endpoint"))
config.clear()
return jsonify(conf_data) return jsonify(conf_data)
# return render_template('get_conf.html', conf_data=conf_data, wg_ip=config.get("Peers","remote_endpoint"), sort_tag=sort, # return render_template('get_conf.html', conf_data=conf_data, wg_ip=config.get("Peers","remote_endpoint"), sort_tag=sort,
# dashboard_refresh_interval=int(config.get("Server", "dashboard_refresh_interval")), peer_display_mode=peer_display_mode) # dashboard_refresh_interval=int(config.get("Server", "dashboard_refresh_interval")), peer_display_mode=peer_display_mode)
@ -1307,13 +1296,11 @@ def download(config_name):
@app.route('/switch_display_mode/<mode>', methods=['GET']) @app.route('/switch_display_mode/<mode>', methods=['GET'])
def switch_display_mode(mode): def switch_display_mode(mode):
if mode in ['list', 'grid']: if mode in ['list', 'grid']:
config = configparser.ConfigParser(strict=False) config = get_dashboard_conf()
config.read(DASHBOARD_CONF)
config.set("Peers", "peer_display_mode", mode) config.set("Peers", "peer_display_mode", mode)
with open(DASHBOARD_CONF, "w", encoding='utf-8') as config_object: set_dashboard_conf(config)
config.write(config_object) config.clear()
return "true" return "true"
return "false" return "false"
@ -1397,8 +1384,7 @@ def init_dashboard():
# Set Default INI File # Set Default INI File
if not os.path.isfile(DASHBOARD_CONF): if not os.path.isfile(DASHBOARD_CONF):
conf_file = open(DASHBOARD_CONF, "w+") conf_file = open(DASHBOARD_CONF, "w+")
config = configparser.ConfigParser(strict=False) config = get_dashboard_conf()
config.read(DASHBOARD_CONF)
# Defualt dashboard account setting # Defualt dashboard account setting
if "Account" not in config: if "Account" not in config:
config['Account'] = {} config['Account'] = {}
@ -1439,8 +1425,7 @@ 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"
with open(DASHBOARD_CONF, "w", encoding='utf-8') as config_object: set_dashboard_conf(config)
config.write(config_object)
config.clear() config.clear()
@ -1448,9 +1433,7 @@ def check_update():
""" """
Dashboard check update Dashboard check update
""" """
config = get_dashboard_conf()
config = configparser.ConfigParser(strict=False)
config.read(DASHBOARD_CONF)
data = urllib.request.urlopen("https://api.github.com/repos/donaldzou/WGDashboard/releases").read() data = urllib.request.urlopen("https://api.github.com/repos/donaldzou/WGDashboard/releases").read()
output = json.loads(data) output = json.loads(data)
release = [] release = []
@ -1468,8 +1451,7 @@ def check_update():
if __name__ == "__main__": if __name__ == "__main__":
init_dashboard() init_dashboard()
UPDATE = check_update() UPDATE = check_update()
configuration_settings = configparser.ConfigParser(strict=False) configuration_settings = get_dashboard_conf()
configuration_settings.read(DASHBOARD_CONF)
app_ip = configuration_settings.get("Server", "app_ip") app_ip = configuration_settings.get("Server", "app_ip")
app_port = configuration_settings.get("Server", "app_port") app_port = configuration_settings.get("Server", "app_port")
wg_conf_path = configuration_settings.get("Server", "wg_conf_path") wg_conf_path = configuration_settings.get("Server", "wg_conf_path")