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>