mirror of
https://github.com/WGDashboard/WGDashboard.git
synced 2026-08-04 06:53:00 +00:00
Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3c50e4768a | |||
| 63dc9834be | |||
| f042e42633 | |||
| 39b80a2e7e | |||
| fb6e948358 | |||
| 181b0845bf | |||
| b2a82dcfe5 | |||
| cd73aef0c9 | |||
| ed522ec024 | |||
| 16998d1e16 | |||
| 11421d2d32 | |||
| 1af708aaea |
@@ -502,7 +502,7 @@ Endpoint = 0.0.0.0:51820
|
|||||||
|
|
||||||
2. Update the dashboard
|
2. Update the dashboard
|
||||||
```shell
|
```shell
|
||||||
git pull https://github.com/donaldzou/WGDashboard.git v4.0 --force
|
git pull https://github.com/donaldzou/WGDashboard.git --force
|
||||||
```
|
```
|
||||||
|
|
||||||
3. Install
|
3. Install
|
||||||
|
|||||||
+134
-77
@@ -33,7 +33,7 @@ import threading
|
|||||||
|
|
||||||
from flask.json.provider import DefaultJSONProvider
|
from flask.json.provider import DefaultJSONProvider
|
||||||
|
|
||||||
DASHBOARD_VERSION = 'v4.0'
|
DASHBOARD_VERSION = 'v4.0.2'
|
||||||
CONFIGURATION_PATH = os.getenv('CONFIGURATION_PATH', '.')
|
CONFIGURATION_PATH = os.getenv('CONFIGURATION_PATH', '.')
|
||||||
DB_PATH = os.path.join(CONFIGURATION_PATH, 'db')
|
DB_PATH = os.path.join(CONFIGURATION_PATH, 'db')
|
||||||
if not os.path.isdir(DB_PATH):
|
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'),
|
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:
|
||||||
|
loggerdbCursor = self.loggerdb.cursor()
|
||||||
|
existingTable = loggerdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
|
||||||
existingTable = [t['name'] for t in existingTable]
|
existingTable = [t['name'] for t in existingTable]
|
||||||
|
|
||||||
if "DashboardLog" not in existingTable:
|
if "DashboardLog" not in existingTable:
|
||||||
self.loggerdbCursor.execute(
|
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))")
|
"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()
|
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:
|
||||||
|
loggerdbCursor = self.loggerdb.cursor()
|
||||||
|
loggerdbCursor.execute(
|
||||||
"INSERT INTO DashboardLog (LogID, URL, IP, Status, Message) VALUES (?, ?, ?, ?, ?)", (str(uuid.uuid4()), URL, IP, Status, Message,))
|
"INSERT INTO DashboardLog (LogID, URL, IP, Status, Message) VALUES (?, ?, ?, ?, ?)", (str(uuid.uuid4()), URL, IP, Status, Message,))
|
||||||
|
if self.loggerdb.in_transaction:
|
||||||
self.loggerdb.commit()
|
self.loggerdb.commit()
|
||||||
return True
|
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:
|
||||||
|
loggerdbCursor = self.loggerdb.cursor()
|
||||||
|
|
||||||
|
existingTable = loggerdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
|
||||||
existingTable = [t['name'] for t in existingTable]
|
existingTable = [t['name'] for t in existingTable]
|
||||||
|
|
||||||
if "JobLog" not in existingTable:
|
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))")
|
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()
|
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:
|
||||||
|
loggerdbCursor = self.loggerdb.cursor()
|
||||||
|
loggerdbCursor.execute(f"INSERT INTO JobLog (LogID, JobID, Status, Message) VALUES (?, ?, ?, ?)",
|
||||||
(str(uuid.uuid4()), JobID, Status, Message,))
|
(str(uuid.uuid4()), JobID, Status, Message,))
|
||||||
|
if self.loggerdb.in_transaction:
|
||||||
self.loggerdb.commit()
|
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,7 +182,9 @@ 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:
|
||||||
|
loggerdbCursor = self.loggerdb.cursor()
|
||||||
|
table = loggerdbCursor.execute(f"SELECT * FROM JobLog WHERE JobID IN ({allJobsID}) ORDER BY LogDate DESC").fetchall()
|
||||||
self.logs.clear()
|
self.logs.clear()
|
||||||
for l in table:
|
for l in table:
|
||||||
logs.append(
|
logs.append(
|
||||||
@@ -217,13 +229,14 @@ 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:
|
||||||
|
jobdbCursor = self.jobdb.cursor()
|
||||||
|
jobs = jobdbCursor.execute("SELECT * FROM PeerJobs WHERE ExpireDate IS NULL").fetchall()
|
||||||
for job in jobs:
|
for job in jobs:
|
||||||
self.Jobs.append(PeerJob(
|
self.Jobs.append(PeerJob(
|
||||||
job['JobID'], job['Configuration'], job['Peer'], job['Field'], job['Operator'], job['Value'],
|
job['JobID'], job['Configuration'], job['Peer'], job['Field'], job['Operator'], job['Value'],
|
||||||
@@ -231,7 +244,9 @@ class PeerJobs:
|
|||||||
|
|
||||||
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:
|
||||||
|
jobdbCursor = self.jobdb.cursor()
|
||||||
|
jobs = jobdbCursor.execute(
|
||||||
f"SELECT * FROM PeerJobs WHERE Configuration = ?", (configuration, )).fetchall()
|
f"SELECT * FROM PeerJobs WHERE Configuration = ?", (configuration, )).fetchall()
|
||||||
j = []
|
j = []
|
||||||
for job in jobs:
|
for job in jobs:
|
||||||
@@ -242,11 +257,14 @@ class PeerJobs:
|
|||||||
return []
|
return []
|
||||||
|
|
||||||
def __createPeerJobsDatabase(self):
|
def __createPeerJobsDatabase(self):
|
||||||
existingTable = self.jobdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
|
with self.jobdb:
|
||||||
|
jobdbCursor = self.jobdb.cursor()
|
||||||
|
|
||||||
|
existingTable = jobdbCursor.execute("SELECT name from sqlite_master where type='table'").fetchall()
|
||||||
existingTable = [t['name'] for t in existingTable]
|
existingTable = [t['name'] for t in existingTable]
|
||||||
|
|
||||||
if "PeerJobs" not in existingTable:
|
if "PeerJobs" not in existingTable:
|
||||||
self.jobdbCursor.execute('''
|
jobdbCursor.execute('''
|
||||||
CREATE TABLE PeerJobs (JobID VARCHAR NOT NULL, Configuration VARCHAR NOT NULL, Peer VARCHAR NOT NULL,
|
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,
|
Field VARCHAR NOT NULL, Operator VARCHAR NOT NULL, Value VARCHAR NOT NULL, CreationDate DATETIME,
|
||||||
ExpireDate DATETIME, Action VARCHAR NOT NULL, PRIMARY KEY (JobID))
|
ExpireDate DATETIME, Action VARCHAR NOT NULL, PRIMARY KEY (JobID))
|
||||||
@@ -261,16 +279,19 @@ 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:
|
||||||
|
with self.jobdb:
|
||||||
|
jobdbCursor = self.jobdb.cursor()
|
||||||
|
|
||||||
if (len(str(Job.CreationDate))) == 0:
|
if (len(str(Job.CreationDate))) == 0:
|
||||||
self.jobdbCursor.execute('''
|
jobdbCursor.execute('''
|
||||||
INSERT INTO PeerJobs VALUES (?, ?, ?, ?, ?, ?, strftime('%Y-%m-%d %H:%M:%S','now'), NULL, ?)
|
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,))
|
''', (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}")
|
JobLogger.log(Job.JobID, Message=f"Job is created if {Job.Field} {Job.Operator} {Job.Value} then {Job.Action}")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
currentJob = self.jobdbCursor.execute('SELECT * FROM PeerJobs WHERE JobID = ?', (Job.JobID, )).fetchone()
|
currentJob = jobdbCursor.execute('SELECT * FROM PeerJobs WHERE JobID = ?', (Job.JobID, )).fetchone()
|
||||||
if currentJob is not None:
|
if currentJob is not None:
|
||||||
self.jobdbCursor.execute('''
|
jobdbCursor.execute('''
|
||||||
UPDATE PeerJobs SET Field = ?, Operator = ?, Value = ?, Action = ? WHERE JobID = ?
|
UPDATE PeerJobs SET Field = ?, Operator = ?, Value = ?, Action = ? WHERE JobID = ?
|
||||||
''', (Job.Field, Job.Operator, Job.Value, Job.Action, Job.JobID))
|
''', (Job.Field, Job.Operator, Job.Value, Job.Action, Job.JobID))
|
||||||
JobLogger.log(Job.JobID,
|
JobLogger.log(Job.JobID,
|
||||||
@@ -288,7 +309,9 @@ 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:
|
||||||
|
jobdbCursor = self.jobdb.cursor()
|
||||||
|
jobdbCursor.execute('''
|
||||||
UPDATE PeerJobs SET ExpireDate = strftime('%Y-%m-%d %H:%M:%S','now') WHERE JobID = ?
|
UPDATE PeerJobs SET ExpireDate = strftime('%Y-%m-%d %H:%M:%S','now') WHERE JobID = ?
|
||||||
''', (Job.JobID,))
|
''', (Job.JobID,))
|
||||||
self.jobdb.commit()
|
self.jobdb.commit()
|
||||||
@@ -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, ""
|
||||||
|
|
||||||
@@ -490,12 +511,13 @@ class WireguardConfiguration:
|
|||||||
# Create tables in database
|
# Create tables in database
|
||||||
self.__createDatabase()
|
self.__createDatabase()
|
||||||
self.getPeersList()
|
self.getPeersList()
|
||||||
|
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,
|
||||||
@@ -508,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,
|
||||||
@@ -524,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,
|
||||||
@@ -535,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,
|
||||||
@@ -550,7 +572,7 @@ class WireguardConfiguration:
|
|||||||
)
|
)
|
||||||
""" % self.Name
|
""" % self.Name
|
||||||
)
|
)
|
||||||
sqldb.commit()
|
# sqldb.commit()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -563,14 +585,14 @@ 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))
|
||||||
|
|
||||||
def __getPeers(self):
|
def __getPeers(self):
|
||||||
|
|
||||||
mt = os.path.getmtime(os.path.join(WG_CONF_PATH, f'{self.Name}.conf'))
|
mt = os.path.getmtime(os.path.join(WG_CONF_PATH, f'{self.Name}.conf'))
|
||||||
if self.__configFileModifiedTime is None or self.__configFileModifiedTime != mt:
|
# if self.__configFileModifiedTime is None or self.__configFileModifiedTime != mt:
|
||||||
self.Peers = []
|
self.Peers = []
|
||||||
with open(os.path.join(WG_CONF_PATH, f'{self.Name}.conf'), 'r') as configFile:
|
with open(os.path.join(WG_CONF_PATH, f'{self.Name}.conf'), 'r') as configFile:
|
||||||
p = []
|
p = []
|
||||||
@@ -599,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 = {
|
||||||
@@ -625,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,
|
||||||
@@ -633,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)}")
|
||||||
@@ -665,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)
|
||||||
@@ -692,11 +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()
|
||||||
numOfRestrictedPeers += 1
|
numOfRestrictedPeers += 1
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
numOfFailedToRestrictPeers += 1
|
numOfFailedToRestrictPeers += 1
|
||||||
@@ -723,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
|
||||||
@@ -799,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:
|
||||||
@@ -814,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,
|
||||||
@@ -824,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],))
|
||||||
@@ -845,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]:
|
||||||
@@ -980,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,
|
||||||
@@ -1033,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:
|
||||||
@@ -1115,15 +1138,17 @@ class DashboardConfig:
|
|||||||
self.__createAPIKeyTable()
|
self.__createAPIKeyTable()
|
||||||
self.DashboardAPIKeys = self.__getAPIKeys()
|
self.DashboardAPIKeys = self.__getAPIKeys()
|
||||||
self.APIAccessed = False
|
self.APIAccessed = False
|
||||||
|
self.SetConfig("Server", "version", DASHBOARD_VERSION)
|
||||||
|
|
||||||
|
|
||||||
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))
|
||||||
@@ -1131,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()
|
||||||
|
|
||||||
|
|
||||||
@@ -1344,6 +1369,14 @@ def _getWireguardConfigurationAvailableIP(configName: str) -> tuple[bool, list[s
|
|||||||
for i in add:
|
for i in add:
|
||||||
a, c = i.split('/')
|
a, c = i.split('/')
|
||||||
existedAddress.append(ipaddress.ip_address(a.replace(" ", "")))
|
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:
|
for i in address:
|
||||||
addressSplit, cidr = i.split('/')
|
addressSplit, cidr = i.split('/')
|
||||||
existedAddress.append(ipaddress.ip_address(addressSplit.replace(" ", "")))
|
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
|
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/*": {
|
||||||
@@ -1419,6 +1463,7 @@ def auth_req():
|
|||||||
and f"{(APP_PREFIX if len(APP_PREFIX) > 0 else '')}" != request.path)
|
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 "validateAuthentication" not in request.path and "authenticate" not in request.path
|
||||||
and "getDashboardConfiguration" not in request.path and "getDashboardTheme" 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 "sharePeer/get" not in request.path
|
||||||
and "isTotpEnabled" 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.")
|
return ResponseObject(False, "Please fill in all required box.")
|
||||||
if not config.getStatus():
|
if not config.getStatus():
|
||||||
config.toggleConfiguration()
|
config.toggleConfiguration()
|
||||||
|
|
||||||
|
availableIps = _getWireguardConfigurationAvailableIP(configName)
|
||||||
|
|
||||||
if bulkAdd:
|
if bulkAdd:
|
||||||
if bulkAddAmount < 1:
|
if bulkAddAmount < 1:
|
||||||
return ResponseObject(False, "Please specify amount of peers you want to add")
|
return ResponseObject(False, "Please specify amount of peers you want to add")
|
||||||
availableIps = _getWireguardConfigurationAvailableIP(configName)
|
|
||||||
if not availableIps[0]:
|
if not availableIps[0]:
|
||||||
return ResponseObject(False, "No more available IP can assign")
|
return ResponseObject(False, "No more available IP can assign")
|
||||||
if bulkAddAmount > len(availableIps[1]):
|
if bulkAddAmount > len(availableIps[1]):
|
||||||
@@ -1788,6 +1836,11 @@ def API_addPeers(configName):
|
|||||||
return ResponseObject(False, f"This peer already exist.")
|
return ResponseObject(False, f"This peer already exist.")
|
||||||
name = data['name']
|
name = data['name']
|
||||||
private_key = data['private_key']
|
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)}])
|
config.addPeers([{"id": public_key, "allowed_ip": ''.join(allowed_ips)}])
|
||||||
# subprocess.check_output(
|
# subprocess.check_output(
|
||||||
# f"wg set {config.Name} peer {public_key} allowed-ips {''.join(allowed_ips)}",
|
# f"wg set {config.Name} peer {public_key} allowed-ips {''.join(allowed_ips)}",
|
||||||
@@ -1857,6 +1910,10 @@ def API_getConfigurationInfo():
|
|||||||
def API_getDashboardTheme():
|
def API_getDashboardTheme():
|
||||||
return ResponseObject(data=DashboardConfig.GetConfig("Server", "dashboard_theme")[1])
|
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"])
|
@app.route(f'{APP_PREFIX}/api/savePeerScheduleJob/', methods=["POST"])
|
||||||
def API_savePeerScheduleJob():
|
def API_savePeerScheduleJob():
|
||||||
@@ -2006,8 +2063,7 @@ def API_traceroute_execute():
|
|||||||
|
|
||||||
@app.route(f'{APP_PREFIX}/api/getDashboardUpdate')
|
@app.route(f'{APP_PREFIX}/api/getDashboardUpdate')
|
||||||
def API_getDashboardUpdate():
|
def API_getDashboardUpdate():
|
||||||
import urllib.request as req;
|
import urllib.request as req
|
||||||
|
|
||||||
try:
|
try:
|
||||||
r = req.urlopen("https://api.github.com/repos/donaldzou/WGDashboard/releases/latest", timeout=5).read()
|
r = req.urlopen("https://api.github.com/repos/donaldzou/WGDashboard/releases/latest", timeout=5).read()
|
||||||
data = dict(json.loads(r))
|
data = dict(json.loads(r))
|
||||||
@@ -2020,8 +2076,8 @@ def API_getDashboardUpdate():
|
|||||||
return ResponseObject(message="You're on the latest version")
|
return ResponseObject(message="You're on the latest version")
|
||||||
return ResponseObject(False)
|
return ResponseObject(False)
|
||||||
|
|
||||||
except urllib.error.HTTPError as e:
|
except urllib.error.HTTPError and urllib.error.URLError as e:
|
||||||
return ResponseObject(False, f"Request to GitHub API failed. Returned a {e.code} status.")
|
return ResponseObject(False, f"Request to GitHub API failed.")
|
||||||
|
|
||||||
'''
|
'''
|
||||||
Sign Up
|
Sign Up
|
||||||
@@ -2102,6 +2158,7 @@ def backGroundThread():
|
|||||||
c.getPeersLatestHandshake()
|
c.getPeersLatestHandshake()
|
||||||
c.getPeersEndpoint()
|
c.getPeersEndpoint()
|
||||||
c.getPeersList()
|
c.getPeersList()
|
||||||
|
c.getRestrictedPeersList()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[WGDashboard] Background Thread #1 Error: {str(e)}", flush=True)
|
print(f"[WGDashboard] Background Thread #1 Error: {str(e)}", flush=True)
|
||||||
time.sleep(10)
|
time.sleep(10)
|
||||||
|
|||||||
Vendored
BIN
Binary file not shown.
|
Before Width: | Height: | Size: 3.2 MiB |
Vendored
+2
-2
File diff suppressed because one or more lines are too long
Vendored
+16
-16
File diff suppressed because one or more lines are too long
Vendored
BIN
Binary file not shown.
|
Before Width: | Height: | Size: 4.5 MiB |
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
"name": "app",
|
"name": "app",
|
||||||
"version": "4.0.0",
|
"version": "4.0.2",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "vite build",
|
"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"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
+4
-4
@@ -36,8 +36,11 @@ export default {
|
|||||||
addAllowedIp(ip){
|
addAllowedIp(ip){
|
||||||
if(this.store.checkCIDR(ip)){
|
if(this.store.checkCIDR(ip)){
|
||||||
this.data.allowed_ips.push(ip);
|
this.data.allowed_ips.push(ip);
|
||||||
|
this.customAvailableIp = ''
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
this.allowedIpFormatError = true;
|
||||||
|
this.dashboardStore.newMessage('WGDashboard', 'Allowed IP is invalid', 'danger')
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -80,10 +83,7 @@ export default {
|
|||||||
:disabled="bulk">
|
:disabled="bulk">
|
||||||
<button class="btn btn-outline-success btn-sm rounded-end-3"
|
<button class="btn btn-outline-success btn-sm rounded-end-3"
|
||||||
:disabled="bulk || !this.customAvailableIp"
|
:disabled="bulk || !this.customAvailableIp"
|
||||||
@click="this.addAllowedIp(this.customAvailableIp)
|
@click="this.addAllowedIp(this.customAvailableIp)"
|
||||||
? this.customAvailableIp = '' :
|
|
||||||
this.allowedIpFormatError = true;
|
|
||||||
this.dashboardStore.newMessage('WGDashboard', 'Allowed IP is invalid', 'danger')"
|
|
||||||
type="button" id="button-addon2">
|
type="button" id="button-addon2">
|
||||||
<i class="bi bi-plus-lg"></i>
|
<i class="bi bi-plus-lg"></i>
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -200,7 +200,8 @@ export default {
|
|||||||
})
|
})
|
||||||
this.loading = false;
|
this.loading = false;
|
||||||
if (this.configurationPeers.length > 0){
|
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);
|
const receive = this.configurationPeers.map(x => x.total_receive + x.cumu_receive).reduce((x,y) => x + y).toFixed(4);
|
||||||
if (
|
if (
|
||||||
this.historyDataSentDifference[this.historyDataSentDifference.length - 1] !== sent
|
this.historyDataSentDifference[this.historyDataSentDifference.length - 1] !== sent
|
||||||
@@ -259,13 +260,13 @@ export default {
|
|||||||
connectedPeers: this.configurationPeers.filter(x => x.status === "running").length,
|
connectedPeers: this.configurationPeers.filter(x => x.status === "running").length,
|
||||||
totalUsage: this.configurationPeers.length > 0 ?
|
totalUsage: this.configurationPeers.length > 0 ?
|
||||||
this.configurationPeers.filter(x => !x.restricted)
|
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 ?
|
totalReceive: this.configurationPeers.length > 0 ?
|
||||||
this.configurationPeers.filter(x => !x.restricted)
|
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 ?
|
totalSent: this.configurationPeers.length > 0 ?
|
||||||
this.configurationPeers.filter(x => !x.restricted)
|
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
|
return k
|
||||||
|
|||||||
@@ -11,16 +11,22 @@ export default {
|
|||||||
const store = DashboardConfigurationStore()
|
const store = DashboardConfigurationStore()
|
||||||
let theme = "dark"
|
let theme = "dark"
|
||||||
let totpEnabled = false;
|
let totpEnabled = false;
|
||||||
|
let version = undefined;
|
||||||
if (!store.IsElectronApp){
|
if (!store.IsElectronApp){
|
||||||
await fetchGet("/api/getDashboardTheme", {}, (res) => {
|
await Promise.all([
|
||||||
|
fetchGet("/api/getDashboardTheme", {}, (res) => {
|
||||||
theme = res.data
|
theme = res.data
|
||||||
});
|
}),
|
||||||
await fetchGet("/api/isTotpEnabled", {}, (res) => {
|
fetchGet("/api/isTotpEnabled", {}, (res) => {
|
||||||
totpEnabled = res.data
|
totpEnabled = res.data
|
||||||
});
|
}),
|
||||||
|
fetchGet("/api/getDashboardVersion", {}, (res) => {
|
||||||
|
version = res.data
|
||||||
|
})
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
store.removeActiveCrossServer();
|
store.removeActiveCrossServer();
|
||||||
return {store, theme, totpEnabled}
|
return {store, theme, totpEnabled, version}
|
||||||
},
|
},
|
||||||
data(){
|
data(){
|
||||||
return {
|
return {
|
||||||
@@ -146,7 +152,7 @@ export default {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<small class="text-muted pb-3 d-block w-100 text-center mt-3">
|
<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>
|
<a href="https://github.com/donaldzou" target="_blank"><strong>Donald Zou</strong></a>
|
||||||
</small>
|
</small>
|
||||||
<div class="messageCentre text-body position-absolute end-0 m-3">
|
<div class="messageCentre text-body position-absolute end-0 m-3">
|
||||||
|
|||||||
+17
-3
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
# wgd.sh - Copyright(C) 2024 Donald Zou [https://github.com/donaldzou]
|
# wgd.sh - Copyright(C) 2024 Donald Zou [https://github.com/donaldzou]
|
||||||
# Under Apache-2.0 License
|
# Under Apache-2.0 License
|
||||||
trap "kill $TOP_PID"
|
#trap "kill $TOP_PID"
|
||||||
export TOP_PID=$$
|
export TOP_PID=$$
|
||||||
|
|
||||||
app_name="dashboard.py"
|
app_name="dashboard.py"
|
||||||
@@ -337,7 +337,21 @@ start_wgd_debug() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
update_wgd() {
|
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'])")
|
|
||||||
|
_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 "%s\n" "$dashes"
|
||||||
printf "[WGDashboard] Are you sure you want to update to the %s? (Y/N): " "$new_ver"
|
printf "[WGDashboard] Are you sure you want to update to the %s? (Y/N): " "$new_ver"
|
||||||
read up
|
read up
|
||||||
@@ -356,7 +370,7 @@ update_wgd() {
|
|||||||
rm wgd.sh.old
|
rm wgd.sh.old
|
||||||
else
|
else
|
||||||
printf "%s\n" "$dashes"
|
printf "%s\n" "$dashes"
|
||||||
printf "| Update Canceled. |\n"
|
printf "[WGDashboard] Update Canceled.\n"
|
||||||
printf "%s\n" "$dashes"
|
printf "%s\n" "$dashes"
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user