Compare commits

..

12 Commits

Author SHA1 Message Date
Donald Zou 3c50e4768a Merge pull request #317 from donaldzou/v4.0-fix3
Fixed recursive use of cursor
2024-08-20 00:02:46 -07:00
Donald Zou 63dc9834be Fixed recursive use of cursor 2024-08-20 00:02:00 -07:00
Donald Zou f042e42633 Adjust version to v4.0.2 2024-08-19 21:30:47 -04:00
Donald Zou 39b80a2e7e Fixed the issue where updating is not working 2024-08-19 19:17:07 -04:00
Donald Zou fb6e948358 Update production UI 2024-08-19 16:55:18 -04:00
Donald Zou 181b0845bf Merge pull request #313 from donaldzou/v4.0-fix2
Fixed #312, #311
2024-08-19 16:50:48 -04:00
Donald Zou b2a82dcfe5 Fixed #312, #311
- Fixed issue in #312: The dashboard will automatically get the actual Dashboard version number.
- Fixed issue in #311: WGDashboard was not treating restricted peers correctly.
2024-08-19 16:50:00 -04:00
Donald Zou cd73aef0c9 Merge pull request #307 from donaldzou/donaldzou-patch-3
Update README.md
2024-08-17 20:34:29 -04:00
Donald Zou ed522ec024 Update README.md 2024-08-17 20:34:20 -04:00
Donald Zou 16998d1e16 Merge pull request #306 from donaldzou/v4.0-fix1
Fixed peer status is not refreshing correctly
2024-08-17 20:25:34 -04:00
Donald Zou 11421d2d32 Try now 2024-08-17 20:19:52 -04:00
Donald Zou 1af708aaea Update 2024-08-17 01:11:48 -04:00
11 changed files with 334 additions and 256 deletions
+1 -1
View File
@@ -502,7 +502,7 @@ Endpoint = 0.0.0.0:51820
2. Update the dashboard
```shell
git pull https://github.com/donaldzou/WGDashboard.git v4.0 --force
git pull https://github.com/donaldzou/WGDashboard.git --force
```
3. Install
+247 -190
View File
@@ -33,7 +33,7 @@ import threading
from flask.json.provider import DefaultJSONProvider
DASHBOARD_VERSION = 'v4.0'
DASHBOARD_VERSION = 'v4.0.2'
CONFIGURATION_PATH = os.getenv('CONFIGURATION_PATH', '.')
DB_PATH = os.path.join(CONFIGURATION_PATH, 'db')
if not os.path.isdir(DB_PATH):
@@ -119,26 +119,30 @@ class DashboardLogger:
self.loggerdb = sqlite3.connect(os.path.join(CONFIGURATION_PATH, 'db', 'wgdashboard_log.db'),
check_same_thread=False)
self.loggerdb.row_factory = sqlite3.Row
self.loggerdbCursor = self.loggerdb.cursor()
self.__createLogDatabase()
self.log(Message="WGDashboard started")
def __createLogDatabase(self):
existingTable = self.loggerdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
existingTable = [t['name'] for t in existingTable]
if "DashboardLog" not in existingTable:
self.loggerdbCursor.execute(
"CREATE TABLE DashboardLog (LogID VARCHAR NOT NULL, LogDate DATETIME DEFAULT (strftime('%Y-%m-%d %H:%M:%S','now', 'localtime')), URL VARCHAR, IP VARCHAR, Status VARCHAR, Message VARCHAR, PRIMARY KEY (LogID))")
self.loggerdb.commit()
with self.loggerdb:
loggerdbCursor = self.loggerdb.cursor()
existingTable = loggerdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
existingTable = [t['name'] for t in existingTable]
if "DashboardLog" not in existingTable:
loggerdbCursor.execute(
"CREATE TABLE DashboardLog (LogID VARCHAR NOT NULL, LogDate DATETIME DEFAULT (strftime('%Y-%m-%d %H:%M:%S','now', 'localtime')), URL VARCHAR, IP VARCHAR, Status VARCHAR, Message VARCHAR, PRIMARY KEY (LogID))")
if self.loggerdb.in_transaction:
self.loggerdb.commit()
def log(self, URL: str = "", IP: str = "", Status: str = "true", Message: str = "") -> bool:
try:
self.loggerdbCursor.execute(
"INSERT INTO DashboardLog (LogID, URL, IP, Status, Message) VALUES (?, ?, ?, ?, ?)", (str(uuid.uuid4()), URL, IP, Status, Message,))
self.loggerdb.commit()
return True
with self.loggerdb:
loggerdbCursor = self.loggerdb.cursor()
loggerdbCursor.execute(
"INSERT INTO DashboardLog (LogID, URL, IP, Status, Message) VALUES (?, ?, ?, ?, ?)", (str(uuid.uuid4()), URL, IP, Status, Message,))
if self.loggerdb.in_transaction:
self.loggerdb.commit()
return True
except Exception as e:
print(e)
print(f"[WGDashboard] Access Log Error: {str(e)}")
return False
class PeerJobLogger:
@@ -147,23 +151,29 @@ class PeerJobLogger:
check_same_thread=False)
self.loggerdb.row_factory = sqlite3.Row
self.logs:list(Log) = []
self.loggerdbCursor = self.loggerdb.cursor()
self.__createLogDatabase()
def __createLogDatabase(self):
existingTable = self.loggerdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
existingTable = [t['name'] for t in existingTable]
with self.loggerdb:
loggerdbCursor = self.loggerdb.cursor()
if "JobLog" not in existingTable:
self.loggerdbCursor.execute("CREATE TABLE JobLog (LogID VARCHAR NOT NULL, JobID NOT NULL, LogDate DATETIME DEFAULT (strftime('%Y-%m-%d %H:%M:%S','now', 'localtime')), Status VARCHAR NOT NULL, Message VARCHAR, PRIMARY KEY (LogID))")
self.loggerdb.commit()
existingTable = loggerdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
existingTable = [t['name'] for t in existingTable]
if "JobLog" not in existingTable:
loggerdbCursor.execute("CREATE TABLE JobLog (LogID VARCHAR NOT NULL, JobID NOT NULL, LogDate DATETIME DEFAULT (strftime('%Y-%m-%d %H:%M:%S','now', 'localtime')), Status VARCHAR NOT NULL, Message VARCHAR, PRIMARY KEY (LogID))")
if self.loggerdb.in_transaction:
self.loggerdb.commit()
def log(self, JobID: str, Status: bool = True, Message: str = "") -> bool:
try:
self.loggerdbCursor.execute(f"INSERT INTO JobLog (LogID, JobID, Status, Message) VALUES (?, ?, ?, ?)",
(str(uuid.uuid4()), JobID, Status, Message,))
self.loggerdb.commit()
with self.loggerdb:
loggerdbCursor = self.loggerdb.cursor()
loggerdbCursor.execute(f"INSERT INTO JobLog (LogID, JobID, Status, Message) VALUES (?, ?, ?, ?)",
(str(uuid.uuid4()), JobID, Status, Message,))
if self.loggerdb.in_transaction:
self.loggerdb.commit()
except Exception as e:
print(e)
print(f"[WGDashboard] Peer Job Log Error: {str(e)}")
return False
return True
@@ -172,11 +182,13 @@ class PeerJobLogger:
try:
allJobs = AllPeerJobs.getAllJobs(configName)
allJobsID = ", ".join([f"'{x.JobID}'" for x in allJobs])
table = self.loggerdb.execute(f"SELECT * FROM JobLog WHERE JobID IN ({allJobsID}) ORDER BY LogDate DESC").fetchall()
self.logs.clear()
for l in table:
logs.append(
Log(l["LogID"], l["JobID"], l["LogDate"], l["Status"], l["Message"]))
with self.loggerdb:
loggerdbCursor = self.loggerdb.cursor()
table = loggerdbCursor.execute(f"SELECT * FROM JobLog WHERE JobID IN ({allJobsID}) ORDER BY LogDate DESC").fetchall()
self.logs.clear()
for l in table:
logs.append(
Log(l["LogID"], l["JobID"], l["LogDate"], l["Status"], l["Message"]))
except Exception as e:
return logs
return logs
@@ -217,41 +229,47 @@ class PeerJobs:
self.jobdb = sqlite3.connect(os.path.join(CONFIGURATION_PATH, 'db', 'wgdashboard_job.db'),
check_same_thread=False)
self.jobdb.row_factory = sqlite3.Row
self.jobdbCursor = self.jobdb.cursor()
self.__createPeerJobsDatabase()
self.__getJobs()
def __getJobs(self):
self.Jobs.clear()
jobs = self.jobdbCursor.execute("SELECT * FROM PeerJobs WHERE ExpireDate IS NULL").fetchall()
for job in jobs:
self.Jobs.append(PeerJob(
job['JobID'], job['Configuration'], job['Peer'], job['Field'], job['Operator'], job['Value'],
job['CreationDate'], job['ExpireDate'], job['Action']))
with self.jobdb:
jobdbCursor = self.jobdb.cursor()
jobs = jobdbCursor.execute("SELECT * FROM PeerJobs WHERE ExpireDate IS NULL").fetchall()
for job in jobs:
self.Jobs.append(PeerJob(
job['JobID'], job['Configuration'], job['Peer'], job['Field'], job['Operator'], job['Value'],
job['CreationDate'], job['ExpireDate'], job['Action']))
def getAllJobs(self, configuration: str = None):
if configuration is not None:
jobs = self.jobdbCursor.execute(
f"SELECT * FROM PeerJobs WHERE Configuration = ?", (configuration, )).fetchall()
j = []
for job in jobs:
j.append(PeerJob(
job['JobID'], job['Configuration'], job['Peer'], job['Field'], job['Operator'], job['Value'],
job['CreationDate'], job['ExpireDate'], job['Action']))
return j
with self.jobdb:
jobdbCursor = self.jobdb.cursor()
jobs = jobdbCursor.execute(
f"SELECT * FROM PeerJobs WHERE Configuration = ?", (configuration, )).fetchall()
j = []
for job in jobs:
j.append(PeerJob(
job['JobID'], job['Configuration'], job['Peer'], job['Field'], job['Operator'], job['Value'],
job['CreationDate'], job['ExpireDate'], job['Action']))
return j
return []
def __createPeerJobsDatabase(self):
existingTable = self.jobdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
existingTable = [t['name'] for t in existingTable]
with self.jobdb:
jobdbCursor = self.jobdb.cursor()
if "PeerJobs" not in existingTable:
self.jobdbCursor.execute('''
CREATE TABLE PeerJobs (JobID VARCHAR NOT NULL, Configuration VARCHAR NOT NULL, Peer VARCHAR NOT NULL,
Field VARCHAR NOT NULL, Operator VARCHAR NOT NULL, Value VARCHAR NOT NULL, CreationDate DATETIME,
ExpireDate DATETIME, Action VARCHAR NOT NULL, PRIMARY KEY (JobID))
''')
self.jobdb.commit()
existingTable = jobdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
existingTable = [t['name'] for t in existingTable]
if "PeerJobs" not in existingTable:
jobdbCursor.execute('''
CREATE TABLE PeerJobs (JobID VARCHAR NOT NULL, Configuration VARCHAR NOT NULL, Peer VARCHAR NOT NULL,
Field VARCHAR NOT NULL, Operator VARCHAR NOT NULL, Value VARCHAR NOT NULL, CreationDate DATETIME,
ExpireDate DATETIME, Action VARCHAR NOT NULL, PRIMARY KEY (JobID))
''')
self.jobdb.commit()
def toJson(self):
return [x.toJson() for x in self.Jobs]
@@ -261,22 +279,25 @@ class PeerJobs:
def saveJob(self, Job: PeerJob) -> tuple[bool, list] | tuple[bool, str]:
try:
if (len(str(Job.CreationDate))) == 0:
self.jobdbCursor.execute('''
INSERT INTO PeerJobs VALUES (?, ?, ?, ?, ?, ?, strftime('%Y-%m-%d %H:%M:%S','now'), NULL, ?)
''', (Job.JobID, Job.Configuration, Job.Peer, Job.Field, Job.Operator, Job.Value, Job.Action,))
JobLogger.log(Job.JobID, Message=f"Job is created if {Job.Field} {Job.Operator} {Job.Value} then {Job.Action}")
with self.jobdb:
jobdbCursor = self.jobdb.cursor()
else:
currentJob = self.jobdbCursor.execute('SELECT * FROM PeerJobs WHERE JobID = ?', (Job.JobID, )).fetchone()
if currentJob is not None:
self.jobdbCursor.execute('''
UPDATE PeerJobs SET Field = ?, Operator = ?, Value = ?, Action = ? WHERE JobID = ?
''', (Job.Field, Job.Operator, Job.Value, Job.Action, Job.JobID))
JobLogger.log(Job.JobID,
Message=f"Job is updated from if {currentJob['Field']} {currentJob['Operator']} {currentJob['value']} then {currentJob['Action']}; to if {Job.Field} {Job.Operator} {Job.Value} then {Job.Action}")
self.jobdb.commit()
self.__getJobs()
if (len(str(Job.CreationDate))) == 0:
jobdbCursor.execute('''
INSERT INTO PeerJobs VALUES (?, ?, ?, ?, ?, ?, strftime('%Y-%m-%d %H:%M:%S','now'), NULL, ?)
''', (Job.JobID, Job.Configuration, Job.Peer, Job.Field, Job.Operator, Job.Value, Job.Action,))
JobLogger.log(Job.JobID, Message=f"Job is created if {Job.Field} {Job.Operator} {Job.Value} then {Job.Action}")
else:
currentJob = jobdbCursor.execute('SELECT * FROM PeerJobs WHERE JobID = ?', (Job.JobID, )).fetchone()
if currentJob is not None:
jobdbCursor.execute('''
UPDATE PeerJobs SET Field = ?, Operator = ?, Value = ?, Action = ? WHERE JobID = ?
''', (Job.Field, Job.Operator, Job.Value, Job.Action, Job.JobID))
JobLogger.log(Job.JobID,
Message=f"Job is updated from if {currentJob['Field']} {currentJob['Operator']} {currentJob['value']} then {currentJob['Action']}; to if {Job.Field} {Job.Operator} {Job.Value} then {Job.Action}")
self.jobdb.commit()
self.__getJobs()
return True, list(
filter(lambda x: x.Configuration == Job.Configuration and x.Peer == Job.Peer and x.JobID == Job.JobID,
@@ -288,10 +309,12 @@ class PeerJobs:
try:
if (len(str(Job.CreationDate))) == 0:
return False, "Job does not exist"
self.jobdbCursor.execute('''
UPDATE PeerJobs SET ExpireDate = strftime('%Y-%m-%d %H:%M:%S','now') WHERE JobID = ?
''', (Job.JobID,))
self.jobdb.commit()
with self.jobdb:
jobdbCursor = self.jobdb.cursor()
jobdbCursor.execute('''
UPDATE PeerJobs SET ExpireDate = strftime('%Y-%m-%d %H:%M:%S','now') WHERE JobID = ?
''', (Job.JobID,))
self.jobdb.commit()
JobLogger.log(Job.JobID, Message=f"Job is removed due to being deleted or finshed.")
self.__getJobs()
return True, list(
@@ -364,10 +387,9 @@ class PeerShareLink:
class PeerShareLinks:
def __init__(self):
self.Links: list[PeerShareLink] = []
self.PeerShareLinkCursor = sqldb.cursor()
existingTables = self.PeerShareLinkCursor.execute("SELECT name FROM sqlite_master WHERE type='table' and name = 'PeerShareLinks'").fetchall()
existingTables = sqlSelect("SELECT name FROM sqlite_master WHERE type='table' and name = 'PeerShareLinks'").fetchall()
if len(existingTables) == 0:
self.PeerShareLinkCursor.execute(
sqlUpdate(
"""
CREATE TABLE PeerShareLinks (
ShareID VARCHAR NOT NULL PRIMARY KEY, Configuration VARCHAR NOT NULL, Peer VARCHAR NOT NULL,
@@ -376,12 +398,12 @@ class PeerShareLinks:
)
"""
)
sqldb.commit()
# sqldb.commit()
self.__getSharedLinks()
# print(self.Links)
def __getSharedLinks(self):
self.Links.clear()
allLinks = self.PeerShareLinkCursor.execute("SELECT * FROM PeerShareLinks WHERE ExpireDate IS NULL OR ExpireDate > datetime('now', 'localtime')").fetchall()
allLinks = sqlSelect("SELECT * FROM PeerShareLinks WHERE ExpireDate IS NULL OR ExpireDate > datetime('now', 'localtime')").fetchall()
for link in allLinks:
self.Links.append(PeerShareLink(*link))
@@ -397,18 +419,17 @@ class PeerShareLinks:
try:
newShareID = str(uuid.uuid4())
if len(self.getLink(Configuration, Peer)) > 0:
self.PeerShareLinkCursor.execute("UPDATE PeerShareLinks SET ExpireDate = datetime('now', 'localtime') WHERE Configuration = ? AND Peer = ?", (Configuration, Peer, ))
self.PeerShareLinkCursor.execute("INSERT INTO PeerShareLinks (ShareID, Configuration, Peer, ExpireDate) VALUES (?, ?, ?, ?)", (newShareID, Configuration, Peer, ExpireDate, ))
sqldb.commit()
sqlUpdate("UPDATE PeerShareLinks SET ExpireDate = datetime('now', 'localtime') WHERE Configuration = ? AND Peer = ?", (Configuration, Peer, ))
sqlUpdate("INSERT INTO PeerShareLinks (ShareID, Configuration, Peer, ExpireDate) VALUES (?, ?, ?, ?)", (newShareID, Configuration, Peer, ExpireDate, ))
# sqldb.commit()
self.__getSharedLinks()
except Exception as e:
return False, str(e)
return True, newShareID
def updateLinkExpireDate(self, ShareID, ExpireDate: datetime = None) -> tuple[bool, str]:
self.PeerShareLinkCursor.execute("UPDATE PeerShareLinks SET ExpireDate = ? WHERE ShareID = ?;", (ExpireDate, ShareID, ))
sqldb.commit()
sqlUpdate("UPDATE PeerShareLinks SET ExpireDate = ? WHERE ShareID = ?;", (ExpireDate, ShareID, ))
# sqldb.commit()
self.__getSharedLinks()
return True, ""
@@ -490,12 +511,13 @@ class WireguardConfiguration:
# Create tables in database
self.__createDatabase()
self.getPeersList()
self.getRestrictedPeersList()
def __createDatabase(self):
existingTables = sqldb.cursor().execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
existingTables = sqlSelect("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
existingTables = [t['name'] for t in existingTables]
if self.Name not in existingTables:
sqldb.cursor().execute(
sqlUpdate(
"""
CREATE TABLE '%s'(
id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL,
@@ -508,10 +530,10 @@ class WireguardConfiguration:
)
""" % self.Name
)
sqldb.commit()
# sqldb.commit()
if f'{self.Name}_restrict_access' not in existingTables:
sqldb.cursor().execute(
sqlUpdate(
"""
CREATE TABLE '%s_restrict_access' (
id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL,
@@ -524,9 +546,9 @@ class WireguardConfiguration:
)
""" % self.Name
)
sqldb.commit()
# sqldb.commit()
if f'{self.Name}_transfer' not in existingTables:
sqldb.cursor().execute(
sqlUpdate(
"""
CREATE TABLE '%s_transfer' (
id VARCHAR NOT NULL, total_receive FLOAT NULL,
@@ -535,9 +557,9 @@ class WireguardConfiguration:
)
""" % self.Name
)
sqldb.commit()
# sqldb.commit()
if f'{self.Name}_deleted' not in existingTables:
sqldb.cursor().execute(
sqlUpdate(
"""
CREATE TABLE '%s_deleted' (
id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL,
@@ -550,7 +572,7 @@ class WireguardConfiguration:
)
""" % self.Name
)
sqldb.commit()
# sqldb.commit()
@@ -563,85 +585,85 @@ class WireguardConfiguration:
def __getRestrictedPeers(self):
self.RestrictedPeers = []
restricted = sqldb.cursor().execute("SELECT * FROM '%s_restrict_access'" % self.Name).fetchall()
restricted = sqlSelect("SELECT * FROM '%s_restrict_access'" % self.Name).fetchall()
for i in restricted:
self.RestrictedPeers.append(Peer(i, self))
def __getPeers(self):
mt = os.path.getmtime(os.path.join(WG_CONF_PATH, f'{self.Name}.conf'))
if self.__configFileModifiedTime is None or self.__configFileModifiedTime != mt:
self.Peers = []
with open(os.path.join(WG_CONF_PATH, f'{self.Name}.conf'), 'r') as configFile:
p = []
pCounter = -1
content = configFile.read().split('\n')
try:
peerStarts = content.index("[Peer]")
content = content[peerStarts:]
for i in content:
if not regex_match("#(.*)", i) and not regex_match(";(.*)", i):
if i == "[Peer]":
pCounter += 1
p.append({})
p[pCounter]["name"] = ""
else:
if len(i) > 0:
split = re.split(r'\s*=\s*', i, 1)
if len(split) == 2:
p[pCounter][split[0]] = split[1]
# if self.__configFileModifiedTime is None or self.__configFileModifiedTime != mt:
self.Peers = []
with open(os.path.join(WG_CONF_PATH, f'{self.Name}.conf'), 'r') as configFile:
p = []
pCounter = -1
content = configFile.read().split('\n')
try:
peerStarts = content.index("[Peer]")
content = content[peerStarts:]
for i in content:
if not regex_match("#(.*)", i) and not regex_match(";(.*)", i):
if i == "[Peer]":
pCounter += 1
p.append({})
p[pCounter]["name"] = ""
else:
if len(i) > 0:
split = re.split(r'\s*=\s*', i, 1)
if len(split) == 2:
p[pCounter][split[0]] = split[1]
if regex_match("#Name# = (.*)", i):
split = re.split(r'\s*=\s*', i, 1)
print(split)
if len(split) == 2:
p[pCounter]["name"] = split[1]
if regex_match("#Name# = (.*)", i):
split = re.split(r'\s*=\s*', i, 1)
print(split)
if len(split) == 2:
p[pCounter]["name"] = split[1]
for i in p:
if "PublicKey" in i.keys():
checkIfExist = sqldb.cursor().execute("SELECT * FROM '%s' WHERE id = ?" % self.Name,
((i['PublicKey']),)).fetchone()
if checkIfExist is None:
newPeer = {
"id": i['PublicKey'],
"private_key": "",
"DNS": DashboardConfig.GetConfig("Peers", "peer_global_DNS")[1],
"endpoint_allowed_ip": DashboardConfig.GetConfig("Peers", "peer_endpoint_allowed_ip")[
1],
"name": i.get("name"),
"total_receive": 0,
"total_sent": 0,
"total_data": 0,
"endpoint": "N/A",
"status": "stopped",
"latest_handshake": "N/A",
"allowed_ip": i.get("AllowedIPs", "N/A"),
"cumu_receive": 0,
"cumu_sent": 0,
"cumu_data": 0,
"traffic": [],
"mtu": DashboardConfig.GetConfig("Peers", "peer_mtu")[1],
"keepalive": DashboardConfig.GetConfig("Peers", "peer_keep_alive")[1],
"remote_endpoint": DashboardConfig.GetConfig("Peers", "remote_endpoint")[1],
"preshared_key": i["PresharedKey"] if "PresharedKey" in i.keys() else ""
}
sqldb.cursor().execute(
"""
INSERT INTO '%s'
VALUES (:id, :private_key, :DNS, :endpoint_allowed_ip, :name, :total_receive, :total_sent,
:total_data, :endpoint, :status, :latest_handshake, :allowed_ip, :cumu_receive, :cumu_sent,
:cumu_data, :mtu, :keepalive, :remote_endpoint, :preshared_key);
""" % self.Name
, newPeer)
sqldb.commit()
self.Peers.append(Peer(newPeer, self))
else:
sqldb.cursor().execute("UPDATE '%s' SET allowed_ip = ? WHERE id = ?" % self.Name,
(i.get("AllowedIPs", "N/A"), i['PublicKey'],))
sqldb.commit()
self.Peers.append(Peer(checkIfExist, self))
except Exception as e:
print(f"[WGDashboard] {self.Name} Error: {str(e)}")
for i in p:
if "PublicKey" in i.keys():
checkIfExist = sqlSelect("SELECT * FROM '%s' WHERE id = ?" % self.Name,
((i['PublicKey']),)).fetchone()
if checkIfExist is None:
newPeer = {
"id": i['PublicKey'],
"private_key": "",
"DNS": DashboardConfig.GetConfig("Peers", "peer_global_DNS")[1],
"endpoint_allowed_ip": DashboardConfig.GetConfig("Peers", "peer_endpoint_allowed_ip")[
1],
"name": i.get("name"),
"total_receive": 0,
"total_sent": 0,
"total_data": 0,
"endpoint": "N/A",
"status": "stopped",
"latest_handshake": "N/A",
"allowed_ip": i.get("AllowedIPs", "N/A"),
"cumu_receive": 0,
"cumu_sent": 0,
"cumu_data": 0,
"traffic": [],
"mtu": DashboardConfig.GetConfig("Peers", "peer_mtu")[1],
"keepalive": DashboardConfig.GetConfig("Peers", "peer_keep_alive")[1],
"remote_endpoint": DashboardConfig.GetConfig("Peers", "remote_endpoint")[1],
"preshared_key": i["PresharedKey"] if "PresharedKey" in i.keys() else ""
}
sqlUpdate(
"""
INSERT INTO '%s'
VALUES (:id, :private_key, :DNS, :endpoint_allowed_ip, :name, :total_receive, :total_sent,
:total_data, :endpoint, :status, :latest_handshake, :allowed_ip, :cumu_receive, :cumu_sent,
:cumu_data, :mtu, :keepalive, :remote_endpoint, :preshared_key);
""" % self.Name
, newPeer)
# sqldb.commit()
self.Peers.append(Peer(newPeer, self))
else:
sqlUpdate("UPDATE '%s' SET allowed_ip = ? WHERE id = ?" % self.Name,
(i.get("AllowedIPs", "N/A"), i['PublicKey'],))
# sqldb.commit()
self.Peers.append(Peer(checkIfExist, self))
except Exception as e:
print(f"[WGDashboard] {self.Name} Error: {str(e)}")
self.__configFileModifiedTime = mt
def addPeers(self, peers: list):
@@ -665,11 +687,11 @@ class WireguardConfiguration:
self.toggleConfiguration()
for i in listOfPublicKeys:
p = sqldb.cursor().execute("SELECT * FROM '%s_restrict_access' WHERE id = ?" % self.Name, (i,)).fetchone()
p = sqlSelect("SELECT * FROM '%s_restrict_access' WHERE id = ?" % self.Name, (i,)).fetchone()
if p is not None:
sqldb.cursor().execute("INSERT INTO '%s' SELECT * FROM %s_restrict_access WHERE id = ?"
sqlUpdate("INSERT INTO '%s' SELECT * FROM %s_restrict_access WHERE id = ?"
% (self.Name, self.Name,), (p['id'],))
sqldb.cursor().execute("DELETE FROM '%s_restrict_access' WHERE id = ?"
sqlUpdate("DELETE FROM '%s_restrict_access' WHERE id = ?"
% self.Name, (p['id'],))
subprocess.check_output(f"wg set {self.Name} peer {p['id']} allowed-ips {p['allowed_ip']}",
shell=True, stderr=subprocess.STDOUT)
@@ -692,11 +714,12 @@ class WireguardConfiguration:
try:
subprocess.check_output(f"wg set {self.Name} peer {pf.id} remove",
shell=True, stderr=subprocess.STDOUT)
sqldb.cursor().execute("INSERT INTO '%s_restrict_access' SELECT * FROM %s WHERE id = ?" %
sqlUpdate("INSERT INTO '%s_restrict_access' SELECT * FROM %s WHERE id = ?" %
(self.Name, self.Name,), (pf.id,))
sqldb.cursor().execute("UPDATE '%s_restrict_access' SET status = 'stopped' WHERE id = ?" %
sqlUpdate("UPDATE '%s_restrict_access' SET status = 'stopped' WHERE id = ?" %
(self.Name,), (pf.id,))
sqldb.cursor().execute("DELETE FROM '%s' WHERE id = ?" % self.Name, (pf.id,))
sqlUpdate("DELETE FROM '%s' WHERE id = ?" % self.Name, (pf.id,))
# sqldb.commit()
numOfRestrictedPeers += 1
except Exception as e:
numOfFailedToRestrictPeers += 1
@@ -723,7 +746,7 @@ class WireguardConfiguration:
try:
subprocess.check_output(f"wg set {self.Name} peer {pf.id} remove",
shell=True, stderr=subprocess.STDOUT)
sqldb.cursor().execute("DELETE FROM '%s' WHERE id = ?" % self.Name, (pf.id,))
sqlUpdate("DELETE FROM '%s' WHERE id = ?" % self.Name, (pf.id,))
numOfDeletedPeers += 1
except Exception as e:
numOfFailedToDeletePeers += 1
@@ -799,7 +822,7 @@ class WireguardConfiguration:
data_usage = [p.split("\t") for p in data_usage]
for i in range(len(data_usage)):
if len(data_usage[i]) == 3:
cur_i = sqldb.cursor().execute(
cur_i = sqlSelect(
"SELECT total_receive, total_sent, cumu_receive, cumu_sent, status FROM '%s' WHERE id= ? "
% self.Name, (data_usage[i][0],)).fetchone()
if cur_i is not None:
@@ -814,7 +837,7 @@ class WireguardConfiguration:
total_sent = cur_total_sent
total_receive = cur_total_receive
else:
sqldb.cursor().execute(
sqlUpdate(
"UPDATE '%s' SET cumu_receive = ?, cumu_sent = ?, cumu_data = ? WHERE id = ?" %
self.Name, (cumulative_receive, cumulative_sent,
cumulative_sent + cumulative_receive,
@@ -824,7 +847,7 @@ class WireguardConfiguration:
total_receive = 0
_, p = self.searchPeer(data_usage[i][0])
if p.total_receive != total_receive or p.total_sent != total_sent:
sqldb.cursor().execute(
sqlUpdate(
"UPDATE '%s' SET total_receive = ?, total_sent = ?, total_data = ? WHERE id = ?"
% self.Name, (total_receive, total_sent,
total_receive + total_sent, data_usage[i][0],))
@@ -845,7 +868,7 @@ class WireguardConfiguration:
for _ in range(int(len(data_usage) / 2)):
sqldb.execute("UPDATE '%s' SET endpoint = ? WHERE id = ?" % self.Name
, (data_usage[count + 1], data_usage[count],))
sqldb.commit()
# sqldb.commit()
count += 2
def toggleConfiguration(self) -> [bool, str]:
@@ -980,7 +1003,7 @@ class Peer:
if f"wg showconf {self.configuration.Name}" not in saveConfig.decode().strip('\n'):
return ResponseObject(False,
"Update peer failed when saving the configuration.")
sqldb.cursor().execute(
sqlUpdate(
'''UPDATE '%s' SET name = ?, private_key = ?, DNS = ?, endpoint_allowed_ip = ?, mtu = ?,
keepalive = ?, preshared_key = ? WHERE id = ?''' % self.configuration.Name,
(name, private_key, dns_addresses, endpoint_allowed_ip, mtu,
@@ -1033,11 +1056,11 @@ PersistentKeepalive = {str(self.keepalive)}
def resetDataUsage(self, type):
try:
if type == "total":
sqldb.cursor().execute("UPDATE '%s' SET total_data = 0, cumu_data = 0, total_receive = 0, cumu_receive = 0, total_sent = 0, cumu_sent = 0 WHERE id = ?" % self.configuration.Name, (self.id, ))
sqlUpdate("UPDATE '%s' SET total_data = 0, cumu_data = 0, total_receive = 0, cumu_receive = 0, total_sent = 0, cumu_sent = 0 WHERE id = ?" % self.configuration.Name, (self.id, ))
elif type == "receive":
sqldb.cursor().execute("UPDATE '%s' SET total_receive = 0, cumu_receive = 0 WHERE id = ?" % self.configuration.Name, (self.id, ))
sqlUpdate("UPDATE '%s' SET total_receive = 0, cumu_receive = 0 WHERE id = ?" % self.configuration.Name, (self.id, ))
elif type == "sent":
sqldb.cursor().execute("UPDATE '%s' SET total_sent = 0, cumu_sent = 0 WHERE id = ?" % self.configuration.Name, (self.id, ))
sqlUpdate("UPDATE '%s' SET total_sent = 0, cumu_sent = 0 WHERE id = ?" % self.configuration.Name, (self.id, ))
else:
return False
except Exception as e:
@@ -1115,15 +1138,17 @@ class DashboardConfig:
self.__createAPIKeyTable()
self.DashboardAPIKeys = self.__getAPIKeys()
self.APIAccessed = False
self.SetConfig("Server", "version", DASHBOARD_VERSION)
def __createAPIKeyTable(self):
existingTable = sqldb.cursor().execute("SELECT name FROM sqlite_master WHERE type='table' AND name = 'DashboardAPIKeys'").fetchall()
existingTable = sqlSelect("SELECT name FROM sqlite_master WHERE type='table' AND name = 'DashboardAPIKeys'").fetchall()
if len(existingTable) == 0:
sqldb.cursor().execute("CREATE TABLE DashboardAPIKeys (Key VARCHAR NOT NULL PRIMARY KEY, CreatedAt DATETIME NOT NULL DEFAULT (datetime('now', 'localtime')), ExpiredAt VARCHAR)")
sqldb.commit()
sqlUpdate("CREATE TABLE DashboardAPIKeys (Key VARCHAR NOT NULL PRIMARY KEY, CreatedAt DATETIME NOT NULL DEFAULT (datetime('now', 'localtime')), ExpiredAt VARCHAR)")
# sqldb.commit()
def __getAPIKeys(self) -> list[DashboardAPIKey]:
keys = sqldb.cursor().execute("SELECT * FROM DashboardAPIKeys WHERE ExpiredAt IS NULL OR ExpiredAt > datetime('now', 'localtime') ORDER BY CreatedAt DESC").fetchall()
keys = sqlSelect("SELECT * FROM DashboardAPIKeys WHERE ExpiredAt IS NULL OR ExpiredAt > datetime('now', 'localtime') ORDER BY CreatedAt DESC").fetchall()
fKeys = []
for k in keys:
fKeys.append(DashboardAPIKey(*k))
@@ -1131,13 +1156,13 @@ class DashboardConfig:
def createAPIKeys(self, ExpiredAt = None):
newKey = secrets.token_urlsafe(32)
sqldb.cursor().execute('INSERT INTO DashboardAPIKeys (Key, ExpiredAt) VALUES (?, ?)', (newKey, ExpiredAt,))
sqldb.commit()
sqlUpdate('INSERT INTO DashboardAPIKeys (Key, ExpiredAt) VALUES (?, ?)', (newKey, ExpiredAt,))
# sqldb.commit()
self.DashboardAPIKeys = self.__getAPIKeys()
def deleteAPIKey(self, key):
sqldb.cursor().execute("UPDATE DashboardAPIKeys SET ExpiredAt = datetime('now', 'localtime') WHERE Key = ?", (key, ))
sqldb.commit()
sqlUpdate("UPDATE DashboardAPIKeys SET ExpiredAt = datetime('now', 'localtime') WHERE Key = ?", (key, ))
# sqldb.commit()
self.DashboardAPIKeys = self.__getAPIKeys()
@@ -1344,6 +1369,14 @@ def _getWireguardConfigurationAvailableIP(configName: str) -> tuple[bool, list[s
for i in add:
a, c = i.split('/')
existedAddress.append(ipaddress.ip_address(a.replace(" ", "")))
for p in configuration.getRestrictedPeersList():
if len(p.allowed_ip) > 0:
add = p.allowed_ip.split(',')
for i in add:
a, c = i.split('/')
existedAddress.append(ipaddress.ip_address(a.replace(" ", "")))
for i in address:
addressSplit, cidr = i.split('/')
existedAddress.append(ipaddress.ip_address(addressSplit.replace(" ", "")))
@@ -1365,6 +1398,17 @@ sqldb = sqlite3.connect(os.path.join(CONFIGURATION_PATH, 'db', 'wgdashboard.db')
sqldb.row_factory = sqlite3.Row
cursor = sqldb.cursor()
def sqlSelect(statement: str, paramters: tuple = ()) -> sqlite3.Cursor:
with sqldb:
cursor = sqldb.cursor()
return cursor.execute(statement, paramters)
def sqlUpdate(statement: str, paramters: tuple = ()) -> sqlite3.Cursor:
with sqldb:
cursor = sqldb.cursor()
cursor.execute(statement, paramters)
sqldb.commit()
DashboardConfig = DashboardConfig()
_, APP_PREFIX = DashboardConfig.GetConfig("Server", "app_prefix")
cors = CORS(app, resources={rf"{APP_PREFIX}/api/*": {
@@ -1419,6 +1463,7 @@ def auth_req():
and f"{(APP_PREFIX if len(APP_PREFIX) > 0 else '')}" != request.path)
and "validateAuthentication" not in request.path and "authenticate" not in request.path
and "getDashboardConfiguration" not in request.path and "getDashboardTheme" not in request.path
and "getDashboardVersion" not in request.path
and "sharePeer/get" not in request.path
and "isTotpEnabled" not in request.path
):
@@ -1751,10 +1796,13 @@ def API_addPeers(configName):
return ResponseObject(False, "Please fill in all required box.")
if not config.getStatus():
config.toggleConfiguration()
availableIps = _getWireguardConfigurationAvailableIP(configName)
if bulkAdd:
if bulkAddAmount < 1:
return ResponseObject(False, "Please specify amount of peers you want to add")
availableIps = _getWireguardConfigurationAvailableIP(configName)
if not availableIps[0]:
return ResponseObject(False, "No more available IP can assign")
if bulkAddAmount > len(availableIps[1]):
@@ -1788,6 +1836,11 @@ def API_addPeers(configName):
return ResponseObject(False, f"This peer already exist.")
name = data['name']
private_key = data['private_key']
for i in allowed_ips:
if i not in availableIps[1]:
return ResponseObject(False, f"This IP is not available: {i}")
config.addPeers([{"id": public_key, "allowed_ip": ''.join(allowed_ips)}])
# subprocess.check_output(
# f"wg set {config.Name} peer {public_key} allowed-ips {''.join(allowed_ips)}",
@@ -1857,6 +1910,10 @@ def API_getConfigurationInfo():
def API_getDashboardTheme():
return ResponseObject(data=DashboardConfig.GetConfig("Server", "dashboard_theme")[1])
@app.route(f'{APP_PREFIX}/api/getDashboardVersion')
def API_getDashboardVersion():
return ResponseObject(data=DashboardConfig.GetConfig("Server", "version")[1])
@app.route(f'{APP_PREFIX}/api/savePeerScheduleJob/', methods=["POST"])
def API_savePeerScheduleJob():
@@ -2006,8 +2063,7 @@ def API_traceroute_execute():
@app.route(f'{APP_PREFIX}/api/getDashboardUpdate')
def API_getDashboardUpdate():
import urllib.request as req;
import urllib.request as req
try:
r = req.urlopen("https://api.github.com/repos/donaldzou/WGDashboard/releases/latest", timeout=5).read()
data = dict(json.loads(r))
@@ -2020,8 +2076,8 @@ def API_getDashboardUpdate():
return ResponseObject(message="You're on the latest version")
return ResponseObject(False)
except urllib.error.HTTPError as e:
return ResponseObject(False, f"Request to GitHub API failed. Returned a {e.code} status.")
except urllib.error.HTTPError and urllib.error.URLError as e:
return ResponseObject(False, f"Request to GitHub API failed.")
'''
Sign Up
@@ -2102,6 +2158,7 @@ def backGroundThread():
c.getPeersLatestHandshake()
c.getPeersEndpoint()
c.getPeersList()
c.getRestrictedPeersList()
except Exception as e:
print(f"[WGDashboard] Background Thread #1 Error: {str(e)}", flush=True)
time.sleep(10)
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.2 MiB

File diff suppressed because one or more lines are too long
+16 -16
View File
File diff suppressed because one or more lines are too long
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.5 MiB

+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "app",
"version": "4.0.0",
"version": "4.0.2",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"build electron": "vite build && vite build --mode electron && cd ../../../../WGDashboard-Desktop && electron-builder",
"build electron": "vite build && vite build --mode electron && cd ../../../../WGDashboard-Desktop && electron-builder --mac --win",
"preview": "vite preview"
},
"dependencies": {
@@ -36,8 +36,11 @@ export default {
addAllowedIp(ip){
if(this.store.checkCIDR(ip)){
this.data.allowed_ips.push(ip);
this.customAvailableIp = ''
return true;
}
this.allowedIpFormatError = true;
this.dashboardStore.newMessage('WGDashboard', 'Allowed IP is invalid', 'danger')
return false;
}
},
@@ -80,10 +83,7 @@ export default {
:disabled="bulk">
<button class="btn btn-outline-success btn-sm rounded-end-3"
:disabled="bulk || !this.customAvailableIp"
@click="this.addAllowedIp(this.customAvailableIp)
? this.customAvailableIp = '' :
this.allowedIpFormatError = true;
this.dashboardStore.newMessage('WGDashboard', 'Allowed IP is invalid', 'danger')"
@click="this.addAllowedIp(this.customAvailableIp)"
type="button" id="button-addon2">
<i class="bi bi-plus-lg"></i>
</button>
@@ -200,7 +200,8 @@ export default {
})
this.loading = false;
if (this.configurationPeers.length > 0){
const sent = this.configurationPeers.map(x => x.total_sent + x.cumu_sent).reduce((x,y) => x + y).toFixed(4);
const sent = this.configurationPeers.map(x => x.total_sent + x.cumu_sent)
.reduce((x,y) => x + y).toFixed(4);
const receive = this.configurationPeers.map(x => x.total_receive + x.cumu_receive).reduce((x,y) => x + y).toFixed(4);
if (
this.historyDataSentDifference[this.historyDataSentDifference.length - 1] !== sent
@@ -259,13 +260,13 @@ export default {
connectedPeers: this.configurationPeers.filter(x => x.status === "running").length,
totalUsage: this.configurationPeers.length > 0 ?
this.configurationPeers.filter(x => !x.restricted)
.map(x => x.total_data + x.cumu_data).reduce((a, b) => a + b).toFixed(4) : 0,
.map(x => x.total_data + x.cumu_data).reduce((a, b) => a + b, 0).toFixed(4) : 0,
totalReceive: this.configurationPeers.length > 0 ?
this.configurationPeers.filter(x => !x.restricted)
.map(x => x.total_receive + x.cumu_receive).reduce((a, b) => a + b).toFixed(4) : 0,
.map(x => x.total_receive + x.cumu_receive).reduce((a, b) => a + b, 0).toFixed(4) : 0,
totalSent: this.configurationPeers.length > 0 ?
this.configurationPeers.filter(x => !x.restricted)
.map(x => x.total_sent + x.cumu_sent).reduce((a, b) => a + b).toFixed(4) : 0
.map(x => x.total_sent + x.cumu_sent).reduce((a, b) => a + b, 0).toFixed(4) : 0
}
return k
+14 -8
View File
@@ -11,16 +11,22 @@ export default {
const store = DashboardConfigurationStore()
let theme = "dark"
let totpEnabled = false;
let version = undefined;
if (!store.IsElectronApp){
await fetchGet("/api/getDashboardTheme", {}, (res) => {
theme = res.data
});
await fetchGet("/api/isTotpEnabled", {}, (res) => {
totpEnabled = res.data
});
await Promise.all([
fetchGet("/api/getDashboardTheme", {}, (res) => {
theme = res.data
}),
fetchGet("/api/isTotpEnabled", {}, (res) => {
totpEnabled = res.data
}),
fetchGet("/api/getDashboardVersion", {}, (res) => {
version = res.data
})
]);
}
store.removeActiveCrossServer();
return {store, theme, totpEnabled}
return {store, theme, totpEnabled, version}
},
data(){
return {
@@ -146,7 +152,7 @@ export default {
</div>
</div>
<small class="text-muted pb-3 d-block w-100 text-center mt-3">
WGDashboard v4.0 | Developed with by
WGDashboard {{ this.version }} | Developed with by
<a href="https://github.com/donaldzou" target="_blank"><strong>Donald Zou</strong></a>
</small>
<div class="messageCentre text-body position-absolute end-0 m-3">
+38 -24
View File
@@ -2,7 +2,7 @@
# wgd.sh - Copyright(C) 2024 Donald Zou [https://github.com/donaldzou]
# Under Apache-2.0 License
trap "kill $TOP_PID"
#trap "kill $TOP_PID"
export TOP_PID=$$
app_name="dashboard.py"
@@ -220,7 +220,7 @@ _checkPythonVersion(){
else
printf "[WGDashboard] %s Could not find a compatible version of Python. Current Python is %s.\n" "$heavy_crossmark" "$version"
printf "[WGDashboard] WGDashboard required Python 3.10, 3.11 or 3.12. Halting install now.\n"
kill $TOP_PID
kill $TOP_PID
fi
}
@@ -337,28 +337,42 @@ start_wgd_debug() {
}
update_wgd() {
new_ver=$(venv_python -c "import json; import urllib.request; data = urllib.request.urlopen('https://api.github.com/repos/donaldzou/WGDashboard/releases/latest').read(); output = json.loads(data);print(output['tag_name'])")
printf "%s\n" "$dashes"
printf "[WGDashboard] Are you sure you want to update to the %s? (Y/N): " "$new_ver"
read up
if [ "$up" = "Y" ] || [ "$up" = "y" ]; then
printf "[WGDashboard] Shutting down WGDashboard\n"
if check_wgd_status; then
stop_wgd
fi
mv wgd.sh wgd.sh.old
printf "[WGDashboard] Downloading %s from GitHub..." "$new_ver"
{ date; git stash; git pull https://github.com/donaldzou/WGDashboard.git $new_ver --force; } >> ./log/update.txt
chmod +x ./wgd.sh
sudo ./wgd.sh install
printf "[WGDashboard] Update completed!\n"
printf "%s\n" "$dashes"
rm wgd.sh.old
else
printf "%s\n" "$dashes"
printf "| Update Canceled. |\n"
printf "%s\n" "$dashes"
fi
_determineOS
if ! python3 --version > /dev/null 2>&1
then
printf "[WGDashboard] Python is not installed, trying to install now\n"
_installPython
else
printf "[WGDashboard] %s Python is installed\n" "$heavy_checkmark"
fi
_checkPythonVersion
_installPythonVenv
_installPythonPip
new_ver=$($venv_python -c "import json; import urllib.request; data = urllib.request.urlopen('https://api.github.com/repos/donaldzou/WGDashboard/releases/latest').read(); output = json.loads(data);print(output['tag_name'])")
printf "%s\n" "$dashes"
printf "[WGDashboard] Are you sure you want to update to the %s? (Y/N): " "$new_ver"
read up
if [ "$up" = "Y" ] || [ "$up" = "y" ]; then
printf "[WGDashboard] Shutting down WGDashboard\n"
if check_wgd_status; then
stop_wgd
fi
mv wgd.sh wgd.sh.old
printf "[WGDashboard] Downloading %s from GitHub..." "$new_ver"
{ date; git stash; git pull https://github.com/donaldzou/WGDashboard.git $new_ver --force; } >> ./log/update.txt
chmod +x ./wgd.sh
sudo ./wgd.sh install
printf "[WGDashboard] Update completed!\n"
printf "%s\n" "$dashes"
rm wgd.sh.old
else
printf "%s\n" "$dashes"
printf "[WGDashboard] Update Canceled.\n"
printf "%s\n" "$dashes"
fi
}
if [ "$#" != 1 ];