1
0
mirror of https://github.com/donaldzou/WGDashboard.git synced 2024-11-06 07:50:13 +01:00

Fixed recursive use of cursor

This commit is contained in:
Donald Zou 2024-08-20 00:02:00 -07:00
parent f042e42633
commit 63dc9834be
2 changed files with 156 additions and 124 deletions

View File

@ -119,26 +119,30 @@ class DashboardLogger:
self.loggerdb = sqlite3.connect(os.path.join(CONFIGURATION_PATH, 'db', 'wgdashboard_log.db'), self.loggerdb = sqlite3.connect(os.path.join(CONFIGURATION_PATH, 'db', 'wgdashboard_log.db'),
check_same_thread=False) check_same_thread=False)
self.loggerdb.row_factory = sqlite3.Row self.loggerdb.row_factory = sqlite3.Row
self.loggerdbCursor = self.loggerdb.cursor()
self.__createLogDatabase() self.__createLogDatabase()
self.log(Message="WGDashboard started") self.log(Message="WGDashboard started")
def __createLogDatabase(self): def __createLogDatabase(self):
existingTable = self.loggerdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall() with self.loggerdb:
existingTable = [t['name'] for t in existingTable] loggerdbCursor = self.loggerdb.cursor()
existingTable = loggerdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
if "DashboardLog" not in existingTable: existingTable = [t['name'] for t in existingTable]
self.loggerdbCursor.execute( if "DashboardLog" not in existingTable:
"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))") loggerdbCursor.execute(
self.loggerdb.commit() "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: def log(self, URL: str = "", IP: str = "", Status: str = "true", Message: str = "") -> bool:
try: try:
self.loggerdbCursor.execute( with self.loggerdb:
"INSERT INTO DashboardLog (LogID, URL, IP, Status, Message) VALUES (?, ?, ?, ?, ?)", (str(uuid.uuid4()), URL, IP, Status, Message,)) loggerdbCursor = self.loggerdb.cursor()
self.loggerdb.commit() loggerdbCursor.execute(
return True "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: except Exception as e:
print(e) print(f"[WGDashboard] Access Log Error: {str(e)}")
return False return False
class PeerJobLogger: class PeerJobLogger:
@ -147,23 +151,29 @@ class PeerJobLogger:
check_same_thread=False) check_same_thread=False)
self.loggerdb.row_factory = sqlite3.Row self.loggerdb.row_factory = sqlite3.Row
self.logs:list(Log) = [] self.logs:list(Log) = []
self.loggerdbCursor = self.loggerdb.cursor()
self.__createLogDatabase() self.__createLogDatabase()
def __createLogDatabase(self): def __createLogDatabase(self):
existingTable = self.loggerdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall() with self.loggerdb:
existingTable = [t['name'] for t in existingTable] loggerdbCursor = self.loggerdb.cursor()
if "JobLog" not in existingTable: existingTable = loggerdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
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))") existingTable = [t['name'] for t in existingTable]
self.loggerdb.commit()
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: def log(self, JobID: str, Status: bool = True, Message: str = "") -> bool:
try: try:
self.loggerdbCursor.execute(f"INSERT INTO JobLog (LogID, JobID, Status, Message) VALUES (?, ?, ?, ?)", with self.loggerdb:
(str(uuid.uuid4()), JobID, Status, Message,)) loggerdbCursor = self.loggerdb.cursor()
self.loggerdb.commit() 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: except Exception as e:
print(e) print(f"[WGDashboard] Peer Job Log Error: {str(e)}")
return False return False
return True return True
@ -172,11 +182,13 @@ class PeerJobLogger:
try: try:
allJobs = AllPeerJobs.getAllJobs(configName) allJobs = AllPeerJobs.getAllJobs(configName)
allJobsID = ", ".join([f"'{x.JobID}'" for x in allJobs]) 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() with self.loggerdb:
self.logs.clear() loggerdbCursor = self.loggerdb.cursor()
for l in table: table = loggerdbCursor.execute(f"SELECT * FROM JobLog WHERE JobID IN ({allJobsID}) ORDER BY LogDate DESC").fetchall()
logs.append( self.logs.clear()
Log(l["LogID"], l["JobID"], l["LogDate"], l["Status"], l["Message"])) for l in table:
logs.append(
Log(l["LogID"], l["JobID"], l["LogDate"], l["Status"], l["Message"]))
except Exception as e: except Exception as e:
return logs return logs
return logs return logs
@ -217,41 +229,47 @@ class PeerJobs:
self.jobdb = sqlite3.connect(os.path.join(CONFIGURATION_PATH, 'db', 'wgdashboard_job.db'), self.jobdb = sqlite3.connect(os.path.join(CONFIGURATION_PATH, 'db', 'wgdashboard_job.db'),
check_same_thread=False) check_same_thread=False)
self.jobdb.row_factory = sqlite3.Row self.jobdb.row_factory = sqlite3.Row
self.jobdbCursor = self.jobdb.cursor()
self.__createPeerJobsDatabase() self.__createPeerJobsDatabase()
self.__getJobs() self.__getJobs()
def __getJobs(self): def __getJobs(self):
self.Jobs.clear() self.Jobs.clear()
jobs = self.jobdbCursor.execute("SELECT * FROM PeerJobs WHERE ExpireDate IS NULL").fetchall() with self.jobdb:
for job in jobs: jobdbCursor = self.jobdb.cursor()
self.Jobs.append(PeerJob( jobs = jobdbCursor.execute("SELECT * FROM PeerJobs WHERE ExpireDate IS NULL").fetchall()
job['JobID'], job['Configuration'], job['Peer'], job['Field'], job['Operator'], job['Value'], for job in jobs:
job['CreationDate'], job['ExpireDate'], job['Action'])) 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): def getAllJobs(self, configuration: str = None):
if configuration is not None: if configuration is not None:
jobs = self.jobdbCursor.execute( with self.jobdb:
f"SELECT * FROM PeerJobs WHERE Configuration = ?", (configuration, )).fetchall() jobdbCursor = self.jobdb.cursor()
j = [] jobs = jobdbCursor.execute(
for job in jobs: f"SELECT * FROM PeerJobs WHERE Configuration = ?", (configuration, )).fetchall()
j.append(PeerJob( j = []
job['JobID'], job['Configuration'], job['Peer'], job['Field'], job['Operator'], job['Value'], for job in jobs:
job['CreationDate'], job['ExpireDate'], job['Action'])) j.append(PeerJob(
return j job['JobID'], job['Configuration'], job['Peer'], job['Field'], job['Operator'], job['Value'],
job['CreationDate'], job['ExpireDate'], job['Action']))
return j
return [] return []
def __createPeerJobsDatabase(self): def __createPeerJobsDatabase(self):
existingTable = self.jobdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall() with self.jobdb:
existingTable = [t['name'] for t in existingTable] jobdbCursor = self.jobdb.cursor()
if "PeerJobs" not in existingTable: existingTable = jobdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
self.jobdbCursor.execute(''' existingTable = [t['name'] for t in existingTable]
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, if "PeerJobs" not in existingTable:
ExpireDate DATETIME, Action VARCHAR NOT NULL, PRIMARY KEY (JobID)) jobdbCursor.execute('''
''') CREATE TABLE PeerJobs (JobID VARCHAR NOT NULL, Configuration VARCHAR NOT NULL, Peer VARCHAR NOT NULL,
self.jobdb.commit() 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): def toJson(self):
return [x.toJson() for x in self.Jobs] 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]: def saveJob(self, Job: PeerJob) -> tuple[bool, list] | tuple[bool, str]:
try: try:
if (len(str(Job.CreationDate))) == 0: with self.jobdb:
self.jobdbCursor.execute(''' jobdbCursor = self.jobdb.cursor()
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,)) if (len(str(Job.CreationDate))) == 0:
JobLogger.log(Job.JobID, Message=f"Job is created if {Job.Field} {Job.Operator} {Job.Value} then {Job.Action}") jobdbCursor.execute('''
INSERT INTO PeerJobs VALUES (?, ?, ?, ?, ?, ?, strftime('%Y-%m-%d %H:%M:%S','now'), NULL, ?)
else: ''', (Job.JobID, Job.Configuration, Job.Peer, Job.Field, Job.Operator, Job.Value, Job.Action,))
currentJob = self.jobdbCursor.execute('SELECT * FROM PeerJobs WHERE JobID = ?', (Job.JobID, )).fetchone() JobLogger.log(Job.JobID, Message=f"Job is created if {Job.Field} {Job.Operator} {Job.Value} then {Job.Action}")
if currentJob is not None:
self.jobdbCursor.execute(''' else:
UPDATE PeerJobs SET Field = ?, Operator = ?, Value = ?, Action = ? WHERE JobID = ? currentJob = jobdbCursor.execute('SELECT * FROM PeerJobs WHERE JobID = ?', (Job.JobID, )).fetchone()
''', (Job.Field, Job.Operator, Job.Value, Job.Action, Job.JobID)) if currentJob is not None:
JobLogger.log(Job.JobID, jobdbCursor.execute('''
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}") UPDATE PeerJobs SET Field = ?, Operator = ?, Value = ?, Action = ? WHERE JobID = ?
self.jobdb.commit() ''', (Job.Field, Job.Operator, Job.Value, Job.Action, Job.JobID))
self.__getJobs() 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( return True, list(
filter(lambda x: x.Configuration == Job.Configuration and x.Peer == Job.Peer and x.JobID == Job.JobID, filter(lambda x: x.Configuration == Job.Configuration and x.Peer == Job.Peer and x.JobID == Job.JobID,
@ -288,10 +309,12 @@ class PeerJobs:
try: try:
if (len(str(Job.CreationDate))) == 0: if (len(str(Job.CreationDate))) == 0:
return False, "Job does not exist" return False, "Job does not exist"
self.jobdbCursor.execute(''' with self.jobdb:
UPDATE PeerJobs SET ExpireDate = strftime('%Y-%m-%d %H:%M:%S','now') WHERE JobID = ? jobdbCursor = self.jobdb.cursor()
''', (Job.JobID,)) jobdbCursor.execute('''
self.jobdb.commit() 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.") JobLogger.log(Job.JobID, Message=f"Job is removed due to being deleted or finshed.")
self.__getJobs() self.__getJobs()
return True, list( return True, list(
@ -364,10 +387,9 @@ class PeerShareLink:
class PeerShareLinks: class PeerShareLinks:
def __init__(self): def __init__(self):
self.Links: list[PeerShareLink] = [] self.Links: list[PeerShareLink] = []
self.PeerShareLinkCursor = sqldb.cursor() existingTables = sqlSelect("SELECT name FROM sqlite_master WHERE type='table' and name = 'PeerShareLinks'").fetchall()
existingTables = self.PeerShareLinkCursor.execute("SELECT name FROM sqlite_master WHERE type='table' and name = 'PeerShareLinks'").fetchall()
if len(existingTables) == 0: if len(existingTables) == 0:
self.PeerShareLinkCursor.execute( sqlUpdate(
""" """
CREATE TABLE PeerShareLinks ( CREATE TABLE PeerShareLinks (
ShareID VARCHAR NOT NULL PRIMARY KEY, Configuration VARCHAR NOT NULL, Peer VARCHAR NOT NULL, 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() self.__getSharedLinks()
# print(self.Links) # print(self.Links)
def __getSharedLinks(self): def __getSharedLinks(self):
self.Links.clear() 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: for link in allLinks:
self.Links.append(PeerShareLink(*link)) self.Links.append(PeerShareLink(*link))
@ -397,18 +419,17 @@ class PeerShareLinks:
try: try:
newShareID = str(uuid.uuid4()) newShareID = str(uuid.uuid4())
if len(self.getLink(Configuration, Peer)) > 0: if len(self.getLink(Configuration, Peer)) > 0:
self.PeerShareLinkCursor.execute("UPDATE PeerShareLinks SET ExpireDate = datetime('now', 'localtime') WHERE Configuration = ? AND Peer = ?", (Configuration, Peer, )) sqlUpdate("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, )) sqlUpdate("INSERT INTO PeerShareLinks (ShareID, Configuration, Peer, ExpireDate) VALUES (?, ?, ?, ?)", (newShareID, Configuration, Peer, ExpireDate, ))
sqldb.commit() # sqldb.commit()
self.__getSharedLinks() self.__getSharedLinks()
except Exception as e: except Exception as e:
return False, str(e) return False, str(e)
return True, newShareID return True, newShareID
def updateLinkExpireDate(self, ShareID, ExpireDate: datetime = None) -> tuple[bool, str]: def updateLinkExpireDate(self, ShareID, ExpireDate: datetime = None) -> tuple[bool, str]:
sqlUpdate("UPDATE PeerShareLinks SET ExpireDate = ? WHERE ShareID = ?;", (ExpireDate, ShareID, ))
self.PeerShareLinkCursor.execute("UPDATE PeerShareLinks SET ExpireDate = ? WHERE ShareID = ?;", (ExpireDate, ShareID, )) # sqldb.commit()
sqldb.commit()
self.__getSharedLinks() self.__getSharedLinks()
return True, "" return True, ""
@ -493,10 +514,10 @@ class WireguardConfiguration:
self.getRestrictedPeersList() self.getRestrictedPeersList()
def __createDatabase(self): 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] existingTables = [t['name'] for t in existingTables]
if self.Name not in existingTables: if self.Name not in existingTables:
sqldb.cursor().execute( sqlUpdate(
""" """
CREATE TABLE '%s'( CREATE TABLE '%s'(
id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL, id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL,
@ -509,10 +530,10 @@ class WireguardConfiguration:
) )
""" % self.Name """ % self.Name
) )
sqldb.commit() # sqldb.commit()
if f'{self.Name}_restrict_access' not in existingTables: if f'{self.Name}_restrict_access' not in existingTables:
sqldb.cursor().execute( sqlUpdate(
""" """
CREATE TABLE '%s_restrict_access' ( CREATE TABLE '%s_restrict_access' (
id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL, id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL,
@ -525,9 +546,9 @@ class WireguardConfiguration:
) )
""" % self.Name """ % self.Name
) )
sqldb.commit() # sqldb.commit()
if f'{self.Name}_transfer' not in existingTables: if f'{self.Name}_transfer' not in existingTables:
sqldb.cursor().execute( sqlUpdate(
""" """
CREATE TABLE '%s_transfer' ( CREATE TABLE '%s_transfer' (
id VARCHAR NOT NULL, total_receive FLOAT NULL, id VARCHAR NOT NULL, total_receive FLOAT NULL,
@ -536,9 +557,9 @@ class WireguardConfiguration:
) )
""" % self.Name """ % self.Name
) )
sqldb.commit() # sqldb.commit()
if f'{self.Name}_deleted' not in existingTables: if f'{self.Name}_deleted' not in existingTables:
sqldb.cursor().execute( sqlUpdate(
""" """
CREATE TABLE '%s_deleted' ( CREATE TABLE '%s_deleted' (
id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL, id VARCHAR NOT NULL, private_key VARCHAR NULL, DNS VARCHAR NULL,
@ -551,7 +572,7 @@ class WireguardConfiguration:
) )
""" % self.Name """ % self.Name
) )
sqldb.commit() # sqldb.commit()
@ -564,7 +585,7 @@ class WireguardConfiguration:
def __getRestrictedPeers(self): def __getRestrictedPeers(self):
self.RestrictedPeers = [] 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: for i in restricted:
self.RestrictedPeers.append(Peer(i, self)) self.RestrictedPeers.append(Peer(i, self))
@ -600,7 +621,7 @@ class WireguardConfiguration:
for i in p: for i in p:
if "PublicKey" in i.keys(): if "PublicKey" in i.keys():
checkIfExist = sqldb.cursor().execute("SELECT * FROM '%s' WHERE id = ?" % self.Name, checkIfExist = sqlSelect("SELECT * FROM '%s' WHERE id = ?" % self.Name,
((i['PublicKey']),)).fetchone() ((i['PublicKey']),)).fetchone()
if checkIfExist is None: if checkIfExist is None:
newPeer = { newPeer = {
@ -626,7 +647,7 @@ class WireguardConfiguration:
"remote_endpoint": DashboardConfig.GetConfig("Peers", "remote_endpoint")[1], "remote_endpoint": DashboardConfig.GetConfig("Peers", "remote_endpoint")[1],
"preshared_key": i["PresharedKey"] if "PresharedKey" in i.keys() else "" "preshared_key": i["PresharedKey"] if "PresharedKey" in i.keys() else ""
} }
sqldb.cursor().execute( sqlUpdate(
""" """
INSERT INTO '%s' INSERT INTO '%s'
VALUES (:id, :private_key, :DNS, :endpoint_allowed_ip, :name, :total_receive, :total_sent, VALUES (:id, :private_key, :DNS, :endpoint_allowed_ip, :name, :total_receive, :total_sent,
@ -634,12 +655,12 @@ class WireguardConfiguration:
:cumu_data, :mtu, :keepalive, :remote_endpoint, :preshared_key); :cumu_data, :mtu, :keepalive, :remote_endpoint, :preshared_key);
""" % self.Name """ % self.Name
, newPeer) , newPeer)
sqldb.commit() # sqldb.commit()
self.Peers.append(Peer(newPeer, self)) self.Peers.append(Peer(newPeer, self))
else: else:
sqldb.cursor().execute("UPDATE '%s' SET allowed_ip = ? WHERE id = ?" % self.Name, sqlUpdate("UPDATE '%s' SET allowed_ip = ? WHERE id = ?" % self.Name,
(i.get("AllowedIPs", "N/A"), i['PublicKey'],)) (i.get("AllowedIPs", "N/A"), i['PublicKey'],))
sqldb.commit() # sqldb.commit()
self.Peers.append(Peer(checkIfExist, self)) self.Peers.append(Peer(checkIfExist, self))
except Exception as e: except Exception as e:
print(f"[WGDashboard] {self.Name} Error: {str(e)}") print(f"[WGDashboard] {self.Name} Error: {str(e)}")
@ -666,11 +687,11 @@ class WireguardConfiguration:
self.toggleConfiguration() self.toggleConfiguration()
for i in listOfPublicKeys: 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: 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'],)) % (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'],)) % self.Name, (p['id'],))
subprocess.check_output(f"wg set {self.Name} peer {p['id']} allowed-ips {p['allowed_ip']}", subprocess.check_output(f"wg set {self.Name} peer {p['id']} allowed-ips {p['allowed_ip']}",
shell=True, stderr=subprocess.STDOUT) shell=True, stderr=subprocess.STDOUT)
@ -693,12 +714,12 @@ class WireguardConfiguration:
try: try:
subprocess.check_output(f"wg set {self.Name} peer {pf.id} remove", subprocess.check_output(f"wg set {self.Name} peer {pf.id} remove",
shell=True, stderr=subprocess.STDOUT) 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,)) (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,)) (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() # sqldb.commit()
numOfRestrictedPeers += 1 numOfRestrictedPeers += 1
except Exception as e: except Exception as e:
numOfFailedToRestrictPeers += 1 numOfFailedToRestrictPeers += 1
@ -725,7 +746,7 @@ class WireguardConfiguration:
try: try:
subprocess.check_output(f"wg set {self.Name} peer {pf.id} remove", subprocess.check_output(f"wg set {self.Name} peer {pf.id} remove",
shell=True, stderr=subprocess.STDOUT) 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 numOfDeletedPeers += 1
except Exception as e: except Exception as e:
numOfFailedToDeletePeers += 1 numOfFailedToDeletePeers += 1
@ -801,7 +822,7 @@ class WireguardConfiguration:
data_usage = [p.split("\t") for p in data_usage] data_usage = [p.split("\t") for p in data_usage]
for i in range(len(data_usage)): for i in range(len(data_usage)):
if len(data_usage[i]) == 3: 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= ? " "SELECT total_receive, total_sent, cumu_receive, cumu_sent, status FROM '%s' WHERE id= ? "
% self.Name, (data_usage[i][0],)).fetchone() % self.Name, (data_usage[i][0],)).fetchone()
if cur_i is not None: if cur_i is not None:
@ -816,7 +837,7 @@ class WireguardConfiguration:
total_sent = cur_total_sent total_sent = cur_total_sent
total_receive = cur_total_receive total_receive = cur_total_receive
else: else:
sqldb.cursor().execute( sqlUpdate(
"UPDATE '%s' SET cumu_receive = ?, cumu_sent = ?, cumu_data = ? WHERE id = ?" % "UPDATE '%s' SET cumu_receive = ?, cumu_sent = ?, cumu_data = ? WHERE id = ?" %
self.Name, (cumulative_receive, cumulative_sent, self.Name, (cumulative_receive, cumulative_sent,
cumulative_sent + cumulative_receive, cumulative_sent + cumulative_receive,
@ -826,7 +847,7 @@ class WireguardConfiguration:
total_receive = 0 total_receive = 0
_, p = self.searchPeer(data_usage[i][0]) _, p = self.searchPeer(data_usage[i][0])
if p.total_receive != total_receive or p.total_sent != total_sent: 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 = ?" "UPDATE '%s' SET total_receive = ?, total_sent = ?, total_data = ? WHERE id = ?"
% self.Name, (total_receive, total_sent, % self.Name, (total_receive, total_sent,
total_receive + total_sent, data_usage[i][0],)) total_receive + total_sent, data_usage[i][0],))
@ -847,7 +868,7 @@ class WireguardConfiguration:
for _ in range(int(len(data_usage) / 2)): for _ in range(int(len(data_usage) / 2)):
sqldb.execute("UPDATE '%s' SET endpoint = ? WHERE id = ?" % self.Name sqldb.execute("UPDATE '%s' SET endpoint = ? WHERE id = ?" % self.Name
, (data_usage[count + 1], data_usage[count],)) , (data_usage[count + 1], data_usage[count],))
sqldb.commit() # sqldb.commit()
count += 2 count += 2
def toggleConfiguration(self) -> [bool, str]: def toggleConfiguration(self) -> [bool, str]:
@ -982,7 +1003,7 @@ class Peer:
if f"wg showconf {self.configuration.Name}" not in saveConfig.decode().strip('\n'): if f"wg showconf {self.configuration.Name}" not in saveConfig.decode().strip('\n'):
return ResponseObject(False, return ResponseObject(False,
"Update peer failed when saving the configuration.") "Update peer failed when saving the configuration.")
sqldb.cursor().execute( sqlUpdate(
'''UPDATE '%s' SET name = ?, private_key = ?, DNS = ?, endpoint_allowed_ip = ?, mtu = ?, '''UPDATE '%s' SET name = ?, private_key = ?, DNS = ?, endpoint_allowed_ip = ?, mtu = ?,
keepalive = ?, preshared_key = ? WHERE id = ?''' % self.configuration.Name, keepalive = ?, preshared_key = ? WHERE id = ?''' % self.configuration.Name,
(name, private_key, dns_addresses, endpoint_allowed_ip, mtu, (name, private_key, dns_addresses, endpoint_allowed_ip, mtu,
@ -1035,11 +1056,11 @@ PersistentKeepalive = {str(self.keepalive)}
def resetDataUsage(self, type): def resetDataUsage(self, type):
try: try:
if type == "total": 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": 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": 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: else:
return False return False
except Exception as e: except Exception as e:
@ -1121,13 +1142,13 @@ class DashboardConfig:
def __createAPIKeyTable(self): 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: 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)") sqlUpdate("CREATE TABLE DashboardAPIKeys (Key VARCHAR NOT NULL PRIMARY KEY, CreatedAt DATETIME NOT NULL DEFAULT (datetime('now', 'localtime')), ExpiredAt VARCHAR)")
sqldb.commit() # sqldb.commit()
def __getAPIKeys(self) -> list[DashboardAPIKey]: 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 = [] fKeys = []
for k in keys: for k in keys:
fKeys.append(DashboardAPIKey(*k)) fKeys.append(DashboardAPIKey(*k))
@ -1135,13 +1156,13 @@ class DashboardConfig:
def createAPIKeys(self, ExpiredAt = None): def createAPIKeys(self, ExpiredAt = None):
newKey = secrets.token_urlsafe(32) newKey = secrets.token_urlsafe(32)
sqldb.cursor().execute('INSERT INTO DashboardAPIKeys (Key, ExpiredAt) VALUES (?, ?)', (newKey, ExpiredAt,)) sqlUpdate('INSERT INTO DashboardAPIKeys (Key, ExpiredAt) VALUES (?, ?)', (newKey, ExpiredAt,))
sqldb.commit() # sqldb.commit()
self.DashboardAPIKeys = self.__getAPIKeys() self.DashboardAPIKeys = self.__getAPIKeys()
def deleteAPIKey(self, key): def deleteAPIKey(self, key):
sqldb.cursor().execute("UPDATE DashboardAPIKeys SET ExpiredAt = datetime('now', 'localtime') WHERE Key = ?", (key, )) sqlUpdate("UPDATE DashboardAPIKeys SET ExpiredAt = datetime('now', 'localtime') WHERE Key = ?", (key, ))
sqldb.commit() # sqldb.commit()
self.DashboardAPIKeys = self.__getAPIKeys() self.DashboardAPIKeys = self.__getAPIKeys()
@ -1377,6 +1398,17 @@ sqldb = sqlite3.connect(os.path.join(CONFIGURATION_PATH, 'db', 'wgdashboard.db')
sqldb.row_factory = sqlite3.Row sqldb.row_factory = sqlite3.Row
cursor = sqldb.cursor() 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() DashboardConfig = DashboardConfig()
_, APP_PREFIX = DashboardConfig.GetConfig("Server", "app_prefix") _, APP_PREFIX = DashboardConfig.GetConfig("Server", "app_prefix")
cors = CORS(app, resources={rf"{APP_PREFIX}/api/*": { cors = CORS(app, resources={rf"{APP_PREFIX}/api/*": {

View File

@ -1,6 +1,6 @@
{ {
"name": "app", "name": "app",
"version": "4.0.1.1", "version": "4.0.2",
"private": true, "private": true,
"type": "module", "type": "module",
"scripts": { "scripts": {