feat: 新增密钥管理界面

#1
This commit is contained in:
Baobhan Sith
2025-05-01 17:40:36 +08:00
parent 2d7434d778
commit 2a201739cb
19 changed files with 1449 additions and 104 deletions
@@ -6,7 +6,9 @@ import apiClient from '../utils/apiClient';
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 SSH Key store +++
import TagInput from './TagInput.vue';
import SshKeySelector from './SshKeySelector.vue'; // +++ Import SSH Key Selector +++
// 定义组件发出的事件
const emit = defineEmits(['close', 'connection-added', 'connection-updated']);
@@ -33,8 +35,9 @@ const initialFormData = {
username: '',
auth_method: 'password' as 'password' | 'key', // SSH specific
password: '',
private_key: '', // SSH specific
passphrase: '', // SSH specific
private_key: '', // SSH specific (for direct input)
passphrase: '', // SSH specific (for direct input)
selected_ssh_key_id: null as number | null, // +++ Add field for selected key ID +++
proxy_id: null as number | null,
tag_ids: [] as number[], // 新增 tag_ids 字段
// Add RDP specific fields later if needed, e.g., domain
@@ -138,8 +141,9 @@ const handleSubmit = async () => {
formError.value = t('connections.form.errorPasswordRequired');
return;
}
if (formData.auth_method === 'key' && !formData.private_key) {
formError.value = t('connections.form.errorPrivateKeyRequired');
// 当认证方式为 key 时,必须选择一个已保存的密钥
if (formData.auth_method === 'key' && !formData.selected_ssh_key_id) {
formError.value = t('connections.form.errorSshKeyRequired'); // 需要添加新的翻译键
return;
}
}
@@ -153,14 +157,16 @@ const handleSubmit = async () => {
}
// 如果原始就是密码,编辑时密码可以不填(表示不修改)
}
// 3. 编辑模式下,如果切换到密钥认证,则私钥必填
else if (isEditMode.value && formData.auth_method === 'key' && !formData.private_key) {
// 检查原始连接的认证方式,如果原始不是密钥,则切换时必须提供私
// 3. 编辑模式下,如果切换到密钥认证,必须选择一个密钥
else if (isEditMode.value && formData.auth_method === 'key' && !formData.selected_ssh_key_id) {
// 检查原始连接的认证方式,如果原始不是密钥,则切换时必须选择一个密
if (props.connectionToEdit?.auth_method !== 'key') {
formError.value = t('connections.form.errorPrivateKeyRequiredOnSwitch');
formError.value = t('connections.form.errorSshKeyRequiredOnSwitch'); // 需要添加新的翻译键
return;
}
// 如果原始就是密钥,编辑时私钥可以不(表示不修改)
// 如果原始就是密钥,编辑时可以不选择新的密钥(表示不修改关联的密钥
// 但如果用户清除了选择,则需要提示
// 注意:当前逻辑下,如果 selected_ssh_key_id 为 null,则会触发此验证
}
// Use uppercase for comparison
} else if (formData.type === 'RDP') {
@@ -203,16 +209,21 @@ const handleSubmit = async () => {
// 或者不发送 password 字段表示不修改
}
} else if (formData.auth_method === 'key') {
// SSH 密钥处理
if (formData.private_key) {
dataToSend.private_key = formData.private_key;
}
// SSH 密码短语处理
if (formData.passphrase) {
dataToSend.passphrase = formData.passphrase;
} else if (isEditMode.value && formData.passphrase === '') {
// dataToSend.passphrase = null; // 发送 null 表示清空
// +++ SSH 密钥处理 (只处理 selected_ssh_key_id) +++
if (formData.selected_ssh_key_id) {
// 如果选择了已保存的密钥,只发送 ID
dataToSend.ssh_key_id = formData.selected_ssh_key_id;
} else if (isEditMode.value && props.connectionToEdit?.auth_method === 'key') {
// 编辑模式下,如果原始是密钥认证且未选择新密钥,则不发送 ssh_key_id (表示不更改)
// 如果原始不是密钥认证,切换到密钥时必须选择一个 (已在验证逻辑中处理)
} else {
// 添加模式下,如果 auth_method 是 key 但没有选择 key,验证逻辑会阻止提交
// 因此这里不需要特殊处理,可以安全地将 ssh_key_id 设为 null 或不设置
dataToSend.ssh_key_id = null; // 或者 delete dataToSend.ssh_key_id;
}
// 确保不发送直接输入的密钥信息
delete dataToSend.private_key;
delete dataToSend.passphrase;
}
// Use uppercase for comparison
} else if (formData.type === 'RDP') {
@@ -273,9 +284,11 @@ const handleTestConnection = async () => {
username: formData.username,
auth_method: formData.auth_method,
password: formData.auth_method === 'password' ? formData.password : undefined,
private_key: formData.auth_method === 'key' ? formData.private_key : undefined,
passphrase: formData.auth_method === 'key' ? formData.passphrase : undefined,
// private_key: formData.auth_method === 'key' ? formData.private_key : undefined, // Removed
// passphrase: formData.auth_method === 'key' ? formData.passphrase : undefined, // Removed
proxy_id: formData.proxy_id || null,
// +++ Add ssh_key_id for testing +++
ssh_key_id: formData.auth_method === 'key' ? formData.selected_ssh_key_id : undefined,
};
// 仅在添加模式下进行前端凭证验证
@@ -286,10 +299,11 @@ const handleTestConnection = async () => {
// 在添加模式下,密码或密钥必须提供
if (dataToSend.auth_method === 'password' && !formData.password) { // 检查 formData 而不是 dataToSend.password
throw new Error(t('connections.form.errorPasswordRequired')); // 复用表单提交的翻译键
}
if (dataToSend.auth_method === 'key' && !formData.private_key) { // 检查 formData 而不是 dataToSend.private_key
throw new Error(t('connections.form.errorPrivateKeyRequired')); // 复用表单提交的翻译键
}
}
// +++ Check selected key for testing +++
if (dataToSend.auth_method === 'key' && !dataToSend.ssh_key_id) {
throw new Error(t('connections.form.errorSshKeyRequired')); // 使用新的翻译键
}
// 调用测试未保存连接的 API
response = await apiClient.post('/connections/test-unsaved', dataToSend);
@@ -409,19 +423,17 @@ const testButtonText = computed(() => {
</div>
<div v-if="formData.auth_method === 'key'" class="space-y-4">
<!-- +++ SSH Key Selector +++ -->
<div>
<label for="conn-private-key" class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.privateKey') }}</label>
<textarea id="conn-private-key" v-model="formData.private_key" rows="4" :required="formData.auth_method === 'key' && !isEditMode"
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 font-mono text-sm"></textarea>
</div>
<div>
<label for="conn-passphrase" class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.passphrase') }} ({{ t('connections.form.optional') }})</label>
<input type="password" id="conn-passphrase" v-model="formData.passphrase" 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-if="isEditMode && formData.auth_method === 'key'">
<small class="block text-xs text-text-secondary">{{ t('connections.form.keyUpdateNote') }}</small>
<label class="block text-sm font-medium text-text-secondary mb-1">{{ t('connections.form.sshKey') }}</label>
<SshKeySelector v-model="formData.selected_ssh_key_id" />
</div>
<!-- Direct Key Input Removed -->
<!-- Note for selected key -->
<div v-if="isEditMode && formData.auth_method === 'key' && formData.selected_ssh_key_id">
<small class="block text-xs text-text-secondary">{{ t('connections.form.keyUpdateNoteSelected') }}</small>
</div>
</div>
</template>
@@ -0,0 +1,225 @@
<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useSshKeysStore, SshKeyBasicInfo, SshKeyInput } from '../stores/sshKeys.store';
import { useUiNotificationsStore } from '../stores/uiNotifications.store';
const emit = defineEmits(['close']);
const { t } = useI18n();
const sshKeysStore = useSshKeysStore();
const uiNotificationsStore = useUiNotificationsStore();
const keys = computed(() => sshKeysStore.sshKeys);
const isLoading = computed(() => sshKeysStore.isLoading);
const isAddEditFormVisible = ref(false);
const keyToEdit = ref<SshKeyBasicInfo | null>(null); // Store basic info for editing
// Form data for adding/editing
const initialFormData: SshKeyInput = {
name: '',
private_key: '',
passphrase: '',
};
const formData = reactive({ ...initialFormData });
const formError = ref<string | null>(null);
// Fetch keys when the modal is mounted
onMounted(() => {
sshKeysStore.fetchSshKeys();
});
// Show the form for adding a new key
const showAddForm = () => {
keyToEdit.value = null;
Object.assign(formData, initialFormData); // Reset form
formError.value = null;
isAddEditFormVisible.value = true;
};
// Show the form for editing an existing key
const showEditForm = async (key: SshKeyBasicInfo) => {
formError.value = null;
keyToEdit.value = key; // Store the key being edited
// Fetch decrypted details to pre-fill the form (excluding passphrase for security)
const details = await sshKeysStore.fetchDecryptedSshKey(key.id);
if (details) {
formData.name = details.name;
formData.private_key = details.privateKey;
formData.passphrase = ''; // Do not pre-fill passphrase
isAddEditFormVisible.value = true;
} else {
// Handle error if details couldn't be fetched
uiNotificationsStore.addNotification({ message: t('sshKeys.modal.errorFetchDetails'), type: 'error' });
keyToEdit.value = null; // Reset edit state
}
};
// Handle form submission (add or edit)
const handleSubmit = async () => {
formError.value = null;
if (!formData.name || !formData.private_key) {
formError.value = t('sshKeys.modal.errorRequiredFields');
return;
}
let success = false;
const dataToSend: Partial<SshKeyInput> = {
name: formData.name,
private_key: formData.private_key,
// Only send passphrase if it's not empty
...(formData.passphrase && { passphrase: formData.passphrase }),
};
if (keyToEdit.value) {
// Edit mode
// Only send fields that changed? Or send all? Backend handles update logic.
// Let's send all potentially updatable fields for simplicity here.
success = await sshKeysStore.updateSshKey(keyToEdit.value.id, dataToSend);
} else {
// Add mode
success = await sshKeysStore.addSshKey(dataToSend as SshKeyInput); // Cast needed as all fields are required for add
}
if (success) {
isAddEditFormVisible.value = false; // Close form on success
} else {
// Error message is handled by the store and displayed via uiNotificationsStore
// Optionally set formError based on store error if needed for specific display
formError.value = sshKeysStore.error;
}
};
// Handle key deletion
const handleDelete = async (key: SshKeyBasicInfo) => {
// Simple confirmation dialog
if (confirm(t('sshKeys.modal.confirmDelete', { name: key.name }))) {
const success = await sshKeysStore.deleteSshKey(key.id);
if (!success) {
// Error handled by store
}
// If the deleted key was being edited, close the form
if (keyToEdit.value?.id === key.id) {
isAddEditFormVisible.value = false;
keyToEdit.value = null;
}
}
};
// Cancel add/edit form
const cancelForm = () => {
isAddEditFormVisible.value = false;
keyToEdit.value = null;
};
</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-3xl max-h-[80vh] flex flex-col">
<!-- Main Modal Content -->
<div v-if="!isAddEditFormVisible" class="flex flex-col h-full">
<h3 class="text-xl font-semibold text-center mb-4 flex-shrink-0">{{ t('sshKeys.modal.title') }}</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"></i>{{ t('sshKeys.modal.addKey') }}
</button>
</div>
<!-- Key List -->
<div class="flex-grow overflow-y-auto border border-border rounded-md">
<table class="min-w-full divide-y divide-border">
<thead class="bg-header sticky top-0">
<tr>
<th scope="col" class="px-6 py-3 text-left text-xs font-medium text-text-secondary uppercase tracking-wider">
{{ t('sshKeys.modal.keyName') }}
</th>
<th scope="col" class="px-6 py-3 text-right text-xs font-medium text-text-secondary uppercase tracking-wider">
{{ t('sshKeys.modal.actions') }}
</th>
</tr>
</thead>
<tbody class="bg-background divide-y divide-border">
<tr v-if="isLoading">
<td colspan="2" class="px-6 py-4 whitespace-nowrap text-sm text-text-secondary text-center">{{ t('sshKeys.modal.loading') }}</td>
</tr>
<tr v-else-if="keys.length === 0">
<td colspan="2" class="px-6 py-4 whitespace-nowrap text-sm text-text-secondary text-center">{{ t('sshKeys.modal.noKeys') }}</td>
</tr>
<tr v-for="key in keys" :key="key.id">
<td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-foreground">{{ key.name }}</td>
<td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium space-x-2">
<button @click="showEditForm(key)" class="text-primary hover:text-primary-hover disabled:opacity-50" :disabled="isLoading" :title="t('sshKeys.modal.edit')">
<i class="fas fa-pencil-alt"></i>
</button>
<button @click="handleDelete(key)" class="text-error hover:text-error-hover disabled:opacity-50" :disabled="isLoading" :title="t('sshKeys.modal.delete')">
<i class="fas fa-trash-alt"></i>
</button>
</td>
</tr>
</tbody>
</table>
</div>
<!-- Close Button -->
<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('sshKeys.modal.close') }}
</button>
</div>
</div>
<!-- Add/Edit Form -->
<div v-else class="flex flex-col h-full">
<h3 class="text-xl font-semibold text-center mb-6 flex-shrink-0">
{{ keyToEdit ? t('sshKeys.modal.editTitle') : t('sshKeys.modal.addTitle') }}
</h3>
<form @submit.prevent="handleSubmit" class="flex-grow overflow-y-auto pr-2 space-y-4">
<div>
<label for="key-name" class="block text-sm font-medium text-text-secondary mb-1">{{ t('sshKeys.modal.keyName') }}</label>
<input type="text" id="key-name" v-model="formData.name" 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 for="key-private" class="block text-sm font-medium text-text-secondary mb-1">{{ t('sshKeys.modal.privateKey') }}</label>
<textarea id="key-private" v-model="formData.private_key" rows="8" 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 font-mono text-sm"></textarea>
<small v-if="keyToEdit" class="block text-xs text-text-secondary mt-1">{{ t('sshKeys.modal.keyUpdateNote') }}</small>
</div>
<div>
<label for="key-passphrase" class="block text-sm font-medium text-text-secondary mb-1">{{ t('sshKeys.modal.passphrase') }} ({{ t('connections.form.optional') }})</label>
<input type="password" id="key-passphrase" v-model="formData.passphrase" 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" />
<small v-if="keyToEdit" class="block text-xs text-text-secondary mt-1">{{ t('sshKeys.modal.passphraseUpdateNote') }}</small>
</div>
<!-- Form Error -->
<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>
<!-- Form Actions -->
<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('sshKeys.modal.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">
{{ keyToEdit ? t('sshKeys.modal.saveChanges') : t('sshKeys.modal.addKey') }}
</button>
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,76 @@
<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { useSshKeysStore } from '../stores/sshKeys.store';
import SshKeyManagementModal from './SshKeyManagementModal.vue'; // Import the modal
const props = defineProps<{
modelValue: number | null; // The selected ssh_key_id (v-model)
}>();
const emit = defineEmits(['update:modelValue']); // Removed 'use-direct-input' event
const { t } = useI18n();
const sshKeysStore = useSshKeysStore();
const keys = computed(() => sshKeysStore.sshKeys);
const isLoading = computed(() => sshKeysStore.isLoading);
const isManagementModalVisible = ref(false);
// Internal state for the selected key ID
const selectedKeyId = ref<number | null>(props.modelValue); // Removed string type
// Watch for external changes to modelValue
watch(() => props.modelValue, (newVal) => {
selectedKeyId.value = newVal;
});
// Watch for internal changes and emit update or switch mode
watch(selectedKeyId, (newVal) => {
// Removed 'direct_input' check
if (typeof newVal === 'number') {
emit('update:modelValue', newVal); // Emit the selected key ID
} else {
emit('update:modelValue', null); // Handle clearing selection (when newVal is null)
}
});
const openManagementModal = () => {
isManagementModalVisible.value = true;
// Refresh keys list when modal opens, in case keys were added/deleted elsewhere
sshKeysStore.fetchSshKeys();
};
const closeManagementModal = () => {
isManagementModalVisible.value = false;
// Refresh keys list after modal closes
sshKeysStore.fetchSshKeys();
};
</script>
<template>
<div class="space-y-2">
<div class="flex items-center space-x-3">
<select id="ssh-key-select" v-model="selectedKeyId" :disabled="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('sshKeys.selector.selectPlaceholder') }}</option>
<option v-for="key in keys" :key="key.id" :value="key.id">
{{ key.name }}
</option>
<!-- Removed direct input option -->
</select>
<button type="button" @click="openManagementModal" :disabled="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('sshKeys.selector.manageKeysTitle')">
<i class="fas fa-cog"></i>
</button>
</div>
<div v-if="isLoading" class="text-xs text-text-secondary">{{ t('sshKeys.selector.loadingKeys') }}</div>
<div v-if="sshKeysStore.error" class="text-xs text-error">{{ t('sshKeys.selector.errorLoading', { error: sshKeysStore.error }) }}</div>
<!-- Key Management Modal -->
<SshKeyManagementModal v-if="isManagementModalVisible" @close="closeManagementModal" />
</div>
</template>