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

Redirect when received a 401 error

This commit is contained in:
Donald Zou 2024-08-04 01:31:31 -04:00
parent 6825d728c2
commit 6cf4eba20a
6 changed files with 85 additions and 63 deletions

View File

@ -293,7 +293,6 @@ class PeerJobs:
def runJob(self): def runJob(self):
needToDelete = [] needToDelete = []
for job in self.Jobs: for job in self.Jobs:
print(job.toJson())
c = WireguardConfigurations.get(job.Configuration) c = WireguardConfigurations.get(job.Configuration)
if c is not None: if c is not None:
f, fp = c.searchPeer(job.Peer) f, fp = c.searchPeer(job.Peer)
@ -305,10 +304,7 @@ class PeerJobs:
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-%dT%H:%M")
runAction: bool = self.__runJob_Compare(x, y, job.Operator) runAction: bool = self.__runJob_Compare(x, y, job.Operator)
print("Running Job:" + str(runAction) + "\n")
if runAction: if runAction:
s = False s = False
if job.Action == "restrict": if job.Action == "restrict":
@ -325,7 +321,6 @@ class PeerJobs:
JobLogger.log(job.JobID, s["status"], JobLogger.log(job.JobID, s["status"],
f"Peer {fp.id} from {c.Name} failed {job.Action}ed." f"Peer {fp.id} from {c.Name} failed {job.Action}ed."
) )
print(f'''[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] Peer Job Schedule: Ran {len(needToDelete)} job(s)''')
for j in needToDelete: for j in needToDelete:
self.deleteJob(j) self.deleteJob(j)
@ -1322,9 +1317,7 @@ def API_SignOut():
@app.route('/api/getWireguardConfigurations', methods=["GET"]) @app.route('/api/getWireguardConfigurations', methods=["GET"])
def API_getWireguardConfigurations(): def API_getWireguardConfigurations():
# WireguardConfigurations = _getConfigurationList() WireguardConfigurations = _getConfigurationList()
print("in request::::")
print(list(WireguardConfigurations.keys()))
return ResponseObject(data=[wc for wc in WireguardConfigurations.values()]) return ResponseObject(data=[wc for wc in WireguardConfigurations.values()])
@ -1847,8 +1840,8 @@ def index():
def backGroundThread(): def backGroundThread():
with app.app_context(): with app.app_context():
print("Waiting 5 sec") print(f"[WGDashboard][{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Background Thread #1 Started")
time.sleep(5) time.sleep(10)
while True: while True:
for c in WireguardConfigurations.values(): for c in WireguardConfigurations.values():
if c.getStatus(): if c.getStatus():
@ -1857,18 +1850,17 @@ def backGroundThread():
c.getPeersLatestHandshake() c.getPeersLatestHandshake()
c.getPeersEndpoint() c.getPeersEndpoint()
except Exception as e: except Exception as e:
print("Error: " + str(e)) print(f"[WGDashboard][{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Background Thread #1 Error: {str(e)}")
time.sleep(10) time.sleep(10)
def peerJobScheduleBackgroundThread(): def peerJobScheduleBackgroundThread():
with app.app_context(): with app.app_context():
print(f'''[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] Peer Job Schedule: Waiting for 10 Seconds''') print(f"[WGDashboard][{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Background Thread #2 Started")
time.sleep(10) time.sleep(10)
while True: while True:
print(f'''[{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}] Peer Job Schedule: Running''')
AllPeerJobs.runJob() AllPeerJobs.runJob()
time.sleep(10) time.sleep(180)
def gunicornConfig(): def gunicornConfig():

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -4,20 +4,16 @@ import Index from "@/views/index.vue"
import Signin from "@/views/signin.vue"; import Signin from "@/views/signin.vue";
import ConfigurationList from "@/components/configurationList.vue"; import ConfigurationList from "@/components/configurationList.vue";
import {fetchGet} from "@/utilities/fetch.js"; import {fetchGet} from "@/utilities/fetch.js";
import {wgdashboardStore} from "@/stores/wgdashboardStore.js";
import Settings from "@/views/settings.vue"; import Settings from "@/views/settings.vue";
import {WireguardConfigurationsStore} from "@/stores/WireguardConfigurationsStore.js"; import {WireguardConfigurationsStore} from "@/stores/WireguardConfigurationsStore.js";
import {DashboardConfigurationStore} from "@/stores/DashboardConfigurationStore.js"; import {DashboardConfigurationStore} from "@/stores/DashboardConfigurationStore.js";
import Setup from "@/views/setup.vue"; import Setup from "@/views/setup.vue";
import NewConfiguration from "@/views/newConfiguration.vue"; import NewConfiguration from "@/views/newConfiguration.vue";
import Configuration from "@/views/configuration.vue"; import Configuration from "@/views/configuration.vue";
import PeerSettings from "@/components/configurationComponents/peerSettings.vue";
import PeerList from "@/components/configurationComponents/peerList.vue"; import PeerList from "@/components/configurationComponents/peerList.vue";
import PeerCreate from "@/components/configurationComponents/peerCreate.vue"; import PeerCreate from "@/components/configurationComponents/peerCreate.vue";
import RestrictedPeers from "@/components/configurationComponents/restrictedPeers.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 PeerJobs from "@/components/configurationComponents/peerJobs.vue";
const checkAuth = async () => { const checkAuth = async () => {
let result = false let result = false
@ -30,6 +26,7 @@ const checkAuth = async () => {
const router = createRouter({ const router = createRouter({
history: createWebHashHistory(), history: createWebHashHistory(),
routes: [ routes: [
{ {
name: "Index", name: "Index",
path: '/', path: '/',
@ -90,7 +87,6 @@ const router = createRouter({
path: 'create', path: 'create',
component: PeerCreate component: PeerCreate
}, },
] ]
}, },
@ -136,9 +132,10 @@ router.beforeEach(async (to, from, next) => {
}else{ }else{
dashboardConfigurationStore.Redirect = to; dashboardConfigurationStore.Redirect = to;
next("/signin") next("/signin")
dashboardConfigurationStore.newMessage("WGDashboard", "Session Ended", "warning")
} }
}else { }else {
next(); next();
} }
}); });
export default router export default router

View File

@ -1,3 +1,5 @@
import router from "@/router/index.js";
import {DashboardConfigurationStore} from "@/stores/DashboardConfigurationStore.js";
export const fetchGet = async (url, params=undefined, callback=undefined) => { export const fetchGet = async (url, params=undefined, callback=undefined) => {
const urlSearchParams = new URLSearchParams(params); const urlSearchParams = new URLSearchParams(params);
await fetch(`${url}?${urlSearchParams.toString()}`, { await fetch(`${url}?${urlSearchParams.toString()}`, {
@ -5,14 +7,22 @@ export const fetchGet = async (url, params=undefined, callback=undefined) => {
"content-type": "application/json" "content-type": "application/json"
} }
}) })
.then(x => x.json()) .then((x) => {
.then(x => callback ? callback(x) : undefined) const store = DashboardConfigurationStore();
.catch(x => { if (!x.ok){
// let router = useRouter() if (x.status !== 200){
// if (x.status === 401){ if (x.status === 401){
// router.push('/signin') router.push({path: '/signin'})
// } store.newMessage("WGDashboard", "Session Ended", "warning")
}) }
throw new Error(x.statusText)
}
}else{
return x.json()
}
}).then(x => callback ? callback(x) : undefined).catch(x => {
console.log(x)
})
} }
export const fetchPost = async (url, body, callback) => { export const fetchPost = async (url, body, callback) => {
@ -22,10 +32,20 @@ export const fetchPost = async (url, body, callback) => {
}, },
method: "POST", method: "POST",
body: JSON.stringify(body) body: JSON.stringify(body)
}).then((x) => {
const store = DashboardConfigurationStore();
if (!x.ok){
if (x.status !== 200){
if (x.status === 401){
router.push({path: '/signin'})
store.newMessage("WGDashboard", "Session Ended", "warning")
}
throw new Error(x.statusText)
}
}else{
return x.json()
}
}).then(x => callback ? callback(x) : undefined).catch(x => {
console.log(x)
}) })
.then(x => x.json())
.then(x => callback ? callback(x) : undefined)
// .catch(() => {
// alert("Error occurred! Check console")
// });
} }

View File

@ -1,9 +1,11 @@
<script> <script>
import {fetchGet, fetchPost} from "../utilities/fetch.js"; import {fetchGet, fetchPost} from "../utilities/fetch.js";
import {DashboardConfigurationStore} from "@/stores/DashboardConfigurationStore.js"; import {DashboardConfigurationStore} from "@/stores/DashboardConfigurationStore.js";
import Message from "@/components/messageCentreComponent/message.vue";
export default { export default {
name: "signin", name: "signin",
components: {Message},
async setup(){ async setup(){
const store = DashboardConfigurationStore() const store = DashboardConfigurationStore()
let theme = "" let theme = ""
@ -26,6 +28,11 @@ export default {
loading: false loading: false
} }
}, },
computed: {
getMessages(){
return this.store.Messages.filter(x => x.show)
}
},
methods: { methods: {
async auth(){ async auth(){
if (this.username && this.password && ((this.totpEnabled && this.totp) || !this.totpEnabled)){ if (this.username && this.password && ((this.totpEnabled && this.totp) || !this.totpEnabled)){
@ -125,6 +132,12 @@ export default {
WGDashboard v4.0 | Developed with by WGDashboard v4.0 | 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 margin-3">
<TransitionGroup name="message" tag="div" class="position-relative">
<Message v-for="m in getMessages.slice().reverse()"
:message="m" :key="m.id"></Message>
</TransitionGroup>
</div>
</div> </div>
</template> </template>