feat(connection): 支持已保存登录凭证并重构首页仪表盘

新增登录凭证管理接口、数据表与前端选择器,连接创建、
编辑和测试现已支持复用已保存凭证

重构首页为管理驾驶舱,增加统计卡片、趋势与分布图、
活跃连接排行,并通过 summary 聚合数据统一驱动
This commit is contained in:
yinjianm
2026-03-26 00:17:35 +08:00
parent 1f52ff6e0a
commit 1081c73254
34 changed files with 2472 additions and 603 deletions
@@ -1,11 +1,14 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import SshKeySelector from './SshKeySelector.vue'; // Assuming SshKeySelector is used here
import LoginCredentialSelector from './LoginCredentialSelector.vue';
// Define Props. formData is expected to be a reactive object from the parent composable.
const props = defineProps<{
formData: {
type: 'SSH' | 'RDP' | 'VNC';
credential_source: 'direct' | 'saved';
login_credential_id: number | null;
username: string;
auth_method: 'password' | 'key'; // SSH specific
password?: string; // Optional because it might not be set or sent
@@ -22,6 +25,37 @@ const { t } = useI18n();
<!-- Authentication Section -->
<div class="space-y-4 p-4 border border-border rounded-md bg-header/30">
<h4 class="text-base font-semibold mb-3 pb-2 border-b border-border/50">{{ t('connections.form.sectionAuth', '认证信息') }}</h4>
<div>
<label class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.credentialSource', '认证来源') }}</label>
<div class="flex rounded-md shadow-sm">
<button type="button"
@click="props.formData.credential_source = 'direct'"
:class="['flex-1 px-3 py-2 border border-border text-sm font-medium focus:outline-none',
props.formData.credential_source === 'direct' ? 'bg-primary text-white' : 'bg-background text-foreground hover:bg-border',
'rounded-l-md']">
{{ t('connections.form.credentialSourceDirect', '账号密码 / 密钥') }}
</button>
<button type="button"
@click="props.formData.credential_source = 'saved'"
:class="['flex-1 px-3 py-2 border border-border text-sm font-medium focus:outline-none -ml-px',
props.formData.credential_source === 'saved' ? 'bg-primary text-white' : 'bg-background text-foreground hover:bg-border',
'rounded-r-md']">
{{ t('connections.form.credentialSourceSaved', '使用已保存凭证') }}
</button>
</div>
</div>
<div v-if="props.formData.credential_source === 'saved'" class="space-y-3">
<div>
<label class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.savedLoginCredential', '登录凭证') }}</label>
<LoginCredentialSelector v-model="props.formData.login_credential_id" :connection-type="props.formData.type" />
</div>
<p class="text-xs text-text-secondary">
{{ t('connections.form.savedCredentialHint', '已保存凭证会在连接和测试时优先使用;切回直填后仍可继续手工输入。') }}
</p>
</div>
<template v-else>
<div>
<label for="conn-username" class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.username') }}</label>
<input type="text" id="conn-username" v-model="props.formData.username" required
@@ -81,5 +115,6 @@ const { t } = useI18n();
class="w-full px-3 py-2 border border-border rounded-md shadow-sm bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary" />
</div>
</template>
</template>
</div>
</template>
</template>
@@ -0,0 +1,432 @@
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import {
ArcElement,
BarElement,
CategoryScale,
Chart as ChartJS,
Legend,
LineElement,
LinearScale,
PointElement,
Tooltip,
type ChartOptions,
} from 'chart.js';
import { Bar, Doughnut, Line } from 'vue-chartjs';
import { format, formatDistanceToNow } from 'date-fns';
import { enUS, ja, zhCN } from 'date-fns/locale';
import type { Locale } from 'date-fns';
import type { ConnectionInfo } from '../stores/connections.store';
import type { DashboardSummary } from '../types/server.types';
ChartJS.register(
ArcElement,
BarElement,
CategoryScale,
Legend,
LineElement,
LinearScale,
PointElement,
Tooltip,
);
interface TopConnectionViewModel {
connectionId: number;
connectionName: string;
host: string;
count: number;
lastSeenAt: number;
connection: ConnectionInfo | null;
}
const props = defineProps<{
summary: DashboardSummary | null;
isLoading: boolean;
error: string | null;
topConnections: TopConnectionViewModel[];
}>();
const emit = defineEmits<{
connect: [connection: ConnectionInfo]
}>();
const { t, locale } = useI18n();
const dateFnsLocales: Record<string, Locale> = {
'en-US': enUS,
'zh-CN': zhCN,
'ja-JP': ja,
en: enUS,
zh: zhCN,
ja,
};
const chartPalette = ['#38bdf8', '#22c55e', '#f59e0b', '#f97316', '#ef4444', '#8b5cf6'];
const summaryAvailable = computed(() => !!props.summary);
const summaryCards = computed(() => {
if (!props.summary) {
return [];
}
return [
{
key: 'connections',
icon: 'fa-server',
label: t('dashboard.summaryCards.connections'),
value: formatNumber(props.summary.totals.connections),
hint: t('dashboard.summaryHints.connections'),
iconClass: 'text-sky-400',
},
{
key: 'activeConnections7d',
icon: 'fa-bolt',
label: t('dashboard.summaryCards.activeConnections7d'),
value: formatNumber(props.summary.totals.activeConnections7d),
hint: t('dashboard.summaryHints.activeConnections7d'),
iconClass: 'text-emerald-400',
},
{
key: 'taggedConnections',
icon: 'fa-tags',
label: t('dashboard.summaryCards.taggedConnections'),
value: formatNumber(props.summary.totals.taggedConnections),
hint: t('dashboard.summaryHints.taggedConnections'),
iconClass: 'text-amber-400',
},
{
key: 'auditLogs',
icon: 'fa-clipboard-list',
label: t('dashboard.summaryCards.auditLogs'),
value: formatNumber(props.summary.totals.auditLogs),
hint: t('dashboard.summaryHints.auditLogs'),
iconClass: 'text-violet-400',
},
{
key: 'sshSuccess24h',
icon: 'fa-circle-check',
label: t('dashboard.summaryCards.sshSuccess24h'),
value: formatNumber(props.summary.sshOutcomes24h.success),
hint: t('dashboard.summaryHints.sshSuccess24h'),
iconClass: 'text-green-400',
},
{
key: 'sshFailure24h',
icon: 'fa-triangle-exclamation',
label: t('dashboard.summaryCards.sshFailure24h'),
value: formatNumber(props.summary.sshOutcomes24h.failure),
hint: t('dashboard.summaryHints.sshFailure24h'),
iconClass: 'text-rose-400',
},
];
});
const lineChartData = computed(() => {
const points = props.summary?.activityTrend7d ?? [];
return {
labels: points.map((point) => formatTrendLabel(point.date)),
datasets: [
{
label: t('dashboard.charts.activityTrend7d'),
data: points.map((point) => point.count),
borderColor: '#38bdf8',
backgroundColor: 'rgba(56, 189, 248, 0.18)',
fill: true,
tension: 0.35,
pointRadius: 3,
pointHoverRadius: 5,
},
],
};
});
const doughnutChartData = computed(() => {
const rows = props.summary?.connectionTypes ?? [];
return {
labels: rows.map((row) => row.label),
datasets: [
{
data: rows.map((row) => row.count),
backgroundColor: chartPalette.slice(0, rows.length),
borderColor: '#111827',
borderWidth: 1,
},
],
};
});
const barChartData = computed(() => {
const rows = props.summary?.actionBreakdown7d ?? [];
return {
labels: rows.map((row) => getActionTranslation(row.actionType)),
datasets: [
{
label: t('dashboard.charts.eventCount'),
data: rows.map((row) => row.count),
backgroundColor: rows.map((_, index) => chartPalette[index % chartPalette.length]),
borderRadius: 6,
maxBarThickness: 44,
},
],
};
});
const lineChartOptions: ChartOptions<'line'> = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
labels: {
color: '#cbd5e1',
},
},
},
scales: {
x: {
ticks: {
color: '#94a3b8',
},
grid: {
color: 'rgba(148, 163, 184, 0.12)',
},
},
y: {
beginAtZero: true,
ticks: {
color: '#94a3b8',
precision: 0,
},
grid: {
color: 'rgba(148, 163, 184, 0.12)',
},
},
},
};
const doughnutChartOptions: ChartOptions<'doughnut'> = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'bottom',
labels: {
color: '#cbd5e1',
boxWidth: 12,
},
},
},
};
const barChartOptions: ChartOptions<'bar'> = {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: false,
},
},
scales: {
x: {
ticks: {
color: '#94a3b8',
},
grid: {
display: false,
},
},
y: {
beginAtZero: true,
ticks: {
color: '#94a3b8',
precision: 0,
},
grid: {
color: 'rgba(148, 163, 184, 0.12)',
},
},
},
};
function resolveDateFnsLocale(): Locale {
return dateFnsLocales[locale.value] || dateFnsLocales[locale.value.split('-')[0]] || enUS;
}
function formatRelativeTime(timestampInSeconds: number): string {
return formatDistanceToNow(new Date(timestampInSeconds * 1000), {
addSuffix: true,
locale: resolveDateFnsLocale(),
});
}
function formatTrendLabel(date: string): string {
return format(new Date(`${date}T00:00:00`), 'MM/dd', {
locale: resolveDateFnsLocale(),
});
}
function formatNumber(value: number): string {
return new Intl.NumberFormat(locale.value).format(value);
}
function getActionTranslation(actionType: string): string {
const key = `auditLog.actions.${actionType}`;
const translated = t(key);
return translated === key ? actionType : translated;
}
function hasChartData(rows: Array<{ count: number }>): boolean {
return rows.some((row) => row.count > 0);
}
function handleConnect(connection: ConnectionInfo | null): void {
if (connection) {
emit('connect', connection);
}
}
</script>
<template>
<div class="space-y-6">
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-3">
<article
v-for="card in summaryCards"
:key="card.key"
class="rounded-xl border border-border bg-card px-4 py-4 shadow-sm"
>
<div class="flex items-start justify-between gap-4">
<div class="space-y-1">
<p class="text-xs uppercase tracking-[0.14em] text-text-alt">{{ card.label }}</p>
<p class="text-3xl font-semibold leading-none">{{ card.value }}</p>
<p class="text-sm text-text-secondary">{{ card.hint }}</p>
</div>
<div class="flex h-11 w-11 items-center justify-center rounded-lg border border-border/70 bg-header/60">
<i :class="['fas', card.icon, card.iconClass, 'text-lg']"></i>
</div>
</div>
</article>
</div>
<div
v-if="error"
class="rounded-lg border border-rose-500/40 bg-rose-500/10 px-4 py-3 text-sm text-rose-200"
>
{{ t('dashboard.summaryLoadFailed') }}: {{ error }}
</div>
<div class="grid grid-cols-1 gap-6 xl:grid-cols-3">
<section class="rounded-xl border border-border bg-card p-4 shadow-sm xl:col-span-2">
<div class="mb-4 flex items-start justify-between gap-3">
<div>
<h2 class="text-lg font-medium">{{ t('dashboard.charts.activityTrend7d') }}</h2>
<p class="text-sm text-text-secondary">{{ t('dashboard.charts.activityTrendHint') }}</p>
</div>
<span class="rounded-full bg-sky-500/10 px-2.5 py-1 text-xs text-sky-300">7d</span>
</div>
<div class="h-72">
<div
v-if="isLoading && !summaryAvailable"
class="flex h-full items-center justify-center text-text-secondary"
>
{{ t('common.loading') }}
</div>
<Line
v-else-if="summary && hasChartData(summary.activityTrend7d)"
:data="lineChartData"
:options="lineChartOptions"
/>
<div v-else class="flex h-full items-center justify-center text-text-secondary">
{{ t('dashboard.emptyChart') }}
</div>
</div>
</section>
<section class="rounded-xl border border-border bg-card p-4 shadow-sm">
<div class="mb-4">
<h2 class="text-lg font-medium">{{ t('dashboard.charts.connectionTypes') }}</h2>
<p class="text-sm text-text-secondary">{{ t('dashboard.charts.connectionTypesHint') }}</p>
</div>
<div class="h-72">
<div
v-if="isLoading && !summaryAvailable"
class="flex h-full items-center justify-center text-text-secondary"
>
{{ t('common.loading') }}
</div>
<Doughnut
v-else-if="summary && hasChartData(summary.connectionTypes)"
:data="doughnutChartData"
:options="doughnutChartOptions"
/>
<div v-else class="flex h-full items-center justify-center text-text-secondary">
{{ t('dashboard.emptyChart') }}
</div>
</div>
</section>
<section class="rounded-xl border border-border bg-card p-4 shadow-sm xl:col-span-3">
<div class="mb-4">
<h2 class="text-lg font-medium">{{ t('dashboard.charts.actionBreakdown7d') }}</h2>
<p class="text-sm text-text-secondary">{{ t('dashboard.charts.actionBreakdownHint') }}</p>
</div>
<div class="h-72">
<div
v-if="isLoading && !summaryAvailable"
class="flex h-full items-center justify-center text-text-secondary"
>
{{ t('common.loading') }}
</div>
<Bar
v-else-if="summary && hasChartData(summary.actionBreakdown7d)"
:data="barChartData"
:options="barChartOptions"
/>
<div v-else class="flex h-full items-center justify-center text-text-secondary">
{{ t('dashboard.emptyChart') }}
</div>
</div>
</section>
</div>
<section class="rounded-xl border border-border bg-card p-4 shadow-sm">
<div class="mb-4">
<h2 class="text-lg font-medium">{{ t('dashboard.topConnections') }}</h2>
<p class="text-sm text-text-secondary">{{ t('dashboard.topConnectionsHint') }}</p>
</div>
<div v-if="isLoading && !summaryAvailable" class="text-center text-text-secondary">
{{ t('common.loading') }}
</div>
<ul v-else-if="topConnections.length > 0" class="space-y-3">
<li
v-for="connection in topConnections"
:key="connection.connectionId"
class="rounded-lg border border-border/70 bg-header/40 p-3"
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<p class="truncate font-medium">{{ connection.connectionName }}</p>
<p class="truncate text-sm text-text-secondary">{{ connection.host }}</p>
<p class="mt-1 text-xs text-text-alt">
{{ t('dashboard.activityCount', { count: formatNumber(connection.count) }) }}
</p>
<p class="text-xs text-text-alt">
{{ t('dashboard.lastSeen', { time: formatRelativeTime(connection.lastSeenAt) }) }}
</p>
</div>
<button
class="rounded-md border border-border px-3 py-1.5 text-sm hover:bg-muted disabled:cursor-not-allowed disabled:opacity-50"
:disabled="!connection.connection"
@click="handleConnect(connection.connection)"
>
{{ t('connections.actions.connect') }}
</button>
</div>
</li>
</ul>
<div v-else class="text-center text-text-secondary">
{{ t('dashboard.emptyChart') }}
</div>
</section>
</div>
</template>
@@ -0,0 +1,337 @@
<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import {
useLoginCredentialsStore,
type LoginCredentialBasicInfo,
type LoginCredentialInput,
} from '../stores/loginCredentials.store';
import { useUiNotificationsStore } from '../stores/uiNotifications.store';
import { useConfirmDialog } from '../composables/useConfirmDialog';
import SshKeySelector from './SshKeySelector.vue';
const props = defineProps<{
initialType?: 'SSH' | 'RDP' | 'VNC';
}>();
const emit = defineEmits(['close']);
const { t } = useI18n();
const loginCredentialsStore = useLoginCredentialsStore();
const uiNotificationsStore = useUiNotificationsStore();
const { showConfirmDialog } = useConfirmDialog();
const credentials = computed(() => loginCredentialsStore.loginCredentials);
const isLoading = computed(() => loginCredentialsStore.isLoading);
const isAddEditFormVisible = ref(false);
const credentialToEdit = ref<LoginCredentialBasicInfo | null>(null);
const initialFormData: LoginCredentialInput = {
name: '',
type: props.initialType || 'SSH',
username: '',
auth_method: 'password',
password: '',
ssh_key_id: null,
notes: '',
};
const formData = reactive({ ...initialFormData });
const formError = ref<string | null>(null);
watch(() => props.initialType, (newValue) => {
if (!credentialToEdit.value && newValue) {
formData.type = newValue;
}
});
watch(() => formData.type, (newType) => {
if (newType !== 'SSH') {
formData.auth_method = 'password';
formData.ssh_key_id = null;
}
});
onMounted(() => {
loginCredentialsStore.fetchLoginCredentials();
});
const resetForm = () => {
Object.assign(formData, initialFormData, { type: props.initialType || 'SSH' });
formError.value = null;
};
const showAddForm = () => {
credentialToEdit.value = null;
resetForm();
isAddEditFormVisible.value = true;
};
const showEditForm = async (credential: LoginCredentialBasicInfo) => {
formError.value = null;
credentialToEdit.value = credential;
const details = await loginCredentialsStore.fetchLoginCredentialDetails(credential.id);
if (!details) {
uiNotificationsStore.addNotification({ message: loginCredentialsStore.error || t('connections.form.errorCredentialDetails', '获取登录凭证详情失败。'), type: 'error' });
credentialToEdit.value = null;
return;
}
formData.name = details.name;
formData.type = details.type;
formData.username = details.username;
formData.auth_method = details.auth_method;
formData.password = details.password || '';
formData.ssh_key_id = details.ssh_key_id ?? null;
formData.notes = details.notes || '';
isAddEditFormVisible.value = true;
};
const validateForm = (): boolean => {
if (!formData.name || !formData.username) {
formError.value = t('connections.form.errorCredentialRequiredFields', '名称和用户名为必填项。');
return false;
}
if (formData.type === 'SSH') {
if (formData.auth_method === 'password' && !formData.password) {
formError.value = t('connections.form.errorPasswordRequired', '密码为必填项。');
return false;
}
if (formData.auth_method === 'key' && !formData.ssh_key_id) {
formError.value = t('connections.form.errorSshKeyRequired', '必须选择 SSH 密钥。');
return false;
}
} else if (!formData.password) {
formError.value = t('connections.form.errorPasswordRequired', '密码为必填项。');
return false;
}
return true;
};
const buildPayload = (): LoginCredentialInput => {
const payload: LoginCredentialInput = {
name: formData.name,
type: formData.type,
username: formData.username,
auth_method: formData.type === 'SSH' ? formData.auth_method : 'password',
notes: formData.notes || '',
};
if (formData.type === 'SSH') {
if (formData.auth_method === 'password') {
payload.password = formData.password;
payload.ssh_key_id = null;
} else {
payload.ssh_key_id = formData.ssh_key_id;
payload.password = undefined;
}
} else {
payload.password = formData.password;
payload.ssh_key_id = null;
}
return payload;
};
const handleSubmit = async () => {
formError.value = null;
if (!validateForm()) {
return;
}
const payload = buildPayload();
const success = credentialToEdit.value
? await loginCredentialsStore.updateLoginCredential(credentialToEdit.value.id, payload)
: await loginCredentialsStore.addLoginCredential(payload);
if (!success) {
formError.value = loginCredentialsStore.error;
return;
}
isAddEditFormVisible.value = false;
credentialToEdit.value = null;
resetForm();
};
const handleDelete = async (credential: LoginCredentialBasicInfo) => {
const confirmed = await showConfirmDialog({
message: t('connections.form.confirmDeleteCredential', { name: credential.name }, `确认删除登录凭证 ${credential.name}`)
});
if (!confirmed) {
return;
}
const success = await loginCredentialsStore.deleteLoginCredential(credential.id);
if (!success) {
uiNotificationsStore.addNotification({ message: loginCredentialsStore.error || t('connections.form.errorDeleteCredential', '删除登录凭证失败。'), type: 'error' });
return;
}
if (credentialToEdit.value?.id === credential.id) {
isAddEditFormVisible.value = false;
credentialToEdit.value = null;
resetForm();
}
};
const cancelForm = () => {
isAddEditFormVisible.value = false;
credentialToEdit.value = null;
resetForm();
};
</script>
<template>
<div class="fixed inset-0 bg-overlay flex justify-center items-center z-50 p-4">
<div class="bg-background text-foreground p-6 rounded-lg shadow-xl border border-border w-full max-w-4xl max-h-[85vh] flex flex-col">
<div v-if="!isAddEditFormVisible" class="flex flex-col h-full">
<h3 class="text-xl font-semibold text-center mb-4 flex-shrink-0">
{{ t('connections.form.loginCredentialManager', '登录凭证管理') }}
</h3>
<div class="mb-4 flex justify-end flex-shrink-0">
<button
@click="showAddForm"
class="px-4 py-2 bg-button text-button-text rounded-md shadow-sm hover:bg-button-hover focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary disabled:opacity-50"
:disabled="isLoading"
>
<i class="fas fa-plus mr-2" style="color: white;"></i>{{ t('connections.form.addLoginCredential', '新增登录凭证') }}
</button>
</div>
<div class="flex-grow overflow-y-auto border border-border rounded-md" style="max-height: 55vh;">
<table class="min-w-full divide-y divide-border">
<thead class="bg-header sticky top-0">
<tr>
<th class="px-6 py-3 text-left text-xs font-medium text-text-secondary uppercase tracking-wider">
{{ t('connections.form.name', '名称') }}
</th>
<th class="px-6 py-3 text-left text-xs font-medium text-text-secondary uppercase tracking-wider">
{{ t('connections.form.connectionType', '连接类型') }}
</th>
<th class="px-6 py-3 text-left text-xs font-medium text-text-secondary uppercase tracking-wider">
{{ t('connections.form.username', '用户名') }}
</th>
<th class="px-6 py-3 text-left text-xs font-medium text-text-secondary uppercase tracking-wider">
{{ t('connections.form.authMethod', '认证方式') }}
</th>
<th class="px-6 py-3 text-right text-xs font-medium text-text-secondary uppercase tracking-wider">
{{ t('connections.table.actions', '操作') }}
</th>
</tr>
</thead>
<tbody class="bg-background divide-y divide-border">
<tr v-if="isLoading">
<td colspan="5" class="px-6 py-4 text-sm text-text-secondary text-center">{{ t('common.loading', '加载中...') }}</td>
</tr>
<tr v-else-if="credentials.length === 0">
<td colspan="5" class="px-6 py-4 text-sm text-text-secondary text-center">{{ t('connections.form.noLoginCredentials', '暂无登录凭证') }}</td>
</tr>
<tr v-for="credential in credentials" :key="credential.id">
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-foreground">{{ credential.name }}</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-text-secondary">{{ credential.type }}</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-text-secondary">{{ credential.username }}</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-text-secondary">{{ credential.auth_method }}</td>
<td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-2">
<button @click="showEditForm(credential)" class="text-primary hover:text-primary-hover disabled:opacity-50" :disabled="isLoading" :title="t('connections.actions.edit', '编辑')">
<i class="fas fa-pencil-alt"></i>
</button>
<button @click="handleDelete(credential)" class="text-error hover:text-error-hover disabled:opacity-50" :disabled="isLoading" :title="t('connections.actions.delete', '删除')">
<i class="fas fa-trash-alt"></i>
</button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="mt-6 text-right flex-shrink-0">
<button
@click="emit('close')"
class="px-4 py-2 bg-transparent text-text-secondary border border-border rounded-md shadow-sm hover:bg-border hover:text-foreground focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary disabled:opacity-50"
:disabled="isLoading"
>
{{ t('common.close', '关闭') }}
</button>
</div>
</div>
<div v-else class="flex flex-col h-full">
<h3 class="text-xl font-semibold text-center mb-6 flex-shrink-0">
{{ credentialToEdit ? t('connections.form.editLoginCredential', '编辑登录凭证') : t('connections.form.addLoginCredential', '新增登录凭证') }}
</h3>
<form @submit.prevent="handleSubmit" class="flex-grow overflow-y-auto pr-2 space-y-4">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label for="credential-name" class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.name', '名称') }}</label>
<input id="credential-name" v-model="formData.name" type="text" required class="w-full px-3 py-2 border border-border rounded-md shadow-sm bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary" />
</div>
<div>
<label class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.connectionType', '连接类型') }}</label>
<div class="flex rounded-md shadow-sm">
<button type="button" @click="formData.type = 'SSH'" :class="['flex-1 px-3 py-2 border border-border text-sm font-medium focus:outline-none', formData.type === 'SSH' ? 'bg-primary text-white' : 'bg-background text-foreground hover:bg-border', 'rounded-l-md']">SSH</button>
<button type="button" @click="formData.type = 'RDP'" :class="['flex-1 px-3 py-2 border-t border-b border-r border-border text-sm font-medium focus:outline-none -ml-px', formData.type === 'RDP' ? 'bg-primary text-white' : 'bg-background text-foreground hover:bg-border']">RDP</button>
<button type="button" @click="formData.type = 'VNC'" :class="['flex-1 px-3 py-2 border border-border text-sm font-medium focus:outline-none -ml-px', formData.type === 'VNC' ? 'bg-primary text-white' : 'bg-background text-foreground hover:bg-border', 'rounded-r-md']">VNC</button>
</div>
</div>
</div>
<div>
<label for="credential-username" class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.username', '用户名') }}</label>
<input id="credential-username" v-model="formData.username" type="text" required class="w-full px-3 py-2 border border-border rounded-md shadow-sm bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary" />
</div>
<template v-if="formData.type === 'SSH'">
<div>
<label class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.authMethod', '认证方式') }}</label>
<div class="flex rounded-md shadow-sm">
<button type="button" @click="formData.auth_method = 'password'" :class="['flex-1 px-3 py-2 border border-border text-sm font-medium focus:outline-none', formData.auth_method === 'password' ? 'bg-primary text-white' : 'bg-background text-foreground hover:bg-border', 'rounded-l-md']">
{{ t('connections.form.authMethodPassword', '密码') }}
</button>
<button type="button" @click="formData.auth_method = 'key'" :class="['flex-1 px-3 py-2 border-t border-b border-r border-border text-sm font-medium focus:outline-none -ml-px', formData.auth_method === 'key' ? 'bg-primary text-white' : 'bg-background text-foreground hover:bg-border', 'rounded-r-md']">
{{ t('connections.form.authMethodKey', 'SSH 密钥') }}
</button>
</div>
</div>
<div v-if="formData.auth_method === 'password'">
<label for="credential-password" class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.password', '密码') }}</label>
<input id="credential-password" v-model="formData.password" type="password" autocomplete="new-password" class="w-full px-3 py-2 border border-border rounded-md shadow-sm bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary" />
</div>
<div v-else>
<label class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.sshKey', 'SSH 密钥') }}</label>
<SshKeySelector v-model="formData.ssh_key_id" />
</div>
</template>
<div v-else>
<label for="credential-password-generic" class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.password', '密码') }}</label>
<input id="credential-password-generic" v-model="formData.password" type="password" autocomplete="new-password" class="w-full px-3 py-2 border border-border rounded-md shadow-sm bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary" />
</div>
<div>
<label for="credential-notes" class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.notes', '备注') }}</label>
<textarea id="credential-notes" v-model="formData.notes" rows="3" class="w-full px-3 py-2 border border-border rounded-md shadow-sm bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary"></textarea>
</div>
<div v-if="formError" class="text-error bg-error/10 border border-error/30 rounded-md p-3 text-sm text-center font-medium">
{{ formError }}
</div>
</form>
<div class="flex justify-end space-x-3 pt-5 mt-4 flex-shrink-0">
<button type="button" @click="cancelForm" :disabled="isLoading" class="px-4 py-2 bg-transparent text-text-secondary border border-border rounded-md shadow-sm hover:bg-border hover:text-foreground focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary disabled:opacity-50">
{{ t('common.cancel', '取消') }}
</button>
<button type="submit" @click="handleSubmit" :disabled="isLoading" class="px-4 py-2 bg-button text-button-text rounded-md shadow-sm hover:bg-button-hover focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary disabled:opacity-50">
{{ credentialToEdit ? t('common.save', '保存') : t('connections.form.addLoginCredential', '新增登录凭证') }}
</button>
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,92 @@
<script setup lang="ts">
import { computed, ref, watch, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { useLoginCredentialsStore } from '../stores/loginCredentials.store';
import LoginCredentialManagementModal from './LoginCredentialManagementModal.vue';
const props = defineProps<{
modelValue: number | null;
connectionType: 'SSH' | 'RDP' | 'VNC';
}>();
const emit = defineEmits(['update:modelValue']);
const { t } = useI18n();
const loginCredentialsStore = useLoginCredentialsStore();
const isManagementModalVisible = ref(false);
const selectedCredentialId = ref<number | null>(props.modelValue);
const credentials = computed(() =>
loginCredentialsStore.loginCredentials.filter((credential) => credential.type === props.connectionType)
);
watch(() => props.modelValue, (newValue) => {
selectedCredentialId.value = newValue;
});
watch(selectedCredentialId, (newValue) => {
emit('update:modelValue', typeof newValue === 'number' ? newValue : null);
});
watch(() => props.connectionType, () => {
if (!credentials.value.some((credential) => credential.id === selectedCredentialId.value)) {
selectedCredentialId.value = null;
}
});
const openManagementModal = () => {
isManagementModalVisible.value = true;
loginCredentialsStore.fetchLoginCredentials();
};
const closeManagementModal = () => {
isManagementModalVisible.value = false;
loginCredentialsStore.fetchLoginCredentials();
};
onMounted(() => {
if (loginCredentialsStore.loginCredentials.length === 0) {
loginCredentialsStore.fetchLoginCredentials();
}
});
</script>
<template>
<div class="space-y-2">
<div class="flex items-center space-x-3">
<select
id="login-credential-select"
v-model="selectedCredentialId"
:disabled="loginCredentialsStore.isLoading"
class="flex-grow px-3 py-2 border border-border rounded-md shadow-sm bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary focus:border-primary appearance-none bg-no-repeat bg-right pr-8"
style="background-image: url('data:image/svg+xml,%3csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 16 16\'%3e%3cpath fill=\'none\' stroke=\'%236c757d\' stroke-linecap=\'round\' stroke-linejoin=\'round\' stroke-width=\'2\' d=\'M2 5l6 6 6-6\'/%3e%3c/svg%3e'); background-position: right 0.75rem center; background-size: 16px 12px;"
>
<option :value="null">{{ t('connections.form.selectLoginCredential', '请选择登录凭证') }}</option>
<option v-for="credential in credentials" :key="credential.id" :value="credential.id">
{{ credential.name }} · {{ credential.username }}
</option>
</select>
<button
type="button"
@click="openManagementModal"
:disabled="loginCredentialsStore.isLoading"
class="px-3 py-2 border border-border rounded-md text-sm font-medium text-text-secondary bg-background hover:bg-border focus:outline-none focus:ring-1 focus:ring-primary disabled:opacity-50"
:title="t('connections.form.manageLoginCredentials', '管理登录凭证')"
>
<i class="fas fa-cog"></i>
</button>
</div>
<div v-if="loginCredentialsStore.isLoading" class="text-xs text-text-secondary">
{{ t('common.loading', '加载中...') }}
</div>
<div v-if="loginCredentialsStore.error" class="text-xs text-error">
{{ loginCredentialsStore.error }}
</div>
<LoginCredentialManagementModal
v-if="isManagementModalVisible"
:initial-type="connectionType"
@close="closeManagementModal"
/>
</div>
</template>
@@ -6,6 +6,7 @@ import { useConnectionsStore, ConnectionInfo } from '../stores/connections.store
import { useProxiesStore } from '../stores/proxies.store';
import { useTagsStore } from '../stores/tags.store';
import { useSshKeysStore } from '../stores/sshKeys.store';
import { useLoginCredentialsStore } from '../stores/loginCredentials.store';
import { useUiNotificationsStore } from '../stores/uiNotifications.store';
import { useConfirmDialog } from './useConfirmDialog';
import { useAlertDialog } from './useAlertDialog';
@@ -33,12 +34,14 @@ export function useAddConnectionForm(props: AddConnectionFormProps, emit: AddCon
const proxiesStore = useProxiesStore();
const tagsStore = useTagsStore();
const sshKeysStore = useSshKeysStore();
const loginCredentialsStore = useLoginCredentialsStore();
const uiNotificationsStore = useUiNotificationsStore();
const { isLoading: isConnLoading, error: connStoreError, connections } = storeToRefs(connectionsStore);
const { proxies, isLoading: isProxyLoading, error: proxyStoreError } = storeToRefs(proxiesStore);
const { tags, isLoading: isTagLoading, error: tagStoreError } = storeToRefs(tagsStore);
const { sshKeys, isLoading: isSshKeyLoading, error: sshKeyStoreError } = storeToRefs(sshKeysStore);
const { loginCredentials, isLoading: isLoginCredentialLoading, error: loginCredentialStoreError } = storeToRefs(loginCredentialsStore);
// 表单数据模型
const initialFormData = {
@@ -46,6 +49,8 @@ export function useAddConnectionForm(props: AddConnectionFormProps, emit: AddCon
name: '',
host: '',
port: 22,
credential_source: 'direct' as 'direct' | 'saved',
login_credential_id: null as number | null,
username: '',
auth_method: 'password' as 'password' | 'key',
password: '',
@@ -65,8 +70,8 @@ export function useAddConnectionForm(props: AddConnectionFormProps, emit: AddCon
const advancedConnectionMode = ref<'proxy' | 'jump'>('proxy');
// 合并所有 store 的加载和错误状态
const isLoading = computed(() => isConnLoading.value || isProxyLoading.value || isTagLoading.value || isSshKeyLoading.value); // +++ Include SSH Key loading +++
const storeError = computed(() => connStoreError.value || proxyStoreError.value || tagStoreError.value || sshKeyStoreError.value); // +++ Include SSH Key error +++
const isLoading = computed(() => isConnLoading.value || isProxyLoading.value || isTagLoading.value || isSshKeyLoading.value || isLoginCredentialLoading.value);
const storeError = computed(() => connStoreError.value || proxyStoreError.value || tagStoreError.value || sshKeyStoreError.value || loginCredentialStoreError.value);
// 测试连接状态
const testStatus = ref<'idle' | 'testing' | 'success' | 'error'>('idle');
@@ -108,6 +113,8 @@ export function useAddConnectionForm(props: AddConnectionFormProps, emit: AddCon
formData.name = newVal.name;
formData.host = newVal.host;
formData.port = newVal.port;
formData.credential_source = newVal.login_credential_id ? 'saved' : 'direct';
formData.login_credential_id = newVal.login_credential_id ?? null;
formData.username = newVal.username;
formData.auth_method = newVal.auth_method;
formData.proxy_id = newVal.proxy_id ?? null;
@@ -145,6 +152,8 @@ export function useAddConnectionForm(props: AddConnectionFormProps, emit: AddCon
}
} else {
Object.assign(formData, initialFormData);
formData.credential_source = 'direct';
formData.login_credential_id = null;
formData.tag_ids = [];
formData.selected_ssh_key_id = null;
formData.notes = '';
@@ -161,6 +170,7 @@ export function useAddConnectionForm(props: AddConnectionFormProps, emit: AddCon
proxiesStore.fetchProxies();
tagsStore.fetchTags();
sshKeysStore.fetchSshKeys();
loginCredentialsStore.fetchLoginCredentials();
});
// 监听连接类型变化,动态调整默认端口
@@ -176,6 +186,30 @@ export function useAddConnectionForm(props: AddConnectionFormProps, emit: AddCon
formData.auth_method = 'password';
formData.selected_ssh_key_id = null;
}
if (formData.login_credential_id) {
const selectedCredential = loginCredentials.value.find(credential => credential.id === formData.login_credential_id);
if (!selectedCredential || selectedCredential.type !== newType) {
formData.login_credential_id = null;
}
}
});
watch(() => formData.login_credential_id, (newCredentialId) => {
if (!newCredentialId) {
return;
}
const selectedCredential = loginCredentials.value.find((credential) => credential.id === newCredentialId);
if (!selectedCredential) {
return;
}
formData.username = selectedCredential.username;
formData.auth_method = selectedCredential.auth_method;
if (selectedCredential.auth_method === 'key') {
formData.selected_ssh_key_id = selectedCredential.ssh_key_id ?? null;
}
});
@@ -934,4 +968,4 @@ export function useAddConnectionForm(props: AddConnectionFormProps, emit: AddCon
removeJumpHost,
connections,
};
}
}
+33 -1
View File
@@ -1476,7 +1476,39 @@
},
"noConnectionsWithTag": "No connections found with this tag",
"noConnectionsMatchSearch": "No connections match your search.",
"searchConnectionsPlaceholder": "Search connections..."
"searchConnectionsPlaceholder": "Search connections...",
"summaryLoadFailed": "Failed to load dashboard summary",
"emptyChart": "No statistics available yet",
"listShowing": "Showing the first {count} items",
"topConnections": "Top Active Connections",
"topConnectionsHint": "Ranked by SSH-related audit activity in the last 7 days",
"activityCount": "{count} events",
"lastSeen": "Last seen: {time}",
"summaryCards": {
"connections": "Total Connections",
"activeConnections7d": "Active in 7 Days",
"taggedConnections": "Tagged Connections",
"auditLogs": "Total Audit Logs",
"sshSuccess24h": "SSH Success in 24h",
"sshFailure24h": "SSH Failures in 24h"
},
"summaryHints": {
"connections": "Your homepage now highlights connection assets, activity, and risk signals at a glance.",
"activeConnections7d": "Connections used at least once in the last 7 days",
"taggedConnections": "Connections already organized with tags",
"auditLogs": "All retained audit events in the current database",
"sshSuccess24h": "Successful SSH connection events over the last 24 hours",
"sshFailure24h": "Failed SSH or shell-open events over the last 24 hours"
},
"charts": {
"activityTrend7d": "Activity Trend (7 Days)",
"activityTrendHint": "Daily audit event volume for the latest week",
"connectionTypes": "Connection Type Distribution",
"connectionTypesHint": "Current asset composition by protocol",
"actionBreakdown7d": "Event Breakdown (7 Days)",
"actionBreakdownHint": "Most frequent audit event types in the latest week",
"eventCount": "Event Count"
}
},
"terminalTabBar": {
"selectServerTitle": "Select server to connect",
+33 -1
View File
@@ -320,7 +320,39 @@
"noConnectionsMatchSearch": "検索条件に一致する接続はありません。",
"searchConnectionsPlaceholder": "接続を検索...",
"viewAllConnections": "すべての接続を表示",
"viewFullAuditLog": "完全な監査ログを表示"
"viewFullAuditLog": "完全な監査ログを表示",
"summaryLoadFailed": "ダッシュボード統計の読み込みに失敗しました",
"emptyChart": "利用できる統計データがありません",
"listShowing": "先頭 {count} 件を表示中",
"topConnections": "最近もっとも活発な接続",
"topConnectionsHint": "直近 7 日間の SSH 関連監査イベント数で集計",
"activityCount": "{count} 件",
"lastSeen": "最終確認: {time}",
"summaryCards": {
"connections": "接続総数",
"activeConnections7d": "7日以内のアクティブ接続",
"taggedConnections": "タグ付き接続",
"auditLogs": "監査ログ総数",
"sshSuccess24h": "24時間の SSH 成功",
"sshFailure24h": "24時間の SSH 失敗"
},
"summaryHints": {
"connections": "ホーム画面で接続資産、活動状況、リスクの兆候をまとめて確認できます。",
"activeConnections7d": "直近 7 日で少なくとも 1 回利用された接続数",
"taggedConnections": "タグで整理済みの接続数",
"auditLogs": "現在のデータベースに保存されている監査イベント総数",
"sshSuccess24h": "過去 24 時間に成功した SSH 接続イベント数",
"sshFailure24h": "過去 24 時間に失敗した SSH 接続または Shell 起動イベント数"
},
"charts": {
"activityTrend7d": "直近 7 日のアクティビティ推移",
"activityTrendHint": "直近 1 週間の監査イベント数を日別に表示",
"connectionTypes": "接続タイプ分布",
"connectionTypesHint": "現在の接続資産をプロトコル別に可視化",
"actionBreakdown7d": "直近 7 日のイベント分布",
"actionBreakdownHint": "最近 1 週間で発生頻度が高い監査イベント種別",
"eventCount": "イベント数"
}
},
"dockerManager": {
"action": {
+33 -1
View File
@@ -1480,7 +1480,39 @@
},
"noConnectionsWithTag": "该标签下没有连接记录",
"noConnectionsMatchSearch": "没有连接匹配搜索条件",
"searchConnectionsPlaceholder": "搜索连接..."
"searchConnectionsPlaceholder": "搜索连接...",
"summaryLoadFailed": "仪表盘统计加载失败",
"emptyChart": "暂无统计数据",
"listShowing": "显示前 {count} 项",
"topConnections": "近期最活跃连接",
"topConnectionsHint": "按最近 7 天 SSH 相关审计事件聚合排序",
"activityCount": "{count} 次",
"lastSeen": "最近出现: {time}",
"summaryCards": {
"connections": "连接总数",
"activeConnections7d": "近 7 天活跃连接",
"taggedConnections": "已打标签连接",
"auditLogs": "审计日志总数",
"sshSuccess24h": "24 小时 SSH 成功",
"sshFailure24h": "24 小时 SSH 失败"
},
"summaryHints": {
"connections": "首页现在会直接展示连接资产、活动趋势和风险信号。",
"activeConnections7d": "最近 7 天内至少连接过一次的连接数",
"taggedConnections": "已经通过标签完成归类的连接数",
"auditLogs": "当前数据库中保留的全部审计事件数量",
"sshSuccess24h": "最近 24 小时内成功建立的 SSH 连接事件",
"sshFailure24h": "最近 24 小时内 SSH 连接或 Shell 打开失败事件"
},
"charts": {
"activityTrend7d": "近 7 天活动趋势",
"activityTrendHint": "按天统计最近一周的审计事件量",
"connectionTypes": "连接类型分布",
"connectionTypesHint": "当前连接资产按协议的占比情况",
"actionBreakdown7d": "近 7 天事件分布",
"actionBreakdownHint": "最近一周出现频率最高的审计事件类型",
"eventCount": "事件数"
}
},
"terminalTabBar": {
"selectServerTitle": "选择要连接的服务器",
@@ -0,0 +1,59 @@
import { defineStore } from 'pinia';
import { ref } from 'vue';
import apiClient from '../utils/apiClient';
import type { DashboardSummary } from '../types/server.types';
export const useDashboardStore = defineStore('dashboard', () => {
const summary = ref<DashboardSummary | null>(null);
const isLoading = ref(false);
const error = ref<string | null>(null);
async function fetchSummary(): Promise<boolean> {
const cacheKey = 'dashboardSummaryCache';
error.value = null;
try {
const cachedData = localStorage.getItem(cacheKey);
if (cachedData) {
summary.value = JSON.parse(cachedData) as DashboardSummary;
isLoading.value = false;
} else {
isLoading.value = true;
}
} catch (cacheError) {
console.error('[DashboardStore] Failed to load dashboard cache:', cacheError);
localStorage.removeItem(cacheKey);
isLoading.value = true;
}
isLoading.value = true;
try {
const response = await apiClient.get<DashboardSummary>('/dashboard/summary');
const freshData = response.data;
const freshDataString = JSON.stringify(freshData);
const currentDataString = JSON.stringify(summary.value);
if (freshDataString !== currentDataString) {
summary.value = freshData;
localStorage.setItem(cacheKey, freshDataString);
}
error.value = null;
return true;
} catch (err: any) {
console.error('[DashboardStore] Failed to fetch dashboard summary:', err);
error.value = err.response?.data?.message || err.message || '获取仪表盘统计失败';
return false;
} finally {
isLoading.value = false;
}
}
return {
summary,
isLoading,
error,
fetchSummary,
};
});
@@ -0,0 +1,130 @@
import { defineStore } from 'pinia';
import { ref } from 'vue';
import apiClient from '../utils/apiClient';
export interface LoginCredentialBasicInfo {
id: number;
name: string;
type: 'SSH' | 'RDP' | 'VNC';
username: string;
auth_method: 'password' | 'key';
ssh_key_id?: number | null;
notes?: string | null;
}
export interface LoginCredentialDetails extends LoginCredentialBasicInfo {
password?: string;
privateKey?: string;
passphrase?: string;
}
export interface LoginCredentialInput {
name: string;
type: 'SSH' | 'RDP' | 'VNC';
username: string;
auth_method?: 'password' | 'key';
password?: string;
private_key?: string;
passphrase?: string;
ssh_key_id?: number | null;
notes?: string | null;
}
export const useLoginCredentialsStore = defineStore('loginCredentials', () => {
const loginCredentials = ref<LoginCredentialBasicInfo[]>([]);
const isLoading = ref(false);
const error = ref<string | null>(null);
async function fetchLoginCredentials() {
isLoading.value = true;
error.value = null;
try {
const response = await apiClient.get<LoginCredentialBasicInfo[]>('/login-credentials');
loginCredentials.value = response.data;
} catch (err: any) {
console.error('Failed to fetch login credentials:', err);
error.value = err.response?.data?.message || err.message || '获取登录凭证列表失败。';
} finally {
isLoading.value = false;
}
}
async function addLoginCredential(payload: LoginCredentialInput): Promise<boolean> {
isLoading.value = true;
error.value = null;
try {
const response = await apiClient.post<{ message: string; credential: LoginCredentialBasicInfo }>('/login-credentials', payload);
loginCredentials.value.unshift(response.data.credential);
loginCredentials.value.sort((left, right) => left.name.localeCompare(right.name));
return true;
} catch (err: any) {
console.error('Failed to add login credential:', err);
error.value = err.response?.data?.message || err.message || '创建登录凭证失败。';
return false;
} finally {
isLoading.value = false;
}
}
async function fetchLoginCredentialDetails(id: number): Promise<LoginCredentialDetails | null> {
isLoading.value = true;
error.value = null;
try {
const response = await apiClient.get<LoginCredentialDetails>(`/login-credentials/${id}/details`);
return response.data;
} catch (err: any) {
console.error(`Failed to fetch login credential ${id}:`, err);
error.value = err.response?.data?.message || err.message || '获取登录凭证详情失败。';
return null;
} finally {
isLoading.value = false;
}
}
async function updateLoginCredential(id: number, payload: Partial<LoginCredentialInput>): Promise<boolean> {
isLoading.value = true;
error.value = null;
try {
const response = await apiClient.put<{ message: string; credential: LoginCredentialBasicInfo }>(`/login-credentials/${id}`, payload);
const index = loginCredentials.value.findIndex((credential) => credential.id === id);
if (index !== -1) {
loginCredentials.value[index] = { ...loginCredentials.value[index], ...response.data.credential };
loginCredentials.value.sort((left, right) => left.name.localeCompare(right.name));
}
return true;
} catch (err: any) {
console.error(`Failed to update login credential ${id}:`, err);
error.value = err.response?.data?.message || err.message || '更新登录凭证失败。';
return false;
} finally {
isLoading.value = false;
}
}
async function deleteLoginCredential(id: number): Promise<boolean> {
isLoading.value = true;
error.value = null;
try {
await apiClient.delete(`/login-credentials/${id}`);
loginCredentials.value = loginCredentials.value.filter((credential) => credential.id !== id);
return true;
} catch (err: any) {
console.error(`Failed to delete login credential ${id}:`, err);
error.value = err.response?.data?.message || err.message || '删除登录凭证失败。';
return false;
} finally {
isLoading.value = false;
}
}
return {
loginCredentials,
isLoading,
error,
fetchLoginCredentials,
addLoginCredential,
fetchLoginCredentialDetails,
updateLoginCredential,
deleteLoginCredential,
};
});
+52 -1
View File
@@ -92,10 +92,17 @@ export type NotificationSettingData = Omit<NotificationSetting, 'id' | 'created_
export type AuditLogActionType =
| 'LOGIN_SUCCESS' | 'LOGIN_FAILURE' | 'LOGOUT' | 'PASSWORD_CHANGED'
| '2FA_ENABLED' | '2FA_DISABLED'
| 'PASSKEY_REGISTERED'
| 'PASSKEY_AUTH_SUCCESS'
| 'PASSKEY_AUTH_FAILURE'
| 'PASSKEY_DELETED'
| 'PASSKEY_DELETE_UNAUTHORIZED'
| 'PASSKEY_NAME_UPDATED'
| 'PASSKEY_NAME_UPDATE_UNAUTHORIZED'
| 'CONNECTION_CREATED' | 'CONNECTION_UPDATED' | 'CONNECTION_DELETED'
| 'PROXY_CREATED' | 'PROXY_UPDATED' | 'PROXY_DELETED'
| 'TAG_CREATED' | 'TAG_UPDATED' | 'TAG_DELETED'
| 'SETTINGS_UPDATED' | 'IP_WHITELIST_UPDATED'
| 'SETTINGS_UPDATED' | 'IP_WHITELIST_UPDATED' | 'CAPTCHA_SETTINGS_UPDATED'
| 'NOTIFICATION_SETTING_CREATED' | 'NOTIFICATION_SETTING_UPDATED' | 'NOTIFICATION_SETTING_DELETED'
// SSH Actions
| 'SSH_CONNECT_SUCCESS' | 'SSH_CONNECT_FAILURE' | 'SSH_SHELL_FAILURE'
@@ -120,3 +127,47 @@ export interface AuditLogApiResponse {
limit: number;
offset: number;
}
export interface DashboardTotals {
connections: number;
activeConnections7d: number;
taggedConnections: number;
auditLogs: number;
}
export interface DashboardSshOutcomes24h {
success: number;
failure: number;
}
export interface DashboardCountByType {
label: string;
count: number;
}
export interface DashboardActivityTrendPoint {
date: string;
count: number;
}
export interface DashboardTopConnection {
connectionId: number;
connectionName: string;
host: string;
count: number;
lastSeenAt: number;
}
export interface DashboardActionBreakdownItem {
actionType: AuditLogActionType | 'OTHER';
count: number;
}
export interface DashboardSummary {
totals: DashboardTotals;
sshOutcomes24h: DashboardSshOutcomes24h;
connectionTypes: DashboardCountByType[];
actionBreakdown7d: DashboardActionBreakdownItem[];
activityTrend7d: DashboardActivityTrendPoint[];
topConnections: DashboardTopConnection[];
}
+362 -330
View File
@@ -1,57 +1,55 @@
<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import AddConnectionForm from '../components/AddConnectionForm.vue';
import { useConnectionsStore } from '../stores/connections.store';
import { useAuditLogStore } from '../stores/audit.store';
import { useSessionStore } from '../stores/session.store';
import { useTagsStore } from '../stores/tags.store';
import type { TagInfo } from '../stores/tags.store';
import type { SortField, SortOrder } from '../stores/settings.store';
import { computed, onMounted, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import type { ConnectionInfo } from '../stores/connections.store';
import { storeToRefs } from 'pinia';
import { formatDistanceToNow } from 'date-fns';
import { zhCN, enUS, ja } from 'date-fns/locale';
import { enUS, ja, zhCN } from 'date-fns/locale';
import type { Locale } from 'date-fns';
import AddConnectionForm from '../components/AddConnectionForm.vue';
import DashboardOverviewPanel from '../components/DashboardOverviewPanel.vue';
import { useAuditLogStore } from '../stores/audit.store';
import { useConnectionsStore, type ConnectionInfo } from '../stores/connections.store';
import { useDashboardStore } from '../stores/dashboard.store';
import { useSessionStore } from '../stores/session.store';
import { useTagsStore, type TagInfo } from '../stores/tags.store';
import type { AuditLogEntry } from '../types/server.types';
import type { SortField, SortOrder } from '../stores/settings.store';
const { t, locale } = useI18n();
const router = useRouter();
const connectionsStore = useConnectionsStore();
const auditLogStore = useAuditLogStore();
const dashboardStore = useDashboardStore();
const sessionStore = useSessionStore();
const tagsStore = useTagsStore();
const tagsStore = useTagsStore();
const { connections, isLoading: isLoadingConnections } = storeToRefs(connectionsStore);
const { logs: auditLogs, isLoading: isLoadingLogs, totalLogs } = storeToRefs(auditLogStore);
const { tags, isLoading: isLoadingTags } = storeToRefs(tagsStore);
const { logs: auditLogs, isLoading: isLoadingLogs } = storeToRefs(auditLogStore);
const { summary, isLoading: isLoadingSummary, error: dashboardError } = storeToRefs(dashboardStore);
const { tags, isLoading: isLoadingTags } = storeToRefs(tagsStore);
const LS_SORT_BY_KEY = 'dashboard_connections_sort_by';
const LS_SORT_ORDER_KEY = 'dashboard_connections_sort_order';
const LS_FILTER_TAG_KEY = 'dashboard_connections_filter_tag';
const LS_FILTER_TAG_KEY = 'dashboard_connections_filter_tag';
const MAX_RECENT_LOGS = 5;
const MAX_VISIBLE_CONNECTIONS = 8;
// Initialize with localStorage values or defaults
const localSortBy = ref<SortField>(localStorage.getItem(LS_SORT_BY_KEY) as SortField || 'last_connected_at');
const localSortOrder = ref<SortOrder>(localStorage.getItem(LS_SORT_ORDER_KEY) as SortOrder || 'desc');
// +++ localStorage ( ref ) +++
const getInitialSelectedTagId = (): number | null => {
const storedValue = localStorage.getItem(LS_FILTER_TAG_KEY);
// 'null' null
return storedValue && storedValue !== 'null' ? parseInt(storedValue, 10) : null;
};
const localSortBy = ref<SortField>((localStorage.getItem(LS_SORT_BY_KEY) as SortField) || 'last_connected_at');
const localSortOrder = ref<SortOrder>((localStorage.getItem(LS_SORT_ORDER_KEY) as SortOrder) || 'desc');
const selectedTagId = ref<number | null>(getInitialSelectedTagId());
const searchQuery = ref('');
// +++ / +++
const showAddEditConnectionForm = ref(false);
const connectionToEdit = ref<ConnectionInfo | null>(null);
const maxRecentLogs = 5;
const dateFnsLocales: Record<string, Locale> = {
'en-US': enUS,
'zh-CN': zhCN,
'ja-JP': ja,
en: enUS,
zh: zhCN,
ja,
};
const sortOptions: { value: SortField; labelKey: string }[] = [
{ value: 'last_connected_at', labelKey: 'dashboard.sortOptions.lastConnected' },
{ value: 'name', labelKey: 'dashboard.sortOptions.name' },
@@ -60,113 +58,185 @@ const sortOptions: { value: SortField; labelKey: string }[] = [
{ value: 'created_at', labelKey: 'dashboard.sortOptions.created' },
];
// +++ +++
function getInitialSelectedTagId(): number | null {
const storedValue = localStorage.getItem(LS_FILTER_TAG_KEY);
return storedValue && storedValue !== 'null' ? parseInt(storedValue, 10) : null;
}
const recentAuditLogs = computed(() => auditLogs.value.slice(0, MAX_RECENT_LOGS));
const filteredAndSortedConnections = computed(() => {
const sortBy = localSortBy.value;
const sortOrderVal = localSortOrder.value;
const factor = sortOrderVal === 'desc' ? -1 : 1;
const factor = localSortOrder.value === 'desc' ? -1 : 1;
const query = searchQuery.value.toLowerCase().trim();
const filterTagId = selectedTagId.value;
const query = searchQuery.value.toLowerCase().trim(); // +++ +++
// 1. Filter by selected tag
let filteredByTag = filterTagId === null
? [...connections.value] // No tag selected, show all
: connections.value.filter(conn => conn.tag_ids?.includes(filterTagId));
// 2. Filter by search query
let searchedConnections = filteredByTag;
let filtered = filterTagId === null
? [...connections.value]
: connections.value.filter((connection) => connection.tag_ids?.includes(filterTagId));
if (query) {
searchedConnections = filteredByTag.filter(conn => {
const nameMatch = conn.name?.toLowerCase().includes(query);
const usernameMatch = conn.username?.toLowerCase().includes(query);
const hostMatch = conn.host?.toLowerCase().includes(query);
const portMatch = conn.port?.toString().includes(query);
filtered = filtered.filter((connection) => {
const nameMatch = connection.name?.toLowerCase().includes(query);
const usernameMatch = connection.username?.toLowerCase().includes(query);
const hostMatch = connection.host?.toLowerCase().includes(query);
const portMatch = connection.port?.toString().includes(query);
return nameMatch || usernameMatch || hostMatch || portMatch;
});
}
// 3. Sort the searched connections
return searchedConnections.sort((a, b) => {
let valA: any;
let valB: any;
switch (sortBy) {
return filtered.sort((left, right) => {
switch (localSortBy.value) {
case 'name':
valA = a.name || '';
valB = b.name || '';
return valA.localeCompare(valB) * factor;
return (left.name || '').localeCompare(right.name || '') * factor;
case 'type':
valA = a.type || '';
valB = b.type || '';
return valA.localeCompare(valB) * factor;
return (left.type || '').localeCompare(right.type || '') * factor;
case 'created_at':
valA = a.created_at ?? 0;
valB = b.created_at ?? 0;
return (valA - valB) * factor;
return ((left.created_at ?? 0) - (right.created_at ?? 0)) * factor;
case 'updated_at':
valA = a.updated_at ?? 0;
valB = b.updated_at ?? 0;
return (valA - valB) * factor;
case 'last_connected_at':
valA = a.last_connected_at ?? (sortOrderVal === 'desc' ? -Infinity : Infinity);
valB = b.last_connected_at ?? (sortOrderVal === 'desc' ? -Infinity : Infinity);
if (valA === valB) return 0;
if (valA < valB) return -1 * factor;
return 1 * factor;
return ((left.updated_at ?? 0) - (right.updated_at ?? 0)) * factor;
case 'last_connected_at': {
const leftValue = left.last_connected_at ?? (localSortOrder.value === 'desc' ? -Infinity : Infinity);
const rightValue = right.last_connected_at ?? (localSortOrder.value === 'desc' ? -Infinity : Infinity);
if (leftValue === rightValue) {
return 0;
}
return leftValue < rightValue ? -1 * factor : 1 * factor;
}
default:
return 0;
}
});
});
const recentAuditLogs = computed(() => {
return auditLogs.value.slice(0, maxRecentLogs);
const visibleConnections = computed(() => filteredAndSortedConnections.value.slice(0, MAX_VISIBLE_CONNECTIONS));
const isAscending = computed(() => localSortOrder.value === 'asc');
const connectionsById = computed(() => {
const map = new Map<number, ConnectionInfo>();
for (const connection of connections.value) {
map.set(connection.id, connection);
}
return map;
});
onMounted(async () => {
// Load saved preferences from localStorage (already done during ref initialization)
// Fetch connections if not already loaded
if (connections.value.length === 0) {
try {
await connectionsStore.fetchConnections();
} catch (error) {
console.error("加载连接列表失败:", error);
}
const topConnections = computed(() => {
if (!summary.value) {
return [] as Array<{ connectionId: number; connectionName: string; host: string; count: number; lastSeenAt: number; connection: ConnectionInfo | null }>;
}
return summary.value.topConnections.map((item) => ({
...item,
connection: connectionsById.value.get(item.connectionId) ?? null,
}));
});
function resolveDateFnsLocale(): Locale {
return dateFnsLocales[locale.value] || dateFnsLocales[locale.value.split('-')[0]] || enUS;
}
function formatRelativeTime(timestampInSeconds: number | null | undefined): string {
if (!timestampInSeconds) {
return t('connections.status.never');
}
// Fetch recent audit logs
try {
await auditLogStore.fetchLogs({
page: 1,
limit: maxRecentLogs,
sortOrder: 'desc',
isDashboardRequest: true
return formatDistanceToNow(new Date(timestampInSeconds * 1000), {
addSuffix: true,
locale: resolveDateFnsLocale(),
});
} catch (error) {
console.error("加载审计日志失败:", error);
console.error('[Dashboard] Failed to format relative time:', error);
return String(timestampInSeconds);
}
}
function formatNumber(value: number): string {
return new Intl.NumberFormat(locale.value).format(value);
}
function getActionTranslation(actionType: string): string {
const key = `auditLog.actions.${actionType}`;
const translated = t(key);
return translated === key ? actionType : translated;
}
function isFailedAction(actionType: string): boolean {
const lowerCaseAction = actionType.toLowerCase();
return lowerCaseAction.includes('fail') || lowerCaseAction.includes('error') || lowerCaseAction.includes('denied');
}
function getTagNames(tagIds: number[] | undefined): string[] {
if (!tagIds || tagIds.length === 0) {
return [];
}
// +++ Fetch tags for filtering +++
try {
await tagsStore.fetchTags();
} catch (error) {
console.error("加载标签列表失败:", error);
const allTags = tags.value as TagInfo[];
return tagIds
.map((id) => allTags.find((tag) => tag.id === id)?.name)
.filter((name): name is string => !!name);
}
function formatAuditDetails(details: AuditLogEntry['details']): string {
if (!details) {
return '-';
}
});
const connectTo = (connection: ConnectionInfo) => {
sessionStore.handleConnectRequest(connection);
};
if ('raw' in details) {
return details.raw;
}
const toggleSortOrder = () => {
// Only update the local sort order state
const formattedEntries = Object.entries(details)
.filter(([key]) => !['userId', 'sessionId'].includes(key))
.slice(0, 4)
.map(([key, value]) => `${key}: ${formatAuditDetailValue(value)}`);
return formattedEntries.length > 0 ? formattedEntries.join(' | ') : JSON.stringify(details);
}
function formatAuditDetailValue(value: unknown): string {
if (value === null || value === undefined) {
return '-';
}
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
return String(value);
}
return JSON.stringify(value);
}
function connectTo(connection: ConnectionInfo | null | undefined): void {
if (connection) {
sessionStore.handleConnectRequest(connection);
}
}
function toggleSortOrder(): void {
localSortOrder.value = localSortOrder.value === 'asc' ? 'desc' : 'asc';
};
}
const isAscending = computed(() => localSortOrder.value === 'asc'); // Use local state
function openAddConnectionForm(): void {
connectionToEdit.value = null;
showAddEditConnectionForm.value = true;
}
function openEditConnectionForm(connection: ConnectionInfo): void {
connectionToEdit.value = connection;
showAddEditConnectionForm.value = true;
}
function handleFormClose(): void {
showAddEditConnectionForm.value = false;
connectionToEdit.value = null;
}
async function handleConnectionModified(): Promise<void> {
showAddEditConnectionForm.value = false;
connectionToEdit.value = null;
await connectionsStore.fetchConnections();
await dashboardStore.fetchSummary();
}
// Watch for changes in local sort state and save to localStorage
watch(localSortBy, (newValue) => {
localStorage.setItem(LS_SORT_BY_KEY, newValue);
});
@@ -175,249 +245,211 @@ watch(localSortOrder, (newValue) => {
localStorage.setItem(LS_SORT_ORDER_KEY, newValue);
});
// +++ Watch for changes in selected tag and save to localStorage +++
watch(selectedTagId, (newValue) => {
// Store 'null' as a string or the number
localStorage.setItem(LS_FILTER_TAG_KEY, newValue === null ? 'null' : String(newValue));
});
const dateFnsLocales: Record<string, Locale> = {
'en-US': enUS,
'zh-CN': zhCN,
'ja-JP': ja,
// 退
'en': enUS,
'zh': zhCN,
'ja': ja,
};
// number | null | undefined
const formatRelativeTime = (timestampInSeconds: number | null | undefined): string => {
if (!timestampInSeconds) return t('connections.status.never');
try {
//
const timestampInMs = timestampInSeconds * 1000;
//
if (isNaN(timestampInMs)) {
console.warn(`[Dashboard] Invalid timestamp received: ${timestampInSeconds}`);
return String(timestampInSeconds); //
}
const date = new Date(timestampInMs);
const currentI18nLocale = locale.value; // vue-i18n locale (e.g., 'zh-CN')
const langPart = currentI18nLocale.split('-')[0]; // (e.g., 'zh')
// 1. (e.g., 'zh-CN' -> zhCN)
let targetDateFnsLocale = dateFnsLocales[currentI18nLocale];
// 2. (e.g., 'zh' -> zhCN)
if (!targetDateFnsLocale) {
targetDateFnsLocale = dateFnsLocales[langPart];
}
// 3. 退 enUS
if (!targetDateFnsLocale) {
console.warn(`[Dashboard] date-fns locale not found for ${currentI18nLocale} or ${langPart}. Falling back to en-US.`);
targetDateFnsLocale = enUS; // 退 enUS
}
return formatDistanceToNow(date, { addSuffix: true, locale: targetDateFnsLocale });
} catch (e) {
console.error("格式化日期失败:", e);
return String(timestampInSeconds); //
}
};
const getActionTranslation = (actionType: string): string => {
// i18n actionType
const key = `auditLog.actions.${actionType}`;
const translated = t(key);
// key
return translated === key ? actionType : translated;
};
//
const isFailedAction = (actionType: string): boolean => {
const lowerCaseAction = actionType.toLowerCase();
//
return lowerCaseAction.includes('fail') || lowerCaseAction.includes('error') || lowerCaseAction.includes('denied');
};
// +++ tag_ids +++
const getTagNames = (tagIds: number[] | undefined): string[] => {
if (!tagIds || tagIds.length === 0) {
return [];
}
const allTags = tags.value as TagInfo[];
return tagIds
.map(id => allTags.find(tag => tag.id === id)?.name)
.filter((name): name is string => !!name); // string
};
// +++ +++
const openAddConnectionForm = () => {
connectionToEdit.value = null;
showAddEditConnectionForm.value = true;
};
// +++ +++
const openEditConnectionForm = (conn: ConnectionInfo) => {
connectionToEdit.value = conn;
showAddEditConnectionForm.value = true;
};
// +++ +++
const handleFormClose = () => {
showAddEditConnectionForm.value = false;
connectionToEdit.value = null; //
};
// +++ / +++
const handleConnectionModified = async () => {
showAddEditConnectionForm.value = false;
connectionToEdit.value = null;
await connectionsStore.fetchConnections(); //
};
// --- selectTagFilter ---
onMounted(async () => {
await Promise.allSettled([
connectionsStore.fetchConnections(),
auditLogStore.fetchLogs({
page: 1,
limit: MAX_RECENT_LOGS,
sortOrder: 'desc',
isDashboardRequest: true,
}),
tagsStore.fetchTags(),
dashboardStore.fetchSummary(),
]);
});
</script>
<template>
<div class="p-4 md:p-6 lg:p-8 bg-background text-foreground">
<h1 class="text-2xl font-semibold mb-6">{{ t('nav.dashboard') }}</h1>
<div class="space-y-6 bg-background p-4 text-foreground md:p-6 lg:p-8">
<div class="flex flex-col gap-2 md:flex-row md:items-end md:justify-between">
<div>
<h1 class="text-2xl font-semibold">{{ t('nav.dashboard') }}</h1>
<p class="text-sm text-text-secondary">{{ t('dashboard.summaryHints.connections') }}</p>
</div>
<span class="inline-flex items-center gap-2 rounded-full border border-border/70 bg-card px-3 py-1.5 text-xs text-text-secondary">
<i class="fas fa-chart-line text-sky-400"></i>
{{ t('dashboard.charts.activityTrend7d') }}
</span>
</div>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 lg:items-start">
<DashboardOverviewPanel
:summary="summary"
:is-loading="isLoadingSummary"
:error="dashboardError"
:top-connections="topConnections"
@connect="connectTo"
/>
<!-- Connection List -->
<div class="bg-card text-card-foreground shadow rounded-lg overflow-hidden border border-border min-h-[400px]">
<div class="px-4 py-3 border-b border-border flex flex-col sm:flex-row justify-between items-start sm:items-center gap-2">
<h2 class="text-lg font-medium flex-shrink-0">{{ t('dashboard.connectionList', '连接列表') }} ({{ filteredAndSortedConnections.length }})</h2>
<div class="w-full sm:w-auto flex flex-wrap sm:flex-nowrap items-stretch sm:items-center space-y-2 sm:space-y-0 sm:space-x-2">
<!-- Search Input (Order adjusted for button placement) -->
<input
type="text"
v-model="searchQuery"
:placeholder="t('dashboard.searchConnectionsPlaceholder', '搜索连接...')"
class="h-8 px-3 py-1 text-sm border border-border rounded bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary w-full sm:w-48"
/>
<div class="flex items-center space-x-2"> <!-- Wrapper for existing controls -->
<!-- Tag Filter Dropdown -->
<select
v-model="selectedTagId"
class="h-8 px-2 py-1 text-sm border border-border rounded bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary appearance-none bg-no-repeat bg-right pr-8"
style="background-image: url('data:image/svg+xml,%3csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 16 16\'%3e%3cpath fill=\'none\' stroke=\'%236c757d\' stroke-linecap=\'round\' stroke-linejoin=\'round\' stroke-width=\'2\' d=\'M2 5l6 6 6-6\'/%3e%3c/svg%3e'); background-position: right 0.5rem center; background-size: 16px 12px;"
aria-label="Filter connections by tag"
:disabled="isLoadingTags"
>
<option :value="null">{{ t('dashboard.filterTags.all', '所有标签') }}</option>
<option v-if="isLoadingTags" disabled>{{ t('common.loading') }}</option>
<!-- 修正 v-for 循环中的类型 -->
<option v-for="tag in (tags as TagInfo[])" :key="tag.id" :value="tag.id">
{{ tag.name }}
</option>
</select>
<!-- Sort By Dropdown -->
<select
v-model="localSortBy"
class="h-8 px-2 py-1 text-sm border border-border rounded bg-background text-foreground focus:outline-none focus:ring-1 focus:ring-primary appearance-none bg-no-repeat bg-right pr-8"
style="background-image: url('data:image/svg+xml,%3csvg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 16 16\'%3e%3cpath fill=\'none\' stroke=\'%236c757d\' stroke-linecap=\'round\' stroke-linejoin=\'round\' stroke-width=\'2\' d=\'M2 5l6 6 6-6\'/%3e%3c/svg%3e'); background-position: right 0.5rem center; background-size: 16px 12px;"
aria-label="Sort connections by"
>
<option v-for="option in sortOptions" :key="option.value" :value="option.value">
{{ t(option.labelKey, option.value.replace('_', ' ')) }}
</option>
</select>
<!-- Sort Order Button -->
<button
@click="toggleSortOrder"
class="h-8 px-1.5 py-1 border border-border rounded hover:bg-muted focus:outline-none focus:ring-1 focus:ring-primary flex items-center justify-center"
:aria-label="isAscending ? t('common.sortAscending') : t('common.sortDescending')"
:title="isAscending ? t('common.sortAscending') : t('common.sortDescending')"
>
<i :class="['fas', isAscending ? 'fa-arrow-up-a-z' : 'fa-arrow-down-z-a', 'w-4 h-4']"></i>
</button>
</div>
<!-- Add Connection Button -->
<button @click="openAddConnectionForm" title="Add Connection" class="h-8 w-8 bg-button rounded-md shadow-sm hover:bg-button-hover focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary transition duration-150 ease-in-out flex items-center justify-center flex-shrink-0 ml-2 sm:ml-0">
<i class="fas fa-plus" style="color: white;"></i>
<section class="rounded-xl border border-border bg-card shadow-sm">
<div class="flex flex-col gap-3 border-b border-border px-4 py-3 lg:flex-row lg:items-center lg:justify-between">
<div>
<h2 class="text-lg font-medium">
{{ t('dashboard.connectionList') }} ({{ formatNumber(filteredAndSortedConnections.length) }})
</h2>
<p class="text-sm text-text-secondary">
{{ t('dashboard.listShowing', { count: Math.min(filteredAndSortedConnections.length, MAX_VISIBLE_CONNECTIONS) }) }}
</p>
</div>
<div class="flex w-full flex-col gap-2 sm:flex-row lg:w-auto">
<input
v-model="searchQuery"
type="text"
:placeholder="t('dashboard.searchConnectionsPlaceholder')"
class="h-9 rounded-md border border-border bg-background px-3 text-sm text-foreground focus:outline-none focus:ring-1 focus:ring-primary sm:w-52"
/>
<div class="flex items-center gap-2">
<select
v-model="selectedTagId"
class="h-9 rounded-md border border-border bg-background px-2 text-sm text-foreground focus:outline-none focus:ring-1 focus:ring-primary"
:disabled="isLoadingTags"
>
<option :value="null">{{ t('dashboard.filterTags.all') }}</option>
<option v-if="isLoadingTags" disabled>{{ t('common.loading') }}</option>
<option v-for="tag in (tags as TagInfo[])" :key="tag.id" :value="tag.id">
{{ tag.name }}
</option>
</select>
<select
v-model="localSortBy"
class="h-9 rounded-md border border-border bg-background px-2 text-sm text-foreground focus:outline-none focus:ring-1 focus:ring-primary"
>
<option v-for="option in sortOptions" :key="option.value" :value="option.value">
{{ t(option.labelKey) }}
</option>
</select>
<button
class="flex h-9 w-9 items-center justify-center rounded-md border border-border hover:bg-muted"
:aria-label="isAscending ? t('common.sortAscending') : t('common.sortDescending')"
:title="isAscending ? t('common.sortAscending') : t('common.sortDescending')"
@click="toggleSortOrder"
>
<i :class="['fas', isAscending ? 'fa-arrow-up-a-z' : 'fa-arrow-down-z-a']"></i>
</button>
<button
class="flex h-9 w-9 items-center justify-center rounded-md bg-button text-button-text shadow-sm hover:bg-button-hover"
title="Add Connection"
@click="openAddConnectionForm"
>
<i class="fas fa-plus"></i>
</button>
</div>
</div>
<div class="p-4">
<!-- Use filteredAndSortedConnections and check its length -->
<div v-if="isLoadingConnections && filteredAndSortedConnections.length === 0" class="text-center text-text-secondary">{{ t('common.loading') }}</div>
<ul v-else-if="filteredAndSortedConnections.length > 0" class="space-y-3">
<!-- Iterate over filteredAndSortedConnections -->
<li v-for="conn in filteredAndSortedConnections" :key="conn.id" class="flex items-center justify-between p-3 bg-header/50 border border-border/50 rounded transition duration-150 ease-in-out">
<div class="flex-grow mr-4 overflow-hidden">
<span class="font-medium block truncate flex items-center" :title="conn.name || ''">
<i :class="['fas', conn.type === 'VNC' ? 'fa-plug' : (conn.type === 'RDP' ? 'fa-desktop' : 'fa-server'), 'mr-2 w-4 text-center text-text-secondary']"></i>
<span>{{ conn.name || conn.host || t('connections.unnamedFallback', '未命名连接') }}</span>
</div>
<div class="p-4">
<div v-if="isLoadingConnections && visibleConnections.length === 0" class="text-center text-text-secondary">
{{ t('common.loading') }}
</div>
<ul v-else-if="visibleConnections.length > 0" class="space-y-3">
<li
v-for="connection in visibleConnections"
:key="connection.id"
class="flex flex-col gap-3 rounded-lg border border-border/70 bg-header/40 p-3 lg:flex-row lg:items-center lg:justify-between"
>
<div class="min-w-0 flex-1">
<div class="flex items-center gap-2">
<i
:class="[
'fas',
connection.type === 'VNC' ? 'fa-plug' : connection.type === 'RDP' ? 'fa-desktop' : 'fa-server',
'w-4 text-text-secondary',
]"
></i>
<span class="truncate font-medium">
{{ connection.name || connection.host || t('connections.unnamedFallback') }}
</span>
<span class="text-sm text-text-secondary block truncate" :title="`${conn.username}@${conn.host}:${conn.port}`">
{{ conn.username }}@{{ conn.host }}:{{ conn.port }}
</span>
<span class="text-xs text-text-alt block mb-1"> <!-- Added margin-bottom -->
{{ t('dashboard.lastConnected', '上次连接:') }} {{ formatRelativeTime(conn.last_connected_at) }}
</span>
<div v-if="getTagNames(conn.tag_ids).length > 0" class="flex flex-wrap gap-1 mt-1">
<span
v-for="tagName in getTagNames(conn.tag_ids)"
:key="tagName"
class="px-1.5 py-0.5 text-xs rounded bg-muted text-muted-foreground border border-border"
>
{{ tagName }}
</span>
</div>
</div>
<div class="flex space-x-2 flex-shrink-0">
<button @click="openEditConnectionForm(conn)" class="px-3 py-1.5 bg-transparent text-foreground border border-border rounded-md shadow-sm hover:bg-border focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary transition duration-150 ease-in-out text-sm font-medium">
<i class="fas fa-pencil-alt"></i>
</button>
<button @click="connectTo(conn)" class="px-4 py-2 bg-button text-button-text rounded-md shadow-sm hover:bg-button-hover focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary transition duration-150 ease-in-out text-sm font-medium"> <!-- Applied standard button style -->
{{ t('connections.actions.connect') }}
</button>
<p class="truncate text-sm text-text-secondary">
{{ connection.username }}@{{ connection.host }}:{{ connection.port }}
</p>
<p class="text-xs text-text-alt">
{{ t('dashboard.lastConnected') }} {{ formatRelativeTime(connection.last_connected_at) }}
</p>
<div v-if="getTagNames(connection.tag_ids).length > 0" class="mt-2 flex flex-wrap gap-1">
<span
v-for="tagName in getTagNames(connection.tag_ids)"
:key="tagName"
class="rounded border border-border bg-muted px-1.5 py-0.5 text-xs text-muted-foreground"
>
{{ tagName }}
</span>
</div>
</li>
</ul>
<!-- Adjust no connections message based on filtering and search -->
<div v-else-if="!isLoadingConnections && searchQuery && filteredAndSortedConnections.length === 0" class="text-center text-text-secondary">{{ t('dashboard.noConnectionsMatchSearch', '没有连接匹配搜索条件') }}</div>
<div v-else-if="!isLoadingConnections && selectedTagId !== null && filteredAndSortedConnections.length === 0" class="text-center text-text-secondary">{{ t('dashboard.noConnectionsWithTag', '该标签下没有连接记录') }}</div>
<div v-else class="text-center text-text-secondary">{{ t('dashboard.noConnections', '没有连接记录') }}</div>
</div>
<div class="flex items-center gap-2">
<button
class="rounded-md border border-border px-3 py-1.5 text-sm hover:bg-muted"
@click="openEditConnectionForm(connection)"
>
<i class="fas fa-pencil-alt"></i>
</button>
<button
class="rounded-md bg-button px-4 py-2 text-sm font-medium text-button-text shadow-sm hover:bg-button-hover"
@click="connectTo(connection)"
>
{{ t('connections.actions.connect') }}
</button>
</div>
</li>
</ul>
<div v-else-if="!isLoadingConnections && searchQuery" class="text-center text-text-secondary">
{{ t('dashboard.noConnectionsMatchSearch') }}
</div>
<div v-else-if="!isLoadingConnections && selectedTagId !== null" class="text-center text-text-secondary">
{{ t('dashboard.noConnectionsWithTag') }}
</div>
<div v-else class="text-center text-text-secondary">
{{ t('dashboard.noConnections') }}
</div>
</div>
<div class="border-t border-border px-4 py-3 text-right">
<RouterLink :to="{ name: 'Connections' }" class="text-sm text-link hover:text-link-hover hover:underline">
{{ t('dashboard.viewAllConnections') }}
</RouterLink>
</div>
</section>
<!-- Recent Activity -->
<div class="bg-card text-card-foreground shadow rounded-lg overflow-hidden border border-border min-h-[400px]">
<div class="px-4 py-3 border-b border-border">
<h2 class="text-lg font-medium">{{ t('dashboard.recentActivity', '最近活动') }}</h2>
<section class="rounded-xl border border-border bg-card shadow-sm">
<div class="border-b border-border px-4 py-3">
<h2 class="text-lg font-medium">{{ t('dashboard.recentActivity') }}</h2>
</div>
<div class="p-4">
<div v-if="isLoadingLogs && recentAuditLogs.length === 0" class="text-center text-text-secondary">
{{ t('common.loading') }}
</div>
<div class="p-4">
<!-- Loading State (Only show if loading AND no logs are displayed yet) -->
<div v-if="isLoadingLogs && recentAuditLogs.length === 0" class="text-center text-text-secondary">{{ t('common.loading') }}</div>
<ul v-else-if="recentAuditLogs.length > 0" class="space-y-3">
<li v-for="log in recentAuditLogs" :key="log.id" class="p-3 bg-header/50 border border-border/50 rounded"> <!-- Applied audit log item style -->
<div class="flex justify-between items-start mb-1">
<span class="font-medium text-sm" :class="{ 'text-error': isFailedAction(log.action_type) }">{{ getActionTranslation(log.action_type) }}</span>
<span class="text-xs text-text-alt flex-shrink-0 ml-2">{{ formatRelativeTime(log.timestamp) }}</span>
</div>
<p class="text-sm text-text-secondary break-words">{{ log.details }}</p>
</li>
</ul>
<div v-else class="text-center text-text-secondary">{{ t('dashboard.noRecentActivity', '没有最近活动记录') }}</div>
</div>
<div class="px-4 py-3 border-t border-border text-right">
<RouterLink :to="{ name: 'AuditLogs' }" class="text-sm text-link hover:text-link-hover hover:underline">
{{ t('dashboard.viewFullAuditLog', '查看完整审计日志') }}
</RouterLink>
<ul v-else-if="recentAuditLogs.length > 0" class="space-y-3">
<li
v-for="log in recentAuditLogs"
:key="log.id"
class="rounded-lg border border-border/70 bg-header/40 p-3"
>
<div class="mb-1 flex items-start justify-between gap-2">
<span class="text-sm font-medium" :class="{ 'text-error': isFailedAction(log.action_type) }">
{{ getActionTranslation(log.action_type) }}
</span>
<span class="shrink-0 text-xs text-text-alt">
{{ formatRelativeTime(log.timestamp) }}
</span>
</div>
<p class="break-words text-sm text-text-secondary">
{{ formatAuditDetails(log.details) }}
</p>
</li>
</ul>
<div v-else class="text-center text-text-secondary">
{{ t('dashboard.noRecentActivity') }}
</div>
</div>
<div class="border-t border-border px-4 py-3 text-right">
<RouterLink :to="{ name: 'AuditLogs' }" class="text-sm text-link hover:text-link-hover hover:underline">
{{ t('dashboard.viewFullAuditLog') }}
</RouterLink>
</div>
</section>
</div>
<!-- Add/Edit Connection Form Modal -->
<AddConnectionForm
v-if="showAddEditConnectionForm"
:connectionToEdit="connectionToEdit"