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

Peer Sharing is done :)

This commit is contained in:
Donald Zou 2024-08-07 00:37:05 -04:00
parent 7463767781
commit fa2d7fa3da
3 changed files with 147 additions and 9 deletions

View File

@ -122,12 +122,14 @@ class DashboardLogger:
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("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.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() 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("INSERT INTO DashboardLog (LogID, URL, IP, Status, Message) VALUES (?, ?, ?, ?, ?)", (str(uuid.uuid4()), URL, IP, Status, Message,)) self.loggerdbCursor.execute(
"INSERT INTO DashboardLog (LogID, URL, IP, Status, Message) VALUES (?, ?, ?, ?, ?)", (str(uuid.uuid4()), URL, IP, Status, Message,))
self.loggerdb.commit() self.loggerdb.commit()
return True return True
except Exception as e: except Exception as e:
@ -308,7 +310,7 @@ class PeerJobs:
y: float = float(job.Value) y: float = float(job.Value)
else: else:
x: datetime = datetime.now() x: datetime = datetime.now()
y: datetime = datetime.strptime(job.Value, "%Y-%m-%dT%H:%M") y: datetime = datetime.strptime(job.Value, "%Y-%m-%d %H:%M:%S")
runAction: bool = self.__runJob_Compare(x, y, job.Operator) runAction: bool = self.__runJob_Compare(x, y, job.Operator)
if runAction: if runAction:
s = False s = False
@ -393,10 +395,6 @@ class PeerShareLinks:
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, )) self.PeerShareLinkCursor.execute("UPDATE PeerShareLinks SET ExpireDate = datetime('now', 'localtime') WHERE Configuration = ? AND Peer = ?", (Configuration, Peer, ))
# if ExpireDate is not None:
# ExpireDate = datetime.strptime(ExpireDate, '%Y-%m-%d %H:%M:%S')
self.PeerShareLinkCursor.execute("INSERT INTO PeerShareLinks (ShareID, Configuration, Peer, ExpireDate) VALUES (?, ?, ?, ?)", (newShareID, Configuration, Peer, ExpireDate, )) self.PeerShareLinkCursor.execute("INSERT INTO PeerShareLinks (ShareID, Configuration, Peer, ExpireDate) VALUES (?, ?, ?, ?)", (newShareID, Configuration, Peer, ExpireDate, ))
sqldb.commit() sqldb.commit()
self.__getSharedLinks() self.__getSharedLinks()
@ -1347,6 +1345,7 @@ def auth_req():
if ('/static/' not in request.path and "username" not in session and "/" != request.path if ('/static/' not in request.path and "username" not in session and "/" != 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 "sharePeer/get" not in request.path
and "isTotpEnabled" not in request.path and "isTotpEnabled" not in request.path
): ):
response = Flask.make_response(app, { response = Flask.make_response(app, {
@ -1606,6 +1605,27 @@ def API_sharePeer_update():
return ResponseObject(status, message) return ResponseObject(status, message)
return ResponseObject(data=AllPeerShareLinks.getLinkByID(ShareID)) return ResponseObject(data=AllPeerShareLinks.getLinkByID(ShareID))
@app.route('/api/sharePeer/get', methods=['GET'])
def API_sharePeer_get():
data = request.args
ShareID = data.get("ShareID")
if ShareID is None or len(ShareID) == 0:
return ResponseObject(False, "Please provide ShareID")
link = AllPeerShareLinks.getLinkByID(ShareID)
if len(link) == 0:
return ResponseObject(False, "This link is either expired to invalid")
l = link[0]
if l.Configuration not in WireguardConfigurations.keys():
return ResponseObject(False, "The peer you're looking for does not exist")
c = WireguardConfigurations.get(l.Configuration)
fp, p = c.searchPeer(l.Peer)
if not fp:
return ResponseObject(False, "The peer you're looking for does not exist")
return ResponseObject(data=p.downloadPeer())
@app.route('/api/allowAccessPeers/<configName>', methods=['POST']) @app.route('/api/allowAccessPeers/<configName>', methods=['POST'])
def API_allowAccessPeers(configName: str) -> ResponseObject: def API_allowAccessPeers(configName: str) -> ResponseObject:
data = request.get_json() data = request.get_json()

View File

@ -15,6 +15,7 @@ import PeerCreate from "@/components/configurationComponents/peerCreate.vue";
import Ping from "@/views/ping.vue"; import Ping from "@/views/ping.vue";
import Traceroute from "@/views/traceroute.vue"; import Traceroute from "@/views/traceroute.vue";
import Totp from "@/components/setupComponent/totp.vue"; import Totp from "@/components/setupComponent/totp.vue";
import Share from "@/views/share.vue";
const checkAuth = async () => { const checkAuth = async () => {
let result = false let result = false
@ -102,14 +103,22 @@ const router = createRouter({
{ {
path: '/welcome', component: Setup, path: '/welcome', component: Setup,
meta: { meta: {
requiresAuth: true requiresAuth: true,
title: "Welcome to WGDashboard"
}, },
}, },
{ {
path: '/2FASetup', component: Totp, path: '/2FASetup', component: Totp,
meta: { meta: {
requiresAuth: true requiresAuth: true,
title: "Multi-Factor Authentication Setup"
}, },
},
{
path: '/share', component: Share,
meta: {
title: "Share"
}
} }
] ]
}); });

View File

@ -0,0 +1,109 @@
<script>
import {useRoute} from "vue-router";
import {DashboardConfigurationStore} from "@/stores/DashboardConfigurationStore.js";
import {fetchGet} from "@/utilities/fetch.js";
import {ref} from "vue";
import QRCode from "qrcode";
export default {
name: "share",
async setup(){
const route = useRoute();
const loaded = ref(false)
const store = DashboardConfigurationStore();
const theme = ref("");
const peerConfiguration = ref("");
const blob = ref(new Blob())
await fetchGet("/api/getDashboardTheme", {}, (res) => {
theme.value = res.data
});
const id = route.query.ShareID
if(id === undefined || id.length === 0){
peerConfiguration.value = undefined
loaded.value = true;
}else{
await fetchGet("/api/sharePeer/get", {
ShareID: id
}, (res) => {
if (res.status){
peerConfiguration.value = res.data;
blob.value = new Blob([peerConfiguration.value.file], { type: "text/plain" });
}else{
peerConfiguration.value = undefined
}
loaded.value = true;
})
}
return {store, theme, peerConfiguration, blob}
},
mounted() {
QRCode.toCanvas(document.querySelector("#qrcode"), this.peerConfiguration.file , (error) => {
if (error) console.error(error)
})
},
methods:{
download(){
const blob = new Blob([this.peerConfiguration.file], { type: "text/plain" });
const jsonObjectUrl = URL.createObjectURL(blob);
const filename = `${this.peerConfiguration.fileName}.conf`;
const anchorEl = document.createElement("a");
anchorEl.href = jsonObjectUrl;
anchorEl.download = filename;
anchorEl.click();
}
},
computed:{
getBlob(){
return URL.createObjectURL(this.blob)
}
}
}
</script>
<template>
<div class="container-fluid login-container-fluid d-flex main pt-5 overflow-scroll"
:data-bs-theme="this.theme">
<div class="m-auto text-body" style="width: 500px">
<div class="text-center position-relative" style=""
v-if="!this.peerConfiguration">
<div class="animate__animated animate__fadeInUp">
<h1 style="font-size: 20rem; filter: blur(1rem); animation-duration: 7s"
class="animate__animated animate__flash animate__infinite">
<i class="bi bi-file-binary"></i>
</h1>
</div>
<div class="position-absolute w-100 h-100 top-0 start-0 d-flex animate__animated animate__fadeInUp"
style="animation-delay: 0.1s;"
>
<h3 class="m-auto">Oh no... This link is either expired or invalid.</h3>
</div>
</div>
<div v-else class="d-flex align-items-center flex-column gap-3">
<div class="h1 dashboardLogo text-center animate__animated animate__fadeInUp">
<h6>WGDashboard</h6>
Scan QR Code from the WireGuard App
</div>
<canvas id="qrcode" class="rounded-3 shadow animate__animated animate__fadeInUp mb-3" ref="qrcode"></canvas>
<p class="text-muted animate__animated animate__fadeInUp mb-1"
style="animation-delay: 0.2s;"
>or click the button below to download the <samp>.conf</samp> file</p>
<a
:download="this.peerConfiguration.fileName + '.conf'"
:href="getBlob"
class="btn btn-lg bg-primary-subtle text-primary-emphasis border-1 border-primary-subtle animate__animated animate__fadeInUp shadow-sm"
style="animation-delay: 0.25s;"
>
<i class="bi bi-download"></i>
</a>
</div>
</div>
</div>
</template>
<style scoped>
.animate__fadeInUp{
animation-timing-function: cubic-bezier(0.42, 0, 0.22, 1.0)
}
</style>