UI review, stage 3: cleanup, shared chart code, confirmations, routing
useTrafficChart composable replaces the duplicated chart code in Analytics and HistoryModal; theme observer is released on unmount; blob URLs are revoked. ConfirmModal gets a unique id; confirm() in Server/PKI and SweetAlert2 in Account are replaced by ConfirmModal and toasts, sweetalert2 and sass removed. Separate authApiClient for /api/auth. 404 redirect, lazy Clients, token-based isAuthenticated, theme from prefers-color-scheme set before mount. BaseModal reactive size, NewClientModal name check and focus on opened, HistoryModal ignores stale answers. Login.vue.bak, the dead global axios interceptor and empty <p> removed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
600119cdd1
commit
897c82ab88
23 files changed
+427
-707
No files matched your search
Generated
+62
-14
@@ -13,8 +13,6 @@
|
||||
"bootstrap": "^5.3.8",
|
||||
"chart.js": "^4.5.1",
|
||||
"qrcode.vue": "^3.6.0",
|
||||
"sass": "^1.97.2",
|
||||
"sweetalert2": "^11.26.17",
|
||||
"vue": "^3.5.24",
|
||||
"vue-router": "^4.6.4"
|
||||
},
|
||||
@@ -537,9 +535,11 @@
|
||||
"version": "2.5.1",
|
||||
"resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.5.1.tgz",
|
||||
"integrity": "sha512-dfUnCxiN9H4ap84DvD2ubjw+3vUNpstxa0TneY/Paat8a3R4uQZDLSvWjmznAY/DoahqTHl9V46HF/Zs3F29pg==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"detect-libc": "^1.0.3",
|
||||
"is-glob": "^4.0.3",
|
||||
@@ -576,11 +576,13 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"android"
|
||||
],
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 10.0.0"
|
||||
},
|
||||
@@ -596,11 +598,13 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 10.0.0"
|
||||
},
|
||||
@@ -616,11 +620,13 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 10.0.0"
|
||||
},
|
||||
@@ -636,11 +642,13 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"freebsd"
|
||||
],
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 10.0.0"
|
||||
},
|
||||
@@ -656,11 +664,13 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 10.0.0"
|
||||
},
|
||||
@@ -676,11 +686,13 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 10.0.0"
|
||||
},
|
||||
@@ -696,11 +708,13 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 10.0.0"
|
||||
},
|
||||
@@ -716,11 +730,13 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 10.0.0"
|
||||
},
|
||||
@@ -736,11 +752,13 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 10.0.0"
|
||||
},
|
||||
@@ -756,11 +774,13 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 10.0.0"
|
||||
},
|
||||
@@ -776,11 +796,13 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 10.0.0"
|
||||
},
|
||||
@@ -796,11 +818,13 @@
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 10.0.0"
|
||||
},
|
||||
@@ -816,11 +840,13 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 10.0.0"
|
||||
},
|
||||
@@ -1520,8 +1546,10 @@
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
|
||||
"integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"fill-range": "^7.1.1"
|
||||
},
|
||||
@@ -1595,7 +1623,10 @@
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz",
|
||||
"integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"readdirp": "^4.0.1"
|
||||
},
|
||||
@@ -1665,8 +1696,10 @@
|
||||
"version": "1.0.3",
|
||||
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-1.0.3.tgz",
|
||||
"integrity": "sha512-pGjwhsmsp4kL2RTz08wcOlGN83otlqHeD/Z5T8GXZB+/YcpQ/dgo+lbU8ZsGxV0HIvqqxo9l7mqYwyYMD9bKDg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"bin": {
|
||||
"detect-libc": "bin/detect-libc.js"
|
||||
},
|
||||
@@ -1832,8 +1865,10 @@
|
||||
"version": "7.1.1",
|
||||
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
|
||||
"integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"to-regex-range": "^5.0.1"
|
||||
},
|
||||
@@ -1993,14 +2028,19 @@
|
||||
"version": "5.1.4",
|
||||
"resolved": "https://registry.npmjs.org/immutable/-/immutable-5.1.4.tgz",
|
||||
"integrity": "sha512-p6u1bG3YSnINT5RQmx/yRZBpenIl30kVxkTLDyHLIMk0gict704Q9n+thfDI7lTRm9vXdDYutVzXhzcThxTnXA==",
|
||||
"license": "MIT"
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/is-extglob": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
|
||||
"integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
@@ -2009,8 +2049,10 @@
|
||||
"version": "4.0.3",
|
||||
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
|
||||
"integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"is-extglob": "^2.1.1"
|
||||
},
|
||||
@@ -2022,8 +2064,10 @@
|
||||
"version": "7.0.0",
|
||||
"resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
|
||||
"integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=0.12.0"
|
||||
}
|
||||
@@ -2064,8 +2108,10 @@
|
||||
"version": "4.0.8",
|
||||
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
|
||||
"integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"braces": "^3.0.3",
|
||||
"picomatch": "^2.3.1"
|
||||
@@ -2078,8 +2124,10 @@
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
|
||||
"integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=8.6"
|
||||
},
|
||||
@@ -2137,8 +2185,10 @@
|
||||
"version": "7.1.1",
|
||||
"resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz",
|
||||
"integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true
|
||||
"optional": true,
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/pathe": {
|
||||
"version": "2.0.3",
|
||||
@@ -2223,7 +2273,10 @@
|
||||
"version": "4.1.2",
|
||||
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz",
|
||||
"integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">= 14.18.0"
|
||||
},
|
||||
@@ -2281,7 +2334,10 @@
|
||||
"version": "1.97.2",
|
||||
"resolved": "https://registry.npmjs.org/sass/-/sass-1.97.2.tgz",
|
||||
"integrity": "sha512-y5LWb0IlbO4e97Zr7c3mlpabcbBtS+ieiZ9iwDooShpFKWXf62zz5pEPdwrLYm+Bxn1fnbwFGzHuCLSA9tBmrw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"chokidar": "^4.0.0",
|
||||
"immutable": "^5.0.2",
|
||||
@@ -2340,16 +2396,6 @@
|
||||
"url": "https://github.com/sponsors/antfu"
|
||||
}
|
||||
},
|
||||
"node_modules/sweetalert2": {
|
||||
"version": "11.26.17",
|
||||
"resolved": "https://registry.npmjs.org/sweetalert2/-/sweetalert2-11.26.17.tgz",
|
||||
"integrity": "sha512-kkaySn1IRfwNlf9AkZVqDmBINDWw9NRR6Ij0O5dBRBOD1+mbtZJWxxR9/pA90nce9E5tIIkJ7SWij4rMWXtA1g==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/limonte"
|
||||
}
|
||||
},
|
||||
"node_modules/tinybench": {
|
||||
"version": "2.9.0",
|
||||
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
|
||||
@@ -2415,8 +2461,10 @@
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
|
||||
"integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"is-number": "^7.0.0"
|
||||
},
|
||||
|
||||
@@ -15,8 +15,6 @@
|
||||
"bootstrap": "^5.3.8",
|
||||
"chart.js": "^4.5.1",
|
||||
"qrcode.vue": "^3.6.0",
|
||||
"sass": "^1.97.2",
|
||||
"sweetalert2": "^11.26.17",
|
||||
"vue": "^3.5.24",
|
||||
"vue-router": "^4.6.4"
|
||||
},
|
||||
|
||||
+11
-22
@@ -24,7 +24,6 @@
|
||||
|
||||
<!-- SECTION: MONITORING -->
|
||||
<div class="nav-section-header">MONITORING</div>
|
||||
<p></p>
|
||||
<router-link to="/" class="nav-link" active-class="active" title="Analytics">
|
||||
<i class="fas fa-chart-line"></i> <span>Analytics</span>
|
||||
</router-link>
|
||||
@@ -34,7 +33,6 @@
|
||||
|
||||
<!-- SECTION: CONFIGURATION -->
|
||||
<div class="nav-section-header mt-3">CONFIGURATION</div>
|
||||
<p></p>
|
||||
<router-link to="/config/pki" class="nav-link" active-class="active" title="PKI">
|
||||
<i class="fas fa-fingerprint"></i> <span>PKI</span>
|
||||
</router-link>
|
||||
@@ -48,7 +46,6 @@
|
||||
|
||||
<!-- SECTION: MANAGEMENT -->
|
||||
<div class="nav-section-header mt-3">MANAGEMENT</div>
|
||||
<p></p>
|
||||
<router-link to="/certificates" class="nav-link" active-class="active" title="Certificates">
|
||||
<i class="fas fa-certificate"></i> <span>Certificates</span>
|
||||
</router-link>
|
||||
@@ -61,7 +58,6 @@
|
||||
|
||||
<!-- SECTION: ACCOUNT -->
|
||||
<div class="nav-section-header mt-3">ACCOUNT</div>
|
||||
<p></p>
|
||||
<router-link to="/account" class="nav-link" active-class="active" title="Account Settings">
|
||||
<i class="fas fa-user-cog"></i> <span>Account Settings</span>
|
||||
</router-link>
|
||||
@@ -96,10 +92,10 @@
|
||||
<i class="fas fa-globe me-1 text-muted"></i>{{ timezoneAbbr }}
|
||||
</span>
|
||||
<button class="btn-header" @click="toggleTheme" title="Toggle Theme">
|
||||
<i class="fas" :class="isDark ? 'fa-sun' : 'fa-moon'" id="themeIcon"></i>
|
||||
<i class="fas" :class="isDark ? 'fa-sun' : 'fa-moon'"></i>
|
||||
</button>
|
||||
<button class="btn-header me-2" @click="refreshPage" title="Refresh">
|
||||
<i class="fas fa-sync-alt" id="refreshIcon"></i>
|
||||
<i class="fas fa-sync-alt"></i>
|
||||
</button>
|
||||
|
||||
<div class="header-divider d-none d-md-block"></div>
|
||||
@@ -138,11 +134,12 @@ import { useRoute, useRouter } from 'vue-router';
|
||||
import ToastContainer from './components/ToastContainer.vue';
|
||||
import { usePkiStatus } from './composables/usePkiStatus';
|
||||
import { useToast } from './composables/useToast';
|
||||
import { useTheme } from './composables/useTheme';
|
||||
|
||||
const { loadConfig, isLoaded } = useAppConfig();
|
||||
const { apiClient } = useApi();
|
||||
const timezoneAbbr = ref(new Date().toLocaleTimeString('en-us',{timeZoneName:'short'}).split(' ')[2] || 'UTC');
|
||||
const isDark = ref(false);
|
||||
const { isDark, toggleTheme } = useTheme();
|
||||
const refreshKey = ref(0);
|
||||
const isSidebarOpen = ref(false);
|
||||
const isCompact = ref(false);
|
||||
@@ -151,7 +148,11 @@ const router = useRouter();
|
||||
const { status: pkiStatus, refresh: refreshPkiStatus } = usePkiStatus();
|
||||
const toast = useToast();
|
||||
|
||||
const isAuthenticated = computed(() => route.name !== 'Login');
|
||||
// Signed in: a stored token on a non-public page (the token is not reactive: it is re-read on every navigation)
|
||||
const isAuthenticated = computed(() => {
|
||||
void route.fullPath;
|
||||
return !route.meta.public && !!localStorage.getItem('ovpmon_token');
|
||||
});
|
||||
const username = ref(localStorage.getItem('ovpmon_user') || '');
|
||||
|
||||
// Keep the header name in sync with the server (login, rename, stale session)
|
||||
@@ -183,13 +184,6 @@ const handleLogout = () => {
|
||||
router.push('/login');
|
||||
};
|
||||
|
||||
const toggleTheme = () => {
|
||||
isDark.value = !isDark.value;
|
||||
const theme = isDark.value ? 'dark' : 'light';
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
localStorage.setItem('theme', theme);
|
||||
};
|
||||
|
||||
const toggleSidebar = () => {
|
||||
isCompact.value = !isCompact.value;
|
||||
localStorage.setItem('sidebarCompact', isCompact.value);
|
||||
@@ -202,7 +196,7 @@ const refreshPage = () => {
|
||||
// Close sidebar on route change
|
||||
watch(() => route.path, () => {
|
||||
isSidebarOpen.value = false;
|
||||
if (route.name !== 'Login') {
|
||||
if (isAuthenticated.value) {
|
||||
syncUsername();
|
||||
refreshPkiStatus();
|
||||
}
|
||||
@@ -211,16 +205,11 @@ watch(() => route.path, () => {
|
||||
onMounted(async () => {
|
||||
await loadConfig();
|
||||
window.addEventListener('ovpmon-user-changed', onUserChanged);
|
||||
if (route.name !== 'Login') {
|
||||
if (isAuthenticated.value) {
|
||||
syncUsername();
|
||||
refreshPkiStatus();
|
||||
}
|
||||
|
||||
// Init Theme
|
||||
const savedTheme = localStorage.getItem('theme') || 'light';
|
||||
isDark.value = savedTheme === 'dark';
|
||||
document.documentElement.setAttribute('data-theme', savedTheme);
|
||||
|
||||
// Init Sidebar
|
||||
const savedCompact = localStorage.getItem('sidebarCompact');
|
||||
isCompact.value = savedCompact === 'true';
|
||||
|
||||
@@ -272,6 +272,11 @@ body {
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
/* Space between a section header and its first link (also kept when the header is hidden in compact mode) */
|
||||
.nav-section-header + .nav-link {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
/* Compact Mode Styles */
|
||||
.sidebar.compact {
|
||||
width: 64px;
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted, onUnmounted } from 'vue';
|
||||
import { ref, computed, onMounted, onUnmounted } from 'vue';
|
||||
import { Modal } from 'bootstrap';
|
||||
|
||||
const props = defineProps({
|
||||
@@ -40,11 +40,11 @@ const props = defineProps({
|
||||
}
|
||||
});
|
||||
|
||||
const emit = defineEmits(['close', 'opened', 'closed']);
|
||||
const emit = defineEmits(['opened', 'closed']);
|
||||
|
||||
const modalRef = ref(null);
|
||||
let bsModal = null;
|
||||
const sizeClass = props.size || '';
|
||||
const sizeClass = computed(() => props.size || '');
|
||||
|
||||
const show = () => {
|
||||
bsModal?.show();
|
||||
@@ -63,7 +63,6 @@ onMounted(() => {
|
||||
|
||||
modalRef.value.addEventListener('hidden.bs.modal', () => {
|
||||
emit('closed');
|
||||
emit('close');
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<BaseModal id="confirmModal" :title="title" ref="modal">
|
||||
<BaseModal :id="modalId" :title="title" ref="modal">
|
||||
<template #body>
|
||||
<p class="text-main" style="white-space: pre-line;">{{ message }}</p>
|
||||
</template>
|
||||
@@ -13,9 +13,11 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue';
|
||||
import { ref, useId } from 'vue';
|
||||
import BaseModal from './BaseModal.vue';
|
||||
|
||||
// Unique element id: several ConfirmModal instances may live on one page
|
||||
const modalId = `confirm-${useId()}`;
|
||||
const emit = defineEmits(['confirm']);
|
||||
const modal = ref(null);
|
||||
|
||||
|
||||
@@ -54,15 +54,12 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue';
|
||||
import Chart from 'chart.js/auto';
|
||||
import { ref, onMounted, onUnmounted } from 'vue';
|
||||
import { useApi } from '../composables/useApi';
|
||||
import { useFormatters } from '../composables/useFormatters';
|
||||
import { useTrafficChart } from '../composables/useTrafficChart';
|
||||
import { Modal } from 'bootstrap';
|
||||
|
||||
const props = defineProps(['modelValue']); // If we wanted v-model control, but using manual open method for now
|
||||
const { fetchClientHistory } = useApi();
|
||||
const { parseServerDate } = useFormatters();
|
||||
|
||||
const modalRef = ref(null);
|
||||
const chartCanvas = ref(null);
|
||||
@@ -71,10 +68,10 @@ const range = ref('24h');
|
||||
const isSpeedMode = ref(false);
|
||||
const loading = ref(false);
|
||||
let bsModal = null;
|
||||
let chartInstance = null;
|
||||
let cachedData = null;
|
||||
let requestId = 0; // the latest request wins: a slow answer for an old range or client is dropped
|
||||
|
||||
const MAX_CHART_POINTS = 48;
|
||||
const chart = useTrafficChart(chartCanvas, { maxPoints: 48 });
|
||||
|
||||
const open = (name) => {
|
||||
clientName.value = name;
|
||||
@@ -90,159 +87,52 @@ const close = () => {
|
||||
|
||||
const loadHistory = async () => {
|
||||
if (!clientName.value) return;
|
||||
const id = ++requestId;
|
||||
loading.value = true;
|
||||
try {
|
||||
const res = await fetchClientHistory(clientName.value, range.value);
|
||||
if (id !== requestId) return;
|
||||
if (res.success && res.data.history) {
|
||||
cachedData = res.data.history;
|
||||
// Map the raw fields to the point format of useTrafficChart
|
||||
cachedData = res.data.history.map(p => ({
|
||||
timestamp: p.timestamp,
|
||||
bytes_received: p.bytes_received,
|
||||
bytes_sent: p.bytes_sent,
|
||||
rx_rate_mbps: p.bytes_received_rate_mbps,
|
||||
tx_rate_mbps: p.bytes_sent_rate_mbps
|
||||
}));
|
||||
renderChart();
|
||||
} else {
|
||||
cachedData = [];
|
||||
if (chartInstance) chartInstance.destroy();
|
||||
chart.destroy();
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
if (id === requestId) console.error(e);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
if (id === requestId) loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const renderChart = () => {
|
||||
if (!chartCanvas.value || !cachedData) return;
|
||||
if (chartInstance) chartInstance.destroy();
|
||||
|
||||
const ctx = chartCanvas.value.getContext('2d');
|
||||
const downsampled = downsampleData(cachedData, MAX_CHART_POINTS);
|
||||
|
||||
const labels = [];
|
||||
const dataRx = [];
|
||||
const dataTx = [];
|
||||
|
||||
downsampled.forEach(point => {
|
||||
const d = parseServerDate(point.timestamp);
|
||||
let label = '';
|
||||
|
||||
if(range.value.includes('h') || range.value === '1d') {
|
||||
label = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
} else {
|
||||
label = d.toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ' +
|
||||
d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
labels.push(label);
|
||||
|
||||
if (!isSpeedMode.value) {
|
||||
dataRx.push(point.bytes_received / (1024 * 1024)); // MB
|
||||
dataTx.push(point.bytes_sent / (1024 * 1024)); // MB
|
||||
} else {
|
||||
dataRx.push(point.bytes_received_rate_mbps);
|
||||
dataTx.push(point.bytes_sent_rate_mbps);
|
||||
}
|
||||
});
|
||||
|
||||
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
|
||||
const gridColor = isDark ? 'rgba(240, 246, 252, 0.1)' : 'rgba(0,0,0,0.05)';
|
||||
const textColor = isDark ? '#8b949e' : '#6c757d';
|
||||
|
||||
chartInstance = new Chart(ctx, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels,
|
||||
datasets: [
|
||||
{
|
||||
label: !isSpeedMode.value ? 'Received (MB)' : 'RX Mbps',
|
||||
data: dataRx,
|
||||
borderColor: '#1652B8', // OpenVPN Blue
|
||||
backgroundColor: 'rgba(22, 82, 184, 0.15)',
|
||||
borderWidth: 2,
|
||||
fill: true,
|
||||
tension: 0.3,
|
||||
pointRadius: 3,
|
||||
pointHoverRadius: 4
|
||||
},
|
||||
{
|
||||
label: !isSpeedMode.value ? 'Sent (MB)' : 'TX Mbps',
|
||||
data: dataTx,
|
||||
borderColor: '#EC7C31', // OpenVPN Orange
|
||||
backgroundColor: 'rgba(236, 124, 49, 0.15)',
|
||||
borderWidth: 2,
|
||||
fill: true,
|
||||
tension: 0.3,
|
||||
pointRadius: 3,
|
||||
pointHoverRadius: 4
|
||||
}
|
||||
]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
interaction: {
|
||||
mode: 'index',
|
||||
intersect: false,
|
||||
},
|
||||
plugins: {
|
||||
legend: { labels: { color: textColor } }
|
||||
},
|
||||
scales: {
|
||||
x: {
|
||||
ticks: { color: textColor, maxTicksLimit: 8 },
|
||||
grid: { color: gridColor }
|
||||
},
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
ticks: { color: textColor },
|
||||
grid: { color: gridColor }
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
if (!cachedData) return;
|
||||
chart.render(cachedData, { range: range.value, speedMode: isSpeedMode.value });
|
||||
};
|
||||
|
||||
const downsampleData = (data, maxPoints) => {
|
||||
if (!data || data.length === 0) return [];
|
||||
if (data.length <= maxPoints) return data;
|
||||
|
||||
const blockSize = Math.ceil(data.length / maxPoints);
|
||||
const result = [];
|
||||
|
||||
for (let i = 0; i < data.length; i += blockSize) {
|
||||
const chunk = data.slice(i, i + blockSize);
|
||||
if (chunk.length === 0) continue;
|
||||
|
||||
let sumRx = 0, sumTx = 0;
|
||||
let maxRxRate = 0, maxTxRate = 0;
|
||||
|
||||
chunk.forEach(pt => {
|
||||
sumRx += (pt.bytes_received || 0);
|
||||
sumTx += (pt.bytes_sent || 0);
|
||||
maxRxRate = Math.max(maxRxRate, pt.bytes_received_rate_mbps || 0);
|
||||
maxTxRate = Math.max(maxTxRate, pt.bytes_sent_rate_mbps || 0);
|
||||
});
|
||||
|
||||
result.push({
|
||||
timestamp: chunk[0].timestamp,
|
||||
bytes_received: sumRx,
|
||||
bytes_sent: sumTx,
|
||||
bytes_received_rate_mbps: maxRxRate,
|
||||
bytes_sent_rate_mbps: maxTxRate
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
bsModal = new Modal(modalRef.value);
|
||||
|
||||
// Clean up chart on close
|
||||
// Clean up the chart on close and drop answers that are still on the way
|
||||
modalRef.value.addEventListener('hidden.bs.modal', () => {
|
||||
if (chartInstance) {
|
||||
chartInstance.destroy();
|
||||
chartInstance = null;
|
||||
}
|
||||
requestId++;
|
||||
loading.value = false;
|
||||
cachedData = null;
|
||||
chart.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
if (chartInstance) chartInstance.destroy();
|
||||
requestId++;
|
||||
bsModal?.dispose();
|
||||
});
|
||||
|
||||
defineExpose({ open, close });
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
<template>
|
||||
<BaseModal id="newClientModal" title="Create New Client" ref="modal">
|
||||
<BaseModal id="newClientModal" title="Create New Client" ref="modal" @opened="inputRef?.focus()">
|
||||
<template #body>
|
||||
<div class="mb-3">
|
||||
<label for="clientName" class="form-label small text-muted text-uppercase fw-bold">Client Name</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-user"></i></span>
|
||||
<input type="text" class="form-control" id="clientName" v-model="clientName" placeholder="e.g. laptop-user" @keyup.enter="confirm" ref="inputRef">
|
||||
<input type="text" class="form-control" :class="{ 'is-invalid': clientName && !isValid }" id="clientName"
|
||||
v-model="clientName" placeholder="e.g. laptop-user" maxlength="64" autocomplete="off" @keyup.enter="confirm" ref="inputRef">
|
||||
</div>
|
||||
<div v-if="clientName && !isValid" class="text-danger small mt-2">
|
||||
Letters, digits, dashes and underscores only; the first character must be a letter or a digit.
|
||||
</div>
|
||||
<div class="form-text mt-2 text-muted small">
|
||||
<i class="fas fa-info-circle me-1"></i> Use only alphanumeric characters, dashes, or underscores.
|
||||
@@ -14,7 +18,7 @@
|
||||
</template>
|
||||
<template #footer>
|
||||
<button type="button" class="btn-action btn-action-secondary" @click="close">Cancel</button>
|
||||
<button type="button" class="btn-action btn-action-save" @click="confirm" :disabled="!clientName">
|
||||
<button type="button" class="btn-action btn-action-save" @click="confirm" :disabled="!isValid">
|
||||
Create Client
|
||||
</button>
|
||||
</template>
|
||||
@@ -22,7 +26,7 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref } from 'vue';
|
||||
import { ref, computed } from 'vue';
|
||||
import BaseModal from './BaseModal.vue';
|
||||
|
||||
const emit = defineEmits(['create']);
|
||||
@@ -30,10 +34,13 @@ const modal = ref(null);
|
||||
const clientName = ref('');
|
||||
const inputRef = ref(null);
|
||||
|
||||
// Same rule as the profiler API (without dots): 1-64 characters, no leading dash or underscore
|
||||
const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
||||
const isValid = computed(() => NAME_RE.test(clientName.value));
|
||||
|
||||
const open = () => {
|
||||
clientName.value = '';
|
||||
modal.value.show();
|
||||
setTimeout(() => inputRef.value?.focus(), 500);
|
||||
modal.value.show(); // the input is focused on the opened event
|
||||
};
|
||||
|
||||
const close = () => {
|
||||
@@ -41,7 +48,7 @@ const close = () => {
|
||||
};
|
||||
|
||||
const confirm = () => {
|
||||
if (clientName.value) {
|
||||
if (isValid.value) {
|
||||
emit('create', clientName.value);
|
||||
close();
|
||||
}
|
||||
|
||||
@@ -4,18 +4,21 @@ import { useAppConfig } from './useAppConfig';
|
||||
// Singleton instances
|
||||
const apiClient = axios.create();
|
||||
const profilesApiClient = axios.create();
|
||||
// Auth endpoints (/api/auth): login, 2FA, password and username changes
|
||||
const authApiClient = axios.create();
|
||||
|
||||
// Helper to get base URLs
|
||||
const getBaseUrl = (config) => config?.api_base_url || 'http://localhost:5001/api/v1';
|
||||
const getProfilesBaseUrl = (config) => config?.profiles_api_base_url || 'http://localhost:8000';
|
||||
|
||||
// Auth endpoints answer 401 for a wrong current password or 2FA code (change-password, change-username):
|
||||
// that is a form error, not an expired session, so it must not log the user out.
|
||||
export const isAuthRequest = (url) => /(^|\/)auth\//.test(url || '');
|
||||
// The auth routes sit next to the API root: /api/v1 -> /api/auth
|
||||
const getAuthBaseUrl = (config) => {
|
||||
const base = getBaseUrl(config).replace(/\/+$/, '');
|
||||
return /\/v1$/.test(base) ? base.replace(/\/v1$/, '/auth') : base + '/../auth';
|
||||
};
|
||||
|
||||
// 401 on a regular API request: the session is gone, clear it and go to the login page
|
||||
export const handleUnauthorized = (error) => {
|
||||
if (error.response && error.response.status === 401 && !isAuthRequest(error.config?.url)) {
|
||||
if (error.response && error.response.status === 401) {
|
||||
localStorage.removeItem('ovpmon_token');
|
||||
localStorage.removeItem('ovpmon_user');
|
||||
// Redirecting using window.location for absolute refresh
|
||||
@@ -26,8 +29,10 @@ export const handleUnauthorized = (error) => {
|
||||
return Promise.reject(error);
|
||||
};
|
||||
|
||||
// Add interceptors to handle Auth and Dynamic Base URLs
|
||||
const setupInterceptors = (instance, getBase) => {
|
||||
// Add interceptors to handle Auth and Dynamic Base URLs.
|
||||
// endSessionOn401 is false for authApiClient: /auth/* answers 401 for a wrong current password or
|
||||
// 2FA code (login, change-password, change-username). That is a form error, not an expired session.
|
||||
const setupInterceptors = (instance, getBase, { endSessionOn401 = true } = {}) => {
|
||||
instance.interceptors.request.use((reqConfig) => {
|
||||
const { config } = useAppConfig();
|
||||
reqConfig.baseURL = getBase(config.value);
|
||||
@@ -39,11 +44,14 @@ const setupInterceptors = (instance, getBase) => {
|
||||
return reqConfig;
|
||||
});
|
||||
|
||||
if (endSessionOn401) {
|
||||
instance.interceptors.response.use(response => response, handleUnauthorized);
|
||||
}
|
||||
};
|
||||
|
||||
setupInterceptors(apiClient, getBaseUrl);
|
||||
setupInterceptors(profilesApiClient, getProfilesBaseUrl);
|
||||
setupInterceptors(authApiClient, getAuthBaseUrl, { endSessionOn401: false });
|
||||
|
||||
export function useApi() {
|
||||
const fetchStats = async () => {
|
||||
@@ -70,6 +78,7 @@ export function useApi() {
|
||||
return {
|
||||
apiClient,
|
||||
profilesApiClient,
|
||||
authApiClient,
|
||||
fetchStats,
|
||||
fetchClientHistory,
|
||||
fetchAnalytics,
|
||||
|
||||
@@ -28,7 +28,7 @@ const failWith = async (client, status, url) => {
|
||||
describe('401 handling', () => {
|
||||
it('keeps the session on 401 from /auth/* (wrong password or 2FA code)', async () => {
|
||||
const { useApi } = await import('./useApi');
|
||||
await failWith(useApi().apiClient, 401, '../auth/change-password');
|
||||
await failWith(useApi().authApiClient, 401, '/change-password');
|
||||
expect(store.ovpmon_token).toBe('tok');
|
||||
expect(location.href).toBe('/account');
|
||||
});
|
||||
@@ -40,6 +40,15 @@ describe('401 handling', () => {
|
||||
expect(location.href).toBe('/login');
|
||||
});
|
||||
|
||||
it('builds the auth base URL next to the API root', async () => {
|
||||
const { useApi } = await import('./useApi');
|
||||
let seen;
|
||||
const client = useApi().authApiClient;
|
||||
client.defaults.adapter = (config) => { seen = config; return Promise.resolve({ status: 200, data: {}, config }); };
|
||||
await client.post('/login');
|
||||
expect(seen.baseURL).toBe('http://localhost:5001/api/auth');
|
||||
});
|
||||
|
||||
it('ignores other error codes', async () => {
|
||||
const { useApi } = await import('./useApi');
|
||||
await failWith(useApi().profilesApiClient, 500, '/profiles');
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { ref, onMounted, onUnmounted } from 'vue';
|
||||
|
||||
const STORAGE_KEY = 'theme';
|
||||
|
||||
const isDark = ref(false);
|
||||
|
||||
const apply = (theme) => {
|
||||
isDark.value = theme === 'dark';
|
||||
document.documentElement.setAttribute('data-theme', theme);
|
||||
};
|
||||
|
||||
// Saved choice first, then the system setting (prefers-color-scheme) on the first visit.
|
||||
// Called from main.js before the app is mounted, so the page never flashes in the wrong theme.
|
||||
export const initTheme = () => {
|
||||
let theme = null;
|
||||
try { theme = localStorage.getItem(STORAGE_KEY); } catch (e) { /* storage blocked */ }
|
||||
if (theme !== 'dark' && theme !== 'light') {
|
||||
theme = window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
apply(theme);
|
||||
};
|
||||
|
||||
const toggleTheme = () => {
|
||||
const theme = isDark.value ? 'light' : 'dark';
|
||||
apply(theme);
|
||||
try { localStorage.setItem(STORAGE_KEY, theme); } catch (e) { /* storage blocked */ }
|
||||
};
|
||||
|
||||
export function useTheme() {
|
||||
return { isDark, toggleTheme };
|
||||
}
|
||||
|
||||
// Call `callback` whenever data-theme of <html> changes; the observer is released with the component
|
||||
export function useThemeObserver(callback) {
|
||||
let observer = null;
|
||||
onMounted(() => {
|
||||
observer = new MutationObserver((mutations) => {
|
||||
if (mutations.some(m => m.attributeName === 'data-theme')) callback();
|
||||
});
|
||||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] });
|
||||
});
|
||||
onUnmounted(() => observer?.disconnect());
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { onUnmounted } from 'vue';
|
||||
import Chart from 'chart.js/auto';
|
||||
import { useFormatters } from './useFormatters';
|
||||
|
||||
export const COLOR_RX = '#1652B8'; // OpenVPN Blue
|
||||
export const COLOR_TX = '#EC7C31'; // Brand Orange
|
||||
|
||||
const MB = 1024 * 1024;
|
||||
|
||||
// Chart colors depend on the page theme (data-theme of <html>)
|
||||
export const getThemeColors = () => {
|
||||
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
|
||||
return {
|
||||
isDark,
|
||||
gridColor: isDark ? 'rgba(240, 246, 252, 0.1)' : 'rgba(0,0,0,0.05)',
|
||||
textColor: isDark ? '#8b949e' : '#6c757d'
|
||||
};
|
||||
};
|
||||
|
||||
// Points: { timestamp, bytes_received, bytes_sent, rx_rate_mbps, tx_rate_mbps }.
|
||||
// Blocks of points are merged: traffic is summed, speed takes the block maximum.
|
||||
export const downsamplePoints = (points, maxPoints) => {
|
||||
if (!points || points.length === 0) return [];
|
||||
if (points.length <= maxPoints) return points;
|
||||
|
||||
const blockSize = Math.ceil(points.length / maxPoints);
|
||||
const result = [];
|
||||
|
||||
for (let i = 0; i < points.length; i += blockSize) {
|
||||
const chunk = points.slice(i, i + blockSize);
|
||||
if (chunk.length === 0) continue;
|
||||
|
||||
let sumRx = 0, sumTx = 0;
|
||||
let maxRxRate = 0, maxTxRate = 0;
|
||||
|
||||
chunk.forEach(pt => {
|
||||
sumRx += (pt.bytes_received || 0);
|
||||
sumTx += (pt.bytes_sent || 0);
|
||||
maxRxRate = Math.max(maxRxRate, pt.rx_rate_mbps || 0);
|
||||
maxTxRate = Math.max(maxTxRate, pt.tx_rate_mbps || 0);
|
||||
});
|
||||
|
||||
result.push({
|
||||
timestamp: chunk[0].timestamp,
|
||||
bytes_received: sumRx,
|
||||
bytes_sent: sumTx,
|
||||
rx_rate_mbps: maxRxRate,
|
||||
tx_rate_mbps: maxTxRate
|
||||
});
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
// Line chart of received/sent traffic bound to a canvas ref.
|
||||
// const chart = useTrafficChart(canvasRef, { maxPoints: 96 });
|
||||
// chart.render(points, { range: '24h', speedMode: false });
|
||||
// The chart is destroyed together with the component.
|
||||
export function useTrafficChart(canvasRef, { maxPoints }) {
|
||||
const { parseServerDate } = useFormatters();
|
||||
let instance = null;
|
||||
|
||||
const destroy = () => {
|
||||
if (instance) {
|
||||
instance.destroy();
|
||||
instance = null;
|
||||
}
|
||||
};
|
||||
|
||||
const formatLabel = (timestamp, range) => {
|
||||
const d = parseServerDate(timestamp);
|
||||
const time = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
if (range.includes('h') || range === '1d') return time;
|
||||
return d.toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ' + time;
|
||||
};
|
||||
|
||||
const render = (points, { range, speedMode }) => {
|
||||
if (!canvasRef.value) return;
|
||||
destroy();
|
||||
|
||||
const labels = [];
|
||||
const dataRx = [];
|
||||
const dataTx = [];
|
||||
|
||||
downsamplePoints(points, maxPoints).forEach(point => {
|
||||
labels.push(formatLabel(point.timestamp, range));
|
||||
if (!speedMode) {
|
||||
dataRx.push(point.bytes_received / MB);
|
||||
dataTx.push(point.bytes_sent / MB);
|
||||
} else {
|
||||
dataRx.push(point.rx_rate_mbps || 0);
|
||||
dataTx.push(point.tx_rate_mbps || 0);
|
||||
}
|
||||
});
|
||||
|
||||
const { gridColor, textColor } = getThemeColors();
|
||||
const dataset = (label, data, color, fill) => ({
|
||||
label,
|
||||
data,
|
||||
borderColor: color,
|
||||
backgroundColor: fill,
|
||||
borderWidth: 2,
|
||||
fill: true,
|
||||
tension: 0.3,
|
||||
pointRadius: 3,
|
||||
pointHoverRadius: 4
|
||||
});
|
||||
|
||||
instance = new Chart(canvasRef.value.getContext('2d'), {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels,
|
||||
datasets: [
|
||||
dataset(speedMode ? 'RX Mbps' : 'Received (MB)', dataRx, COLOR_RX, 'rgba(22, 82, 184, 0.15)'),
|
||||
dataset(speedMode ? 'TX Mbps' : 'Sent (MB)', dataTx, COLOR_TX, 'rgba(236, 124, 49, 0.15)')
|
||||
]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
interaction: { mode: 'index', intersect: false },
|
||||
plugins: { legend: { labels: { color: textColor } } },
|
||||
scales: {
|
||||
x: { ticks: { color: textColor, maxTicksLimit: 8 }, grid: { color: gridColor } },
|
||||
y: { beginAtZero: true, ticks: { color: textColor }, grid: { color: gridColor } }
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
onUnmounted(destroy);
|
||||
|
||||
return { render, destroy };
|
||||
}
|
||||
+3
-16
@@ -8,23 +8,10 @@ import 'bootstrap/dist/js/bootstrap.bundle.min.js';
|
||||
import '@fortawesome/fontawesome-free/css/all.min.css';
|
||||
|
||||
import './assets/main.css';
|
||||
import axios from 'axios';
|
||||
import { initTheme } from './composables/useTheme';
|
||||
|
||||
// Global Axios Defaults (No Base URL - handled by useApi.js)
|
||||
// We keep global error handling for 401s as a fallback
|
||||
axios.interceptors.response.use(
|
||||
response => response,
|
||||
error => {
|
||||
if (error.response && error.response.status === 401) {
|
||||
localStorage.removeItem('ovpmon_token');
|
||||
localStorage.removeItem('ovpmon_user');
|
||||
if (window.location.pathname !== '/login') {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
// Theme is applied before mounting: no flash of the wrong theme
|
||||
initTheme();
|
||||
|
||||
const app = createApp(App);
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router';
|
||||
import Clients from '../views/Clients.vue';
|
||||
import Login from '../views/Login.vue';
|
||||
import { usePkiStatus } from '../composables/usePkiStatus';
|
||||
import { useToast } from '../composables/useToast';
|
||||
@@ -13,7 +12,7 @@ const routes = [
|
||||
{
|
||||
path: '/clients',
|
||||
name: 'Clients',
|
||||
component: Clients
|
||||
component: () => import('../views/Clients.vue')
|
||||
},
|
||||
{
|
||||
path: '/certificates',
|
||||
@@ -52,6 +51,11 @@ const routes = [
|
||||
name: 'Login',
|
||||
component: Login,
|
||||
meta: { public: true }
|
||||
},
|
||||
// Unknown address: back to the start page (the guard sends guests to the login page)
|
||||
{
|
||||
path: '/:pathMatch(.*)*',
|
||||
redirect: '/'
|
||||
}
|
||||
];
|
||||
|
||||
|
||||
@@ -117,10 +117,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Alerts/Notifications Modal -->
|
||||
<ConfirmModal ref="confirmModal" />
|
||||
|
||||
<!-- Action Confirmations Modal -->
|
||||
<!-- Confirmation before 2FA is disabled; results are shown as toasts -->
|
||||
<ConfirmModal ref="disable2FAModal" @confirm="handleDisable2FA" />
|
||||
|
||||
<!-- Password Change Modal -->
|
||||
@@ -223,16 +220,16 @@
|
||||
import { ref, onMounted, reactive } from 'vue';
|
||||
import { useApi } from '../composables/useApi';
|
||||
import QrcodeVue from 'qrcode.vue';
|
||||
import Swal from 'sweetalert2';
|
||||
import BaseModal from '../components/BaseModal.vue';
|
||||
import ConfirmModal from '../components/ConfirmModal.vue';
|
||||
import { useToast } from '../composables/useToast';
|
||||
|
||||
const { apiClient } = useApi();
|
||||
const { apiClient, authApiClient } = useApi();
|
||||
const toast = useToast();
|
||||
|
||||
// UI Refs
|
||||
const pwModal = ref(null);
|
||||
const userModal = ref(null);
|
||||
const confirmModal = ref(null);
|
||||
const disable2FAModal = ref(null);
|
||||
|
||||
// Password Logic
|
||||
@@ -252,36 +249,21 @@ const showPwModal = () => {
|
||||
|
||||
const handleChangePassword = async () => {
|
||||
if (passwordForm.new_password !== passwordForm.confirm_password) {
|
||||
Swal.fire({
|
||||
title: 'Error!',
|
||||
text: 'New passwords do not match',
|
||||
icon: 'error',
|
||||
confirmButtonColor: '#EC7C31'
|
||||
});
|
||||
toast.show('New passwords do not match', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
pwLoading.value = true;
|
||||
try {
|
||||
await apiClient.post('../auth/change-password', {
|
||||
await authApiClient.post('/change-password', {
|
||||
current_password: passwordForm.current_password,
|
||||
new_password: passwordForm.new_password
|
||||
});
|
||||
|
||||
pwModal.value.hide();
|
||||
Swal.fire({
|
||||
title: 'Success!',
|
||||
text: 'Password updated successfully.',
|
||||
icon: 'success',
|
||||
confirmButtonColor: '#1652B8'
|
||||
});
|
||||
toast.show('Password updated successfully.', 'success');
|
||||
} catch (err) {
|
||||
Swal.fire({
|
||||
title: 'Failed',
|
||||
text: err.response?.data?.error || 'Failed to update password',
|
||||
icon: 'error',
|
||||
confirmButtonColor: '#cf222e'
|
||||
});
|
||||
toast.show(err.response?.data?.error || 'Failed to update password', 'error');
|
||||
} finally {
|
||||
pwLoading.value = false;
|
||||
}
|
||||
@@ -300,18 +282,13 @@ const showUserModal = () => {
|
||||
|
||||
const handleChangeUsername = async () => {
|
||||
if (!/^[A-Za-z][A-Za-z0-9_.-]{2,31}$/.test(usernameForm.new_username)) {
|
||||
Swal.fire({
|
||||
title: 'Error!',
|
||||
text: 'Username must be 3-32 chars, start with a letter, and contain only letters, digits, . _ -',
|
||||
icon: 'error',
|
||||
confirmButtonColor: '#EC7C31'
|
||||
});
|
||||
toast.show('Username must be 3-32 chars, start with a letter, and contain only letters, digits, . _ -', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
userLoading.value = true;
|
||||
try {
|
||||
const res = await apiClient.post('../auth/change-username', {
|
||||
const res = await authApiClient.post('/change-username', {
|
||||
new_username: usernameForm.new_username,
|
||||
current_password: usernameForm.current_password,
|
||||
otp: usernameForm.otp || undefined
|
||||
@@ -320,19 +297,9 @@ const handleChangeUsername = async () => {
|
||||
try { localStorage.setItem('ovpmon_user', res.data.username); } catch (e) { /* ignore */ }
|
||||
window.dispatchEvent(new Event('ovpmon-user-changed'));
|
||||
userModal.value.hide();
|
||||
Swal.fire({
|
||||
title: 'Success!',
|
||||
text: 'Username updated. Use the new username the next time you sign in.',
|
||||
icon: 'success',
|
||||
confirmButtonColor: '#1652B8'
|
||||
});
|
||||
toast.show('Username updated. Use the new username the next time you sign in.', 'success');
|
||||
} catch (err) {
|
||||
Swal.fire({
|
||||
title: 'Failed',
|
||||
text: err.response?.data?.error || 'Failed to update username',
|
||||
icon: 'error',
|
||||
confirmButtonColor: '#cf222e'
|
||||
});
|
||||
toast.show(err.response?.data?.error || 'Failed to update username', 'error');
|
||||
} finally {
|
||||
userLoading.value = false;
|
||||
}
|
||||
@@ -344,7 +311,6 @@ const step2 = ref(false);
|
||||
const loading = ref(false);
|
||||
const otp = ref('');
|
||||
const setupData = ref({ secret: '', uri: '' });
|
||||
const isDark = ref(document.documentElement.getAttribute('data-theme') === 'dark');
|
||||
|
||||
const fetchUserStatus = async () => {
|
||||
loading.value = true;
|
||||
@@ -358,27 +324,16 @@ const fetchUserStatus = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
fetchUserStatus();
|
||||
|
||||
const observer = new MutationObserver((mutations) => {
|
||||
mutations.forEach((mutation) => {
|
||||
if (mutation.attributeName === 'data-theme') {
|
||||
isDark.value = document.documentElement.getAttribute('data-theme') === 'dark';
|
||||
}
|
||||
});
|
||||
});
|
||||
observer.observe(document.documentElement, { attributes: true });
|
||||
});
|
||||
onMounted(fetchUserStatus);
|
||||
|
||||
const initSetup = async () => {
|
||||
loading.value = true;
|
||||
try {
|
||||
const res = await apiClient.post('../auth/setup-2fa');
|
||||
const res = await authApiClient.post('/setup-2fa');
|
||||
setupData.value = res.data;
|
||||
step2.value = true;
|
||||
} catch (err) {
|
||||
Swal.fire('Error', 'Failed to initialize 2FA setup.', 'error');
|
||||
toast.show(err.response?.data?.error || 'Failed to initialize 2FA setup.', 'error');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
@@ -388,26 +343,14 @@ const verifyAndEnable = async () => {
|
||||
if (!otp.value || otp.value.length !== 6) return;
|
||||
loading.value = true;
|
||||
try {
|
||||
await apiClient.post('../auth/enable-2fa', {
|
||||
await authApiClient.post('/enable-2fa', {
|
||||
secret: setupData.value.secret,
|
||||
otp: otp.value
|
||||
});
|
||||
isEnabled.value = true;
|
||||
confirmModal.value.open({
|
||||
title: 'Success!',
|
||||
message: 'Two-factor authentication has been enabled successfully. Your dashboard is now more secure.',
|
||||
confirmText: 'Great!',
|
||||
confirmBtnClass: 'btn-action-save',
|
||||
showCancel: false
|
||||
});
|
||||
toast.show('Two-factor authentication has been enabled. Your dashboard is now more secure.', 'success');
|
||||
} catch (err) {
|
||||
confirmModal.value.open({
|
||||
title: 'Verification Failed',
|
||||
message: err.response?.data?.error || 'The code you entered is invalid. Please check your authenticator app and try again.',
|
||||
confirmText: 'Try Again',
|
||||
confirmBtnClass: 'btn-action-danger',
|
||||
showCancel: false
|
||||
});
|
||||
toast.show(err.response?.data?.error || 'The code you entered is invalid. Please check your authenticator app and try again.', 'error');
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
@@ -424,25 +367,13 @@ const disableConfirm = () => {
|
||||
|
||||
const handleDisable2FA = async () => {
|
||||
try {
|
||||
await apiClient.post('../auth/disable-2fa');
|
||||
await authApiClient.post('/disable-2fa');
|
||||
|
||||
isEnabled.value = false;
|
||||
step2.value = false;
|
||||
confirmModal.value.open({
|
||||
title: '2FA Disabled',
|
||||
message: 'Two-factor authentication has been disabled. Your account is now using standard password protection.',
|
||||
confirmText: 'OK',
|
||||
confirmBtnClass: 'btn-action-primary',
|
||||
showCancel: false
|
||||
});
|
||||
toast.show('Two-factor authentication has been disabled. Your account is now using standard password protection.', 'warning');
|
||||
} catch (err) {
|
||||
confirmModal.value.open({
|
||||
title: 'Error',
|
||||
message: err.response?.data?.error || 'Failed to disable two-factor authentication. Please try again.',
|
||||
confirmText: 'OK',
|
||||
confirmBtnClass: 'btn-action-danger',
|
||||
showCancel: false
|
||||
});
|
||||
toast.show(err.response?.data?.error || 'Failed to disable two-factor authentication. Please try again.', 'error');
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
+24
-140
@@ -151,16 +151,18 @@ import Chart from 'chart.js/auto';
|
||||
import { useApi } from '../composables/useApi';
|
||||
import { useFormatters } from '../composables/useFormatters';
|
||||
import { useAppConfig } from '../composables/useAppConfig';
|
||||
import { useThemeObserver } from '../composables/useTheme';
|
||||
import { useTrafficChart, getThemeColors, COLOR_RX, COLOR_TX } from '../composables/useTrafficChart';
|
||||
|
||||
const { fetchAnalytics, fetchCertificates } = useApi();
|
||||
const { formatBytes, parseServerDate } = useFormatters();
|
||||
const { formatBytes } = useFormatters();
|
||||
const { config } = useAppConfig();
|
||||
|
||||
// Refs
|
||||
const mainChartRef = ref(null);
|
||||
const pieChartRef = ref(null);
|
||||
let mainChartInstance = null;
|
||||
let pieChartInstance = null;
|
||||
const mainChart = useTrafficChart(mainChartRef, { maxPoints: 96 });
|
||||
|
||||
// State
|
||||
const loading = reactive({ analytics: true, certs: true });
|
||||
@@ -179,17 +181,14 @@ const kpi = reactive({
|
||||
|
||||
const topClients = ref([]);
|
||||
const expiringCertsList = ref([]);
|
||||
let cachedHistory = null;
|
||||
|
||||
// Helpers
|
||||
const MAX_CHART_POINTS = 96;
|
||||
let cachedHistory = [];
|
||||
|
||||
const loadAnalytics = async () => {
|
||||
loading.analytics = true;
|
||||
try {
|
||||
const res = await fetchAnalytics(range.value);
|
||||
if (res.success) {
|
||||
proccessData(res.data);
|
||||
processData(res.data);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
@@ -218,7 +217,7 @@ const loadCerts = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
const proccessData = (data) => {
|
||||
const processData = (data) => {
|
||||
kpi.concurrentUsers = data.max_concurrent_24h || 0;
|
||||
|
||||
// Traffic Distribution
|
||||
@@ -237,87 +236,21 @@ const proccessData = (data) => {
|
||||
percent: kpi.totalTraffic > 0 ? ((Number(c.total_traffic) / kpi.totalTraffic) * 100).toFixed(1) : 0
|
||||
}));
|
||||
|
||||
cachedHistory = data.global_history_24h || [];
|
||||
// Map the raw fields to the point format of useTrafficChart
|
||||
cachedHistory = (data.global_history_24h || []).map(p => ({
|
||||
timestamp: p.timestamp,
|
||||
bytes_received: p.total_rx,
|
||||
bytes_sent: p.total_tx,
|
||||
rx_rate_mbps: p.total_rx_rate,
|
||||
tx_rate_mbps: p.total_tx_rate
|
||||
}));
|
||||
|
||||
renderMainChart();
|
||||
renderPieChart();
|
||||
};
|
||||
|
||||
const renderMainChart = () => {
|
||||
if (!mainChartRef.value) return;
|
||||
if (mainChartInstance) mainChartInstance.destroy();
|
||||
|
||||
const downsampled = downsampleData(cachedHistory, MAX_CHART_POINTS);
|
||||
const labels = [];
|
||||
const dataRx = [];
|
||||
const dataTx = [];
|
||||
|
||||
downsampled.forEach(point => {
|
||||
const d = parseServerDate(point.timestamp);
|
||||
let label = '';
|
||||
if(range.value.includes('h') || range.value === '1d') {
|
||||
label = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
} else {
|
||||
label = d.toLocaleDateString([], { month: 'short', day: 'numeric' }) + ' ' +
|
||||
d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
labels.push(label);
|
||||
|
||||
if (!isSpeedMode.value) {
|
||||
dataRx.push(point.bytes_received / (1024 * 1024)); // MB
|
||||
dataTx.push(point.bytes_sent / (1024 * 1024)); // MB
|
||||
} else {
|
||||
dataRx.push(point.rx_rate_mbps || 0);
|
||||
dataTx.push(point.tx_rate_mbps || 0);
|
||||
}
|
||||
});
|
||||
|
||||
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
|
||||
const gridColor = isDark ? 'rgba(240, 246, 252, 0.1)' : 'rgba(0,0,0,0.05)';
|
||||
const textColor = isDark ? '#8b949e' : '#6c757d';
|
||||
|
||||
const ctx = mainChartRef.value.getContext('2d');
|
||||
mainChartInstance = new Chart(ctx, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels,
|
||||
datasets: [
|
||||
|
||||
{
|
||||
label: !isSpeedMode.value ? 'Received (MB)' : 'RX Mbps',
|
||||
data: dataRx,
|
||||
borderColor: '#1652B8', // OpenVPN Blue
|
||||
backgroundColor: 'rgba(22, 82, 184, 0.15)',
|
||||
borderWidth: 2,
|
||||
fill: true,
|
||||
tension: 0.3,
|
||||
pointRadius: 3,
|
||||
pointHoverRadius: 4
|
||||
},
|
||||
{
|
||||
label: !isSpeedMode.value ? 'Sent (MB)' : 'TX Mbps',
|
||||
data: dataTx,
|
||||
borderColor: '#EC7C31', // Brand Orange
|
||||
backgroundColor: 'rgba(236, 124, 49, 0.15)',
|
||||
borderWidth: 2,
|
||||
fill: true,
|
||||
tension: 0.3,
|
||||
pointRadius: 3,
|
||||
pointHoverRadius: 4
|
||||
}
|
||||
]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
interaction: { mode: 'index', intersect: false },
|
||||
plugins: { legend: { labels: { color: textColor } } },
|
||||
scales: {
|
||||
x: { ticks: { color: textColor, maxTicksLimit: 8 }, grid: { color: gridColor } },
|
||||
y: { beginAtZero: true, ticks: { color: textColor }, grid: { color: gridColor } }
|
||||
}
|
||||
}
|
||||
});
|
||||
mainChart.render(cachedHistory, { range: range.value, speedMode: isSpeedMode.value });
|
||||
};
|
||||
|
||||
const renderPieChart = () => {
|
||||
@@ -325,8 +258,7 @@ const renderPieChart = () => {
|
||||
if (pieChartInstance) pieChartInstance.destroy();
|
||||
|
||||
const ctx = pieChartRef.value.getContext('2d');
|
||||
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
|
||||
const bgColor = isDark ? '#161b22' : '#ffffff';
|
||||
const bgColor = getThemeColors().isDark ? '#161b22' : '#ffffff';
|
||||
|
||||
pieChartInstance = new Chart(ctx, {
|
||||
type: 'doughnut',
|
||||
@@ -334,7 +266,7 @@ const renderPieChart = () => {
|
||||
labels: ['Received', 'Sent'],
|
||||
datasets: [{
|
||||
data: [kpi.totalReceived, kpi.totalSent],
|
||||
backgroundColor: ['#1652B8', '#EC7C31'],
|
||||
backgroundColor: [COLOR_RX, COLOR_TX],
|
||||
borderColor: bgColor,
|
||||
borderWidth: 2,
|
||||
hoverOffset: 4
|
||||
@@ -349,66 +281,19 @@ const renderPieChart = () => {
|
||||
});
|
||||
};
|
||||
|
||||
const downsampleData = (data, maxPoints) => {
|
||||
if (!data || data.length === 0) return [];
|
||||
if (data.length <= maxPoints) {
|
||||
// Map raw fields to internal standardized names
|
||||
return data.map(p => ({
|
||||
timestamp: p.timestamp,
|
||||
bytes_received: p.total_rx,
|
||||
bytes_sent: p.total_tx,
|
||||
rx_rate_mbps: p.total_rx_rate,
|
||||
tx_rate_mbps: p.total_tx_rate
|
||||
}));
|
||||
}
|
||||
|
||||
const blockSize = Math.ceil(data.length / maxPoints);
|
||||
const result = [];
|
||||
|
||||
for (let i = 0; i < data.length; i += blockSize) {
|
||||
const chunk = data.slice(i, i + blockSize);
|
||||
if (chunk.length === 0) continue;
|
||||
|
||||
let sumRx = 0, sumTx = 0;
|
||||
let maxRxR = 0, maxTxR = 0;
|
||||
|
||||
chunk.forEach(pt => {
|
||||
sumRx += (pt.total_rx || 0);
|
||||
sumTx += (pt.total_tx || 0);
|
||||
maxRxR = Math.max(maxRxR, pt.total_rx_rate || 0);
|
||||
maxTxR = Math.max(maxTxR, pt.total_tx_rate || 0);
|
||||
});
|
||||
|
||||
result.push({
|
||||
timestamp: chunk[0].timestamp,
|
||||
bytes_received: sumRx,
|
||||
bytes_sent: sumTx,
|
||||
rx_rate_mbps: maxRxR,
|
||||
tx_rate_mbps: maxTxR
|
||||
});
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
// Lifecycle
|
||||
let intervalId;
|
||||
|
||||
// Redraw the charts when the theme is toggled
|
||||
useThemeObserver(() => {
|
||||
renderMainChart();
|
||||
renderPieChart();
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
loadAnalytics();
|
||||
loadCerts();
|
||||
|
||||
// Support Theme Toggle re-render like in Clients
|
||||
// We observe the attribute on html
|
||||
const observer = new MutationObserver((mutations) => {
|
||||
mutations.forEach((mutation) => {
|
||||
if (mutation.type === 'attributes' && mutation.attributeName === 'data-theme') {
|
||||
renderMainChart();
|
||||
renderPieChart();
|
||||
}
|
||||
});
|
||||
});
|
||||
observer.observe(document.documentElement, { attributes: true });
|
||||
|
||||
const refreshTime = config.value?.refresh_interval || 30000;
|
||||
intervalId = setInterval(() => {
|
||||
loadAnalytics();
|
||||
@@ -418,7 +303,6 @@ onMounted(() => {
|
||||
|
||||
onUnmounted(() => {
|
||||
if (intervalId) clearInterval(intervalId);
|
||||
if (mainChartInstance) mainChartInstance.destroy();
|
||||
if (pieChartInstance) pieChartInstance.destroy();
|
||||
});
|
||||
</script>
|
||||
@@ -296,6 +296,8 @@ const downloadConfig = async (cert) => {
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
// Release the blob after the browser has started the download
|
||||
setTimeout(() => window.URL.revokeObjectURL(url), 1000);
|
||||
} catch(e) {
|
||||
showToast('Could not download config: ' + (e.response?.data?.detail || e.message), 'error');
|
||||
}
|
||||
|
||||
@@ -126,7 +126,7 @@ import { useFormatters } from '../composables/useFormatters';
|
||||
import HistoryModal from '../components/HistoryModal.vue';
|
||||
import { useAppConfig } from '../composables/useAppConfig';
|
||||
|
||||
const { fetchStats, apiClient } = useApi();
|
||||
const { fetchStats } = useApi();
|
||||
const { formatBytes, formatRate, parseServerDate } = useFormatters();
|
||||
const { config } = useAppConfig();
|
||||
|
||||
|
||||
@@ -98,7 +98,7 @@ import { useRouter } from 'vue-router';
|
||||
import { useApi } from '../composables/useApi';
|
||||
|
||||
const router = useRouter();
|
||||
const { apiClient } = useApi();
|
||||
const { authApiClient } = useApi();
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const requires2FA = ref(false);
|
||||
@@ -114,9 +114,7 @@ const handleLogin = async () => {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
// Auth routes are under /api/auth, while apiClient defaults to /api/v1
|
||||
// We use a relative path with '..' to go up to /api
|
||||
const response = await apiClient.post('../auth/login', form);
|
||||
const response = await authApiClient.post('/login', form);
|
||||
if (response.data.requires_2fa) {
|
||||
requires2FA.value = true;
|
||||
tempToken.value = response.data.temp_token;
|
||||
@@ -137,7 +135,7 @@ const handleVerify2FA = async () => {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const response = await apiClient.post('../auth/verify-2fa', {
|
||||
const response = await authApiClient.post('/verify-2fa', {
|
||||
temp_token: tempToken.value,
|
||||
otp: otp.value
|
||||
});
|
||||
|
||||
@@ -1,251 +0,0 @@
|
||||
<template>
|
||||
<div class="login-page">
|
||||
<div class="login-card">
|
||||
<div class="login-header">
|
||||
<div class="brand-logo">
|
||||
<i class="fas fa-shield-alt"></i>
|
||||
</div>
|
||||
<h1>OpenVPN Monitor</h1>
|
||||
<p class="text-muted">Secure Access Control</p>
|
||||
</div>
|
||||
|
||||
<div class="login-body">
|
||||
<!-- Standard Login -->
|
||||
<form v-if="!requires2FA" @submit.prevent="handleLogin">
|
||||
<div class="mb-4">
|
||||
<label class="form-label">Username</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-user"></i></span>
|
||||
<input
|
||||
type="text"
|
||||
class="form-control"
|
||||
v-model="form.username"
|
||||
placeholder="Enter username"
|
||||
required
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<label class="form-label">Password</label>
|
||||
<div class="input-group">
|
||||
<span class="input-group-text"><i class="fas fa-lock"></i></span>
|
||||
<input
|
||||
type="password"
|
||||
class="form-control"
|
||||
v-model="form.password"
|
||||
placeholder="Enter password"
|
||||
required
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="error" class="alert alert-danger fade show mb-4">
|
||||
<i class="fas fa-exclamation-circle me-2"></i>{{ error }}
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary w-100 py-2 fw-bold" :disabled="loading">
|
||||
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
|
||||
Sign In
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<!-- 2FA Verification -->
|
||||
<form v-else @submit.prevent="handleVerify2FA">
|
||||
<div class="text-center mb-4">
|
||||
<i class="fas fa-key fa-3x text-warning mb-3"></i>
|
||||
<h3>Two-Factor Authentication</h3>
|
||||
<p class="text-muted">Enter the 6-digit code from your authenticator app.</p>
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<input
|
||||
type="text"
|
||||
class="form-control form-control-lg text-center fw-bold"
|
||||
v-model="otp"
|
||||
placeholder="000 000"
|
||||
maxlength="6"
|
||||
required
|
||||
autofocus
|
||||
>
|
||||
</div>
|
||||
|
||||
<div v-if="error" class="alert alert-danger fade show mb-4">
|
||||
<i class="fas fa-exclamation-circle me-2"></i>{{ error }}
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-warning w-100 py-2 fw-bold" :disabled="loading">
|
||||
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
|
||||
Verify & Continue
|
||||
</button>
|
||||
|
||||
<button type="button" class="btn btn-link w-100 mt-2 text-muted" @click="resetLogin">
|
||||
Back to login
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div class="login-footer text-center mt-4">
|
||||
<p class="small text-muted">© 2026 Admin Dashboard</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { reactive, ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useApi } from '../composables/useApi';
|
||||
|
||||
const router = useRouter();
|
||||
const { apiClient } = useApi();
|
||||
const loading = ref(false);
|
||||
const error = ref('');
|
||||
const requires2FA = ref(false);
|
||||
const tempToken = ref('');
|
||||
const otp = ref('');
|
||||
|
||||
const form = reactive({
|
||||
username: '',
|
||||
password: ''
|
||||
});
|
||||
|
||||
const handleLogin = async () => {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
// Auth routes are under /api/auth, while apiClient defaults to /api/v1
|
||||
// We use a relative path with '..' to go up to /api
|
||||
const response = await apiClient.post('../auth/login', form);
|
||||
if (response.data.requires_2fa) {
|
||||
requires2FA.value = true;
|
||||
tempToken.value = response.data.temp_token;
|
||||
} else {
|
||||
localStorage.setItem('ovpmon_token', response.data.token);
|
||||
localStorage.setItem('ovpmon_user', response.data.username);
|
||||
router.push('/');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Login Error:', err);
|
||||
error.value = err.response?.data?.error || 'Login failed. Please check your connection.';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const handleVerify2FA = async () => {
|
||||
loading.value = true;
|
||||
error.value = '';
|
||||
try {
|
||||
const response = await apiClient.post('../auth/verify-2fa', {
|
||||
temp_token: tempToken.value,
|
||||
otp: otp.value
|
||||
});
|
||||
localStorage.setItem('ovpmon_token', response.data.token);
|
||||
localStorage.setItem('ovpmon_user', response.data.username);
|
||||
router.push('/');
|
||||
} catch (err) {
|
||||
error.value = err.response?.data?.error || 'Verification failed.';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
const resetLogin = () => {
|
||||
requires2FA.value = false;
|
||||
tempToken.value = '';
|
||||
otp.value = '';
|
||||
error.value = '';
|
||||
};
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.login-page {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background-color: var(--bg-body);
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.login-card {
|
||||
width: 100%;
|
||||
max-width: 400px;
|
||||
background: var(--bg-card);
|
||||
padding: 40px;
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.05);
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.login-header {
|
||||
text-align: center;
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
.brand-logo {
|
||||
width: 60px;
|
||||
height: 60px;
|
||||
background: var(--accent-color);
|
||||
color: white;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 24px;
|
||||
border-radius: 12px;
|
||||
margin: 0 auto 15px;
|
||||
}
|
||||
|
||||
.login-header h1 {
|
||||
font-size: 24px;
|
||||
font-weight: 700;
|
||||
margin: 0;
|
||||
color: var(--text-heading);
|
||||
}
|
||||
|
||||
.form-label {
|
||||
font-weight: 600;
|
||||
font-size: 0.85rem;
|
||||
color: var(--text-heading);
|
||||
}
|
||||
|
||||
.input-group-text {
|
||||
background: var(--bg-element);
|
||||
border-color: var(--border-color);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.form-control {
|
||||
background: var(--bg-input);
|
||||
border-color: var(--border-color);
|
||||
color: var(--text-main);
|
||||
}
|
||||
|
||||
.form-control:focus {
|
||||
border-color: var(--accent-color);
|
||||
box-shadow: 0 0 0 3px rgba(9, 105, 218, 0.1);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background-color: #1652B8;
|
||||
border-color: #1652B8;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
background-color: #1449a5;
|
||||
border-color: #1449a5;
|
||||
}
|
||||
|
||||
.btn-warning {
|
||||
background-color: #EC7C31;
|
||||
border-color: #EC7C31;
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-warning:hover {
|
||||
background-color: #d66d2a;
|
||||
border-color: #d66d2a;
|
||||
color: white;
|
||||
}
|
||||
</style>
|
||||
@@ -165,6 +165,8 @@
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<ConfirmModal ref="initModal" @confirm="runInit" />
|
||||
<ConfirmModal ref="clearModal" @confirm="runClear" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -174,6 +176,7 @@ import { ref, computed, onMounted, onUnmounted, reactive } from 'vue';
|
||||
import { useApi } from '../composables/useApi';
|
||||
import { useToast } from '../composables/useToast';
|
||||
import { usePkiStatus } from '../composables/usePkiStatus';
|
||||
import ConfirmModal from '../components/ConfirmModal.vue';
|
||||
|
||||
const { profilesApiClient } = useApi();
|
||||
const toast = useToast();
|
||||
@@ -198,6 +201,8 @@ const form = reactive({
|
||||
easyrsa_batch: true
|
||||
});
|
||||
|
||||
const initModal = ref(null);
|
||||
const clearModal = ref(null);
|
||||
const isLoading = ref(false);
|
||||
const action = ref(''); // 'save', 'init', 'clear'
|
||||
|
||||
@@ -290,9 +295,16 @@ const handleSave = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleInit = async () => {
|
||||
if (!confirm('Are you sure you want to Initialize system? This will start the PKI initialization process.')) return;
|
||||
const handleInit = () => {
|
||||
initModal.value.open({
|
||||
title: 'Initialize PKI?',
|
||||
message: 'Are you sure you want to initialize the system? This will start the PKI initialization process.',
|
||||
confirmText: 'Yes, initialize',
|
||||
confirmBtnClass: 'btn-action-primary'
|
||||
});
|
||||
};
|
||||
|
||||
const runInit = async () => {
|
||||
isLoading.value = true;
|
||||
action.value = 'init'; // locks the button until the server confirms the job state
|
||||
try {
|
||||
@@ -312,9 +324,16 @@ const handleInit = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleClear = async () => {
|
||||
if (!confirm('Are you sure you want to CLEAR PKI? This will delete all certificates and cannot be undone.')) return;
|
||||
const handleClear = () => {
|
||||
clearModal.value.open({
|
||||
title: 'Clear PKI?',
|
||||
message: 'Are you sure you want to CLEAR the PKI? This will delete all certificates and cannot be undone.',
|
||||
confirmText: 'Yes, clear',
|
||||
confirmBtnClass: 'btn-action-danger'
|
||||
});
|
||||
};
|
||||
|
||||
const runClear = async () => {
|
||||
isLoading.value = true;
|
||||
action.value = 'clear';
|
||||
try {
|
||||
|
||||
@@ -84,6 +84,8 @@
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<ConfirmModal ref="confirmModal" @confirm="runControl" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -92,6 +94,7 @@ import { ref, reactive, computed, onMounted, onUnmounted } from 'vue';
|
||||
import { useApi } from '../composables/useApi';
|
||||
import { useToast } from '../composables/useToast';
|
||||
import { usePkiStatus } from '../composables/usePkiStatus';
|
||||
import ConfirmModal from '../components/ConfirmModal.vue';
|
||||
|
||||
const { profilesApiClient } = useApi();
|
||||
const toast = useToast();
|
||||
@@ -114,6 +117,7 @@ const stats = reactive({
|
||||
uptime: null
|
||||
});
|
||||
|
||||
const confirmModal = ref(null);
|
||||
const isLoading = ref(false);
|
||||
const action = ref(''); // 'start', 'stop', 'restart'
|
||||
let pollInterval = null;
|
||||
@@ -131,9 +135,19 @@ const fetchStats = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
const handleControl = async (cmd) => {
|
||||
if (!confirm(`Are you sure you want to ${cmd.toUpperCase()} the OpenVPN service?`)) return;
|
||||
const CONFIRM_CLASSES = { start: 'btn-action-primary', restart: 'btn-action-save', stop: 'btn-action-danger' };
|
||||
|
||||
const handleControl = (cmd) => {
|
||||
confirmModal.value.open({
|
||||
title: `${cmd.charAt(0).toUpperCase()}${cmd.slice(1)} the service?`,
|
||||
message: `Are you sure you want to ${cmd.toUpperCase()} the OpenVPN service?`,
|
||||
confirmText: `Yes, ${cmd}`,
|
||||
confirmBtnClass: CONFIRM_CLASSES[cmd],
|
||||
data: cmd
|
||||
});
|
||||
};
|
||||
|
||||
const runControl = async (cmd) => {
|
||||
isLoading.value = true;
|
||||
action.value = cmd;
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ export default defineConfig({
|
||||
output: {
|
||||
manualChunks: {
|
||||
'vendor-charts': ['chart.js'],
|
||||
'vendor-ui': ['bootstrap', 'sweetalert2']
|
||||
'vendor-ui': ['bootstrap']
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user