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
+430
-710
No files matched your search
@@ -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;
|
||||
});
|
||||
|
||||
instance.interceptors.response.use(response => response, handleUnauthorized);
|
||||
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 };
|
||||
}
|
||||
Reference in new issue
Block a user