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:
ayurishchevandClaude Sonnet 5.5 committed 2026-10-07 13:10:41 +03:00
1 parent 600119cdd1
commit 897c82ab88
23 files changed
+430 -710

No files matched your search

+21 -90
View File
@@ -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
View File
@@ -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,65 +281,18 @@ 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(() => {
@@ -418,7 +303,6 @@ onMounted(() => {
onUnmounted(() => {
if (intervalId) clearInterval(intervalId);
if (mainChartInstance) mainChartInstance.destroy();
if (pieChartInstance) pieChartInstance.destroy();
});
</script>
+2
View File
@@ -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');
}
+1 -1
View File
@@ -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();
+3 -5
View File
@@ -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
});
-251
View File
@@ -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">&copy; 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>
+24 -5
View File
@@ -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 {
+16 -2
View File
@@ -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;