mirror of
https://github.com/donaldzou/WGDashboard.git
synced 2025-10-04 00:06:18 +00:00
Webhooks feature is done #669
This commit is contained in:
@@ -8,12 +8,14 @@ from .AmneziaWGPeer import AmneziaWGPeer
|
||||
from .PeerShareLinks import PeerShareLinks
|
||||
from .Utilities import RegexMatch
|
||||
from .WireguardConfiguration import WireguardConfiguration
|
||||
from .DashboardWebHooks import DashboardWebHooks
|
||||
|
||||
|
||||
class AmneziaWireguardConfiguration(WireguardConfiguration):
|
||||
def __init__(self, DashboardConfig,
|
||||
AllPeerJobs: PeerJobs,
|
||||
AllPeerShareLinks: PeerShareLinks,
|
||||
DashboardWebHooks: DashboardWebHooks,
|
||||
name: str = None, data: dict = None, backup: dict = None, startup: bool = False):
|
||||
self.Jc = 0
|
||||
self.Jmin = 0
|
||||
@@ -25,7 +27,7 @@ class AmneziaWireguardConfiguration(WireguardConfiguration):
|
||||
self.H3 = 3
|
||||
self.H4 = 4
|
||||
|
||||
super().__init__(DashboardConfig, AllPeerJobs, AllPeerShareLinks, name, data, backup, startup, wg=False)
|
||||
super().__init__(DashboardConfig, AllPeerJobs, AllPeerShareLinks, DashboardWebHooks, name, data, backup, startup, wg=False)
|
||||
|
||||
def toJson(self):
|
||||
self.Status = self.getStatus()
|
||||
@@ -301,6 +303,10 @@ class AmneziaWireguardConfiguration(WireguardConfiguration):
|
||||
p = self.searchPeer(p['id'])
|
||||
if p[0]:
|
||||
result['peers'].append(p[1])
|
||||
self.DashboardWebHooks.RunWebHook("peer_created", {
|
||||
"configuration": self.Name,
|
||||
"peers": list(map(lambda k : k['id'], peers))
|
||||
})
|
||||
return True, result
|
||||
except Exception as e:
|
||||
result['message'] = str(e)
|
||||
|
@@ -168,19 +168,23 @@ class DashboardWebHooks:
|
||||
return False, str(e)
|
||||
return True, None
|
||||
|
||||
def RunWebHook(self, action: str, data: dict[str, str]):
|
||||
if action not in WebHookActions:
|
||||
return False
|
||||
self.__getWebHooks()
|
||||
subscribedWebHooks = filter(lambda webhook: action in webhook.SubscribedActions, self.WebHooks)
|
||||
data['action'] = action
|
||||
for i in subscribedWebHooks:
|
||||
try:
|
||||
t = threading.Thread(target=WebHookSession, args=(i,data), daemon=True)
|
||||
t.start()
|
||||
print("Spinning threads...")
|
||||
except Exception as e:
|
||||
pass
|
||||
def RunWebHook(self, action: str, data):
|
||||
try:
|
||||
if action not in WebHookActions:
|
||||
return False
|
||||
self.__getWebHooks()
|
||||
subscribedWebHooks = filter(lambda webhook: action in webhook.SubscribedActions, self.WebHooks)
|
||||
data['action'] = action
|
||||
for i in subscribedWebHooks:
|
||||
try:
|
||||
ws = WebHookSession(i, data)
|
||||
t = threading.Thread(target=ws.Execute, daemon=True)
|
||||
t.start()
|
||||
print("Spinning threads...")
|
||||
except Exception as e:
|
||||
print(e)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
return True
|
||||
|
||||
class WebHookSession:
|
||||
@@ -197,7 +201,6 @@ class WebHookSession:
|
||||
data['webhook_session'] = self.sessionID
|
||||
self.data = data
|
||||
self.Prepare()
|
||||
self.Execute(data)
|
||||
|
||||
def Prepare(self):
|
||||
with self.engine.begin() as conn:
|
||||
@@ -235,7 +238,7 @@ class WebHookSession:
|
||||
)
|
||||
)
|
||||
|
||||
def Execute(self, data: dict[str, str]):
|
||||
def Execute(self):
|
||||
success = False
|
||||
|
||||
for i in range(5):
|
||||
@@ -247,15 +250,15 @@ class WebHookSession:
|
||||
headerDictionary[header['key']] = header['value']
|
||||
|
||||
if self.webHook.ContentType == "application/json":
|
||||
reqData = json.dumps(data)
|
||||
reqData = json.dumps(self.data)
|
||||
else:
|
||||
for (key, val) in data.items():
|
||||
if type(data[key]) not in [str, int]:
|
||||
data[key] = json.dumps(data[key])
|
||||
reqData = urllib.parse.urlencode(data)
|
||||
for (key, val) in self.data.items():
|
||||
if type(self.data[key]) not in [str, int]:
|
||||
self.data[key] = json.dumps(self.data[key])
|
||||
reqData = urllib.parse.urlencode(self.data)
|
||||
try:
|
||||
req = requests.post(
|
||||
self.webHook.PayloadURL, headers=headerDictionary, timeout=10, data=reqData
|
||||
self.webHook.PayloadURL, headers=headerDictionary, timeout=10, data=reqData, verify=self.webHook.VerifySSL
|
||||
)
|
||||
req.raise_for_status()
|
||||
success = True
|
||||
|
@@ -11,12 +11,14 @@ from itertools import islice
|
||||
|
||||
from .ConnectionString import ConnectionString
|
||||
from .DashboardConfig import DashboardConfig
|
||||
from .DashboardWebHooks import DashboardWebHooks
|
||||
from .Peer import Peer
|
||||
from .PeerJobs import PeerJobs
|
||||
from .PeerShareLinks import PeerShareLinks
|
||||
from .Utilities import StringToBoolean, GenerateWireguardPublicKey, RegexMatch, ValidateDNSAddress, \
|
||||
ValidateEndpointAllowedIPs
|
||||
from .WireguardConfigurationInfo import WireguardConfigurationInfo, PeerGroupsClass
|
||||
from .DashboardWebHooks import DashboardWebHooks
|
||||
|
||||
|
||||
class WireguardConfiguration:
|
||||
@@ -30,6 +32,7 @@ class WireguardConfiguration:
|
||||
def __init__(self, DashboardConfig: DashboardConfig,
|
||||
AllPeerJobs: PeerJobs,
|
||||
AllPeerShareLinks: PeerShareLinks,
|
||||
DashboardWebHooks: DashboardWebHooks,
|
||||
name: str = None,
|
||||
data: dict = None,
|
||||
backup: dict = None,
|
||||
@@ -61,6 +64,7 @@ class WireguardConfiguration:
|
||||
self.AllPeerJobs = AllPeerJobs
|
||||
self.DashboardConfig = DashboardConfig
|
||||
self.AllPeerShareLinks = AllPeerShareLinks
|
||||
self.DashboardWebHooks = DashboardWebHooks
|
||||
self.configPath = os.path.join(self.__getProtocolPath(), f'{self.Name}.conf')
|
||||
self.engine: sqlalchemy.engine = sqlalchemy.create_engine(ConnectionString("wgdashboard"))
|
||||
self.metadata: sqlalchemy.MetaData = sqlalchemy.MetaData()
|
||||
@@ -497,6 +501,10 @@ class WireguardConfiguration:
|
||||
p = self.searchPeer(p['id'])
|
||||
if p[0]:
|
||||
result['peers'].append(p[1])
|
||||
self.DashboardWebHooks.RunWebHook("peer_created", {
|
||||
"configuration": self.Name,
|
||||
"peers": list(map(lambda k : k['id'], peers))
|
||||
})
|
||||
return True, result
|
||||
except Exception as e:
|
||||
result['message'] = str(e)
|
||||
@@ -598,6 +606,7 @@ class WireguardConfiguration:
|
||||
def deletePeers(self, listOfPublicKeys, AllPeerJobs: PeerJobs, AllPeerShareLinks: PeerShareLinks) -> tuple[bool, str]:
|
||||
numOfDeletedPeers = 0
|
||||
numOfFailedToDeletePeers = 0
|
||||
deleted = []
|
||||
if not self.getStatus():
|
||||
self.toggleConfiguration()
|
||||
with self.engine.begin() as conn:
|
||||
@@ -616,6 +625,7 @@ class WireguardConfiguration:
|
||||
self.peersTable.columns.id == pf.id
|
||||
)
|
||||
)
|
||||
deleted.append(pf.id)
|
||||
numOfDeletedPeers += 1
|
||||
except Exception as e:
|
||||
numOfFailedToDeletePeers += 1
|
||||
@@ -624,12 +634,17 @@ class WireguardConfiguration:
|
||||
return False, "Failed to save configuration through WireGuard"
|
||||
|
||||
self.getPeers()
|
||||
|
||||
|
||||
if numOfDeletedPeers == 0 and numOfFailedToDeletePeers == 0:
|
||||
return False, "No peer(s) to delete found"
|
||||
|
||||
|
||||
if numOfDeletedPeers == len(listOfPublicKeys):
|
||||
self.DashboardWebHooks.RunWebHook("peer_deleted", {
|
||||
"configuration": self.Name,
|
||||
"peers": deleted
|
||||
})
|
||||
return True, f"Deleted {numOfDeletedPeers} peer(s)"
|
||||
|
||||
return False, f"Deleted {numOfDeletedPeers} peer(s) successfully. Failed to delete {numOfFailedToDeletePeers} peer(s)"
|
||||
|
||||
def __wgSave(self) -> tuple[bool, str] | tuple[bool, None]:
|
||||
|
Reference in New Issue
Block a user