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>
+35 -1
View File
@@ -166,7 +166,11 @@
"sectionAuth": "Authentication",
"sectionAdvanced": "Advanced Options",
"testConnection": "Test Connection",
"testing": "Testing..."
"testing": "Testing...",
"sshKey": "SSH Key",
"privateKeyDirect": "Private Key Content",
"keyUpdateNoteDirect": "Leave private key and passphrase blank to keep the existing key when editing.",
"keyUpdateNoteSelected": "Select another key or use direct input to change the key when editing."
},
"test": {
"success": "Connection test successful!",
@@ -981,5 +985,35 @@
},
"terminalTabBar": {
"selectServerTitle": "Select server to connect"
},
"sshKeys": {
"selector": {
"selectPlaceholder": "Select an SSH key...",
"useDirectInput": "Or input key content directly",
"manageKeysTitle": "Manage SSH Keys",
"loadingKeys": "Loading keys..."
},
"modal": {
"title": "SSH Key Management",
"addKey": "Add Key",
"keyName": "Key Name",
"actions": "Actions",
"loading": "Loading...",
"noKeys": "No SSH keys found. Please add one.",
"close": "Close",
"addTitle": "Add New SSH Key",
"editTitle": "Edit SSH Key",
"privateKey": "Private Key Content",
"passphrase": "Passphrase",
"cancel": "Cancel",
"saveChanges": "Save Changes",
"edit": "Edit",
"delete": "Delete",
"errorFetchDetails": "Failed to fetch key details",
"errorRequiredFields": "Key name and private key content cannot be empty.",
"confirmDelete": "Are you sure you want to delete the key \"{name}\"? This cannot be undone.",
"keyUpdateNote": "Leave private key blank to keep the existing key. Passphrase always needs re-entry if required.",
"passphraseUpdateNote": "Leave blank to keep or remove the passphrase. Enter a new passphrase to update."
}
}
}
+35 -1
View File
@@ -138,7 +138,11 @@
"titleEdit": "接続の編集",
"typeRdp": "RDP",
"typeSsh": "SSH",
"username": "ユーザー名:"
"username": "ユーザー名:",
"sshKey": "SSH キー",
"privateKeyDirect": "秘密鍵の内容",
"keyUpdateNoteDirect": "編集時に既存のキーを保持するには、秘密鍵とパスフレーズを空のままにしてください。",
"keyUpdateNoteSelected": "編集時にキーを変更するには、別のキーを選択するか、直接入力を使用してください。"
},
"noConnections": "接続がありません。'新しい接続を追加'をクリックして作成してください。",
"noUntaggedConnections": "タグなしの接続はありません。",
@@ -984,5 +988,35 @@
"noResults": "\"{searchTerm}\"に一致する接続は見つかりませんでした。",
"searchPlaceholder": "名前またはホストを検索...",
"untagged": "タグなし"
},
"sshKeys": {
"selector": {
"selectPlaceholder": "SSH キーを選択...",
"useDirectInput": "またはキーの内容を直接入力",
"manageKeysTitle": "SSH キーを管理",
"loadingKeys": "キーを読み込み中..."
},
"modal": {
"title": "SSH キー管理",
"addKey": "キーを追加",
"keyName": "キー名",
"actions": "操作",
"loading": "読み込み中...",
"noKeys": "SSH キーが見つかりません。追加してください。",
"close": "閉じる",
"addTitle": "新しい SSH キーを追加",
"editTitle": "SSH キーを編集",
"privateKey": "秘密鍵の内容",
"passphrase": "パスフレーズ",
"cancel": "キャンセル",
"saveChanges": "変更を保存",
"edit": "編集",
"delete": "削除",
"errorFetchDetails": "キーの詳細の取得に失敗しました",
"errorRequiredFields": "キー名と秘密鍵の内容は空にできません。",
"confirmDelete": "キー \"{name}\" を削除しますか?この操作は元に戻せません。",
"keyUpdateNote": "既存のキーを保持するには、秘密鍵を空のままにしてください。パスフレーズは必要に応じて再入力する必要があります。",
"passphraseUpdateNote": "パスフレーズを保持または削除するには空のままにします。更新するには新しいパスフレーズを入力してください。"
}
}
}
+35 -1
View File
@@ -166,7 +166,11 @@
"sectionAuth": "认证信息",
"sectionAdvanced": "高级选项",
"testConnection": "测试连接",
"testing": "测试中..."
"testing": "测试中...",
"sshKey": "SSH 密钥",
"privateKeyDirect": "私钥内容",
"keyUpdateNoteDirect": "编辑时将私钥和密码短语留空以保留现有密钥。",
"keyUpdateNoteSelected": "编辑时选择其他密钥或使用直接输入来更改密钥。"
},
"test": {
"success": "连接测试成功!",
@@ -984,5 +988,35 @@
},
"terminalTabBar": {
"selectServerTitle": "选择要连接的服务器"
},
"sshKeys": {
"selector": {
"selectPlaceholder": "选择一个 SSH 密钥...",
"useDirectInput": "或直接输入密钥内容",
"manageKeysTitle": "管理 SSH 密钥",
"loadingKeys": "正在加载密钥..."
},
"modal": {
"title": "SSH 密钥管理",
"addKey": "添加密钥",
"keyName": "密钥名称",
"actions": "操作",
"loading": "加载中...",
"noKeys": "没有找到 SSH 密钥。请添加一个。",
"close": "关闭",
"addTitle": "添加新 SSH 密钥",
"editTitle": "编辑 SSH 密钥",
"privateKey": "私钥内容",
"passphrase": "私钥密码",
"cancel": "取消",
"saveChanges": "保存更改",
"edit": "编辑",
"delete": "删除",
"errorFetchDetails": "获取密钥详情失败",
"errorRequiredFields": "密钥名称和私钥内容不能为空。",
"confirmDelete": "确定要删除密钥 \"{name}\" 吗?此操作不可撤销。",
"keyUpdateNote": "将私钥留空以保留现有密钥。密码短语始终需要重新输入(如果需要)。",
"passphraseUpdateNote": "留空表示不修改或移除密码短语。输入新密码短语以更新。"
}
}
}
@@ -0,0 +1,153 @@
import { defineStore } from 'pinia';
import { ref } from 'vue';
import apiClient from '../utils/apiClient';
import { useUiNotificationsStore } from './uiNotifications.store'; // For displaying errors
// Interface for basic SSH key info (for lists)
export interface SshKeyBasicInfo {
id: number;
name: string;
}
// Interface for detailed SSH key info (including decrypted key for editing)
// Be cautious when handling decryptedPrivateKey in the UI
export interface SshKeyDetails extends SshKeyBasicInfo {
privateKey: string; // Decrypted private key
passphrase?: string; // Decrypted passphrase
}
// Interface for creating/updating SSH keys (sending to backend)
export interface SshKeyInput {
name: string;
private_key: string; // Plain text private key
passphrase?: string; // Plain text passphrase
}
export const useSshKeysStore = defineStore('sshKeys', () => {
const uiNotificationsStore = useUiNotificationsStore();
const sshKeys = ref<SshKeyBasicInfo[]>([]);
const isLoading = ref(false);
const error = ref<string | null>(null);
// --- Actions ---
// Fetch all SSH key names
async function fetchSshKeys() {
isLoading.value = true;
error.value = null;
try {
const response = await apiClient.get<SshKeyBasicInfo[]>('/ssh-keys');
sshKeys.value = response.data;
console.log('SSH Keys fetched:', sshKeys.value);
} catch (err: any) {
console.error('Failed to fetch SSH keys:', err);
error.value = err.response?.data?.message || err.message || '获取 SSH 密钥列表失败。';
// Ensure error.value is not null before passing
uiNotificationsStore.addNotification({ message: error.value ?? '未知错误', type: 'error' });
} finally {
isLoading.value = false;
}
}
// Add a new SSH key
async function addSshKey(keyInput: SshKeyInput): Promise<boolean> {
isLoading.value = true;
error.value = null;
try {
const response = await apiClient.post<{ message: string, key: SshKeyBasicInfo }>('/ssh-keys', keyInput);
// Add the new key to the local list
sshKeys.value.push(response.data.key);
// Sort keys by name
sshKeys.value.sort((a, b) => a.name.localeCompare(b.name));
uiNotificationsStore.addNotification({ message: response.data.message || 'SSH 密钥添加成功。', type: 'success' });
return true;
} catch (err: any) {
console.error('Failed to add SSH key:', err);
error.value = err.response?.data?.message || err.message || '添加 SSH 密钥失败。';
// Ensure error.value is not null before passing
uiNotificationsStore.addNotification({ message: error.value ?? '未知错误', type: 'error' });
return false;
} finally {
isLoading.value = false;
}
}
// Fetch decrypted details for a single key (used for editing)
async function fetchDecryptedSshKey(id: number): Promise<SshKeyDetails | null> {
isLoading.value = true; // Consider a different loading state if needed
error.value = null;
try {
// Use the dedicated details endpoint
const response = await apiClient.get<SshKeyDetails>(`/ssh-keys/${id}/details`);
return response.data;
} catch (err: any) {
console.error(`Failed to fetch decrypted SSH key ${id}:`, err);
error.value = err.response?.data?.message || err.message || `获取密钥 ${id} 详情失败。`;
// Ensure error.value is not null before passing
uiNotificationsStore.addNotification({ message: error.value ?? '未知错误', type: 'error' });
return null;
} finally {
isLoading.value = false; // Reset loading state
}
}
// Update an existing SSH key
async function updateSshKey(id: number, keyInput: Partial<SshKeyInput>): Promise<boolean> {
isLoading.value = true;
error.value = null;
try {
const response = await apiClient.put<{ message: string, key: SshKeyBasicInfo }>(`/ssh-keys/${id}`, keyInput);
// Update the key in the local list
const index = sshKeys.value.findIndex(key => key.id === id);
if (index !== -1) {
sshKeys.value[index] = { ...sshKeys.value[index], ...response.data.key }; // Update with new basic info
// Sort keys by name again if name changed
sshKeys.value.sort((a, b) => a.name.localeCompare(b.name));
}
uiNotificationsStore.addNotification({ message: response.data.message || 'SSH 密钥更新成功。', type: 'success' });
return true;
} catch (err: any) {
console.error(`Failed to update SSH key ${id}:`, err);
error.value = err.response?.data?.message || err.message || `更新 SSH 密钥 ${id} 失败。`;
// Ensure error.value is not null before passing
uiNotificationsStore.addNotification({ message: error.value ?? '未知错误', type: 'error' });
return false;
} finally {
isLoading.value = false;
}
}
// Delete an SSH key
async function deleteSshKey(id: number): Promise<boolean> {
isLoading.value = true;
error.value = null;
try {
const response = await apiClient.delete<{ message: string }>(`/ssh-keys/${id}`);
// Remove the key from the local list
sshKeys.value = sshKeys.value.filter(key => key.id !== id);
uiNotificationsStore.addNotification({ message: response.data.message || 'SSH 密钥删除成功。', type: 'success' });
return true;
} catch (err: any) {
console.error(`Failed to delete SSH key ${id}:`, err);
error.value = err.response?.data?.message || err.message || `删除 SSH 密钥 ${id} 失败。`;
// Ensure error.value is not null before passing
uiNotificationsStore.addNotification({ message: error.value ?? '未知错误', type: 'error' });
return false;
} finally {
isLoading.value = false;
}
}
return {
sshKeys,
isLoading,
error,
fetchSshKeys,
addSshKey,
fetchDecryptedSshKey,
updateSshKey,
deleteSshKey,
};
});