feat(tenant): expose API Key reset from the API Info page

Add a danger-themed reset button next to the existing copy/eye buttons
on the API Info settings page. Confirmation dialog warns that the old
key is revoked immediately; on success the new plaintext key replaces
the displayed value and is auto-revealed so the user can copy it.

Backend: new POST /api/v1/tenants/:id/api-key handler that wraps the
existing TenantService.UpdateAPIKey; access is gated by the same
authorizeTenantAccess check as other tenant endpoints. The handler
returns the freshly generated plaintext key, while the encrypted form
is persisted to the database.

Frontend: new resetTenantApiKey API client, reset button + confirm
dialog wiring in ApiInfo.vue, plus matching i18n entries for zh-CN,
en-US, ko-KR, and ru-RU.
This commit is contained in:
wizardchen
2026-04-29 20:00:46 +08:00
committed by lyingbug
parent cbdfba0075
commit 7fcd92994b
8 changed files with 150 additions and 3 deletions
+18 -1
View File
@@ -1,4 +1,4 @@
import { get } from '@/utils/request'
import { get, post } from '@/utils/request'
import i18n from '@/i18n'
const t = (key: string) => i18n.global.t(key)
@@ -53,6 +53,23 @@ export async function listAllTenants(): Promise<{ success: boolean; data?: { ite
}
}
/**
* 重置租户的 API Key。成功后返回新的明文 Key,旧 Key 立即失效。
*/
export async function resetTenantApiKey(
tenantId: number,
): Promise<{ success: boolean; data?: { api_key: string }; message?: string }> {
try {
const response = await post(`/api/v1/tenants/${tenantId}/api-key`)
return response as unknown as { success: boolean; data?: { api_key: string }; message?: string }
} catch (error: any) {
return {
success: false,
message: error.message || t('error.tenant.resetApiKeyFailed'),
}
}
}
/**
* 搜索租户(支持分页、关键词搜索和租户ID过滤)
*/
+8
View File
@@ -2206,6 +2206,13 @@ export default {
copyUrlTitle: 'Copy API URL',
urlCopySuccess: 'API URL copied to clipboard',
copyTitle: 'Copy API Key',
resetTitle: 'Reset API Key',
resetConfirmTitle: 'Reset API Key?',
resetConfirmBody: 'After reset, the old API Key is revoked immediately. Every app, SDK, and script using the old key must switch to the new key to keep working. This action cannot be undone.',
resetConfirmOk: 'Reset',
resetConfirmCancel: 'Cancel',
resetSuccess: 'API Key reset; the new key is shown in the field above',
resetFailed: 'Failed to reset API Key',
docLabel: 'API Documentation',
docDescription: 'View complete API documentation and examples,',
openDoc: 'Open documentation',
@@ -2316,6 +2323,7 @@ export default {
tenant: {
listFailed: 'Failed to list tenants',
searchFailed: 'Failed to search tenants',
resetApiKeyFailed: 'Failed to reset API Key',
},
initialization: {
checkFailed: 'Check failed',
+8
View File
@@ -1573,6 +1573,13 @@ export default {
copyUrlTitle: "API URL 복사",
urlCopySuccess: "API URL이 클립보드에 복사되었습니다",
copyTitle: "API 키 복사",
resetTitle: "API 키 재설정",
resetConfirmTitle: "API 키를 재설정할까요?",
resetConfirmBody: "재설정하면 기존 API 키는 즉시 무효화됩니다. 기존 키를 사용하는 앱, SDK, 스크립트는 모두 새 키로 교체해야 계속 사용할 수 있습니다. 이 작업은 되돌릴 수 없습니다.",
resetConfirmOk: "재설정",
resetConfirmCancel: "취소",
resetSuccess: "API 키가 재설정되었습니다. 새 키는 위 입력란에 표시됩니다",
resetFailed: "API 키 재설정에 실패했습니다",
docLabel: "API 문서",
docDescription: "전체 API 호출 문서 및 예시 보기, ",
openDoc: "문서 열기",
@@ -1684,6 +1691,7 @@ export default {
tenant: {
listFailed: '테넌트 목록 조회 실패',
searchFailed: '테넌트 검색 실패',
resetApiKeyFailed: 'API 키 재설정 실패',
},
initialization: {
checkFailed: '검사 실패',
+9 -1
View File
@@ -1391,6 +1391,13 @@ export default {
copyUrlTitle: 'Скопировать URL API',
urlCopySuccess: 'URL API скопирован в буфер обмена',
copyTitle: 'Скопировать API Key',
resetTitle: 'Сбросить API Key',
resetConfirmTitle: 'Сбросить API Key?',
resetConfirmBody: 'После сброса прежний API Key немедленно перестаёт действовать. Все приложения, SDK и скрипты, использующие старый ключ, должны быть переведены на новый ключ. Это действие нельзя отменить.',
resetConfirmOk: 'Сбросить',
resetConfirmCancel: 'Отмена',
resetSuccess: 'API Key сброшен; новый ключ показан в поле выше',
resetFailed: 'Не удалось сбросить API Key',
docLabel: 'Документация API',
docDescription: 'Ознакомьтесь с полной документацией и примерами API,',
openDoc: 'Открыть документацию',
@@ -1499,7 +1506,8 @@ export default {
},
tenant: {
listFailed: 'Не удалось получить список тенантов',
searchFailed: 'Не удалось выполнить поиск тенантов'
searchFailed: 'Не удалось выполнить поиск тенантов',
resetApiKeyFailed: 'Не удалось сбросить API Key'
},
initialization: {
checkFailed: 'Проверка не пройдена',
+8
View File
@@ -1554,6 +1554,13 @@ export default {
copyUrlTitle: "复制 API 地址",
urlCopySuccess: "API 地址已复制到剪贴板",
copyTitle: "复制 API Key",
resetTitle: "重置 API Key",
resetConfirmTitle: "确认重置 API Key?",
resetConfirmBody: "重置后,旧的 API Key 会立即失效,所有使用旧 Key 的应用、SDK 与脚本必须更换为新 Key 才能继续访问。此操作不可撤销。",
resetConfirmOk: "确认重置",
resetConfirmCancel: "取消",
resetSuccess: "API Key 已重置,新 Key 已显示在输入框中",
resetFailed: "重置 API Key 失败",
docLabel: "API 文档",
docDescription: "查看完整的 API 调用文档和示例,",
openDoc: "打开文档",
@@ -1664,6 +1671,7 @@ export default {
tenant: {
listFailed: "获取租户列表失败",
searchFailed: "搜索租户失败",
resetApiKeyFailed: "重置 API Key 失败",
},
initialization: {
checkFailed: "检查失败",
+50 -1
View File
@@ -51,6 +51,16 @@
>
<t-icon name="file-copy" />
</t-button>
<t-button
size="small"
variant="text"
theme="danger"
:loading="resetting"
:title="$t('tenant.api.resetTitle')"
@click="confirmResetApiKey"
>
<t-icon name="refresh" />
</t-button>
</div>
</div>
</div>
@@ -213,8 +223,9 @@
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { getCurrentUser, type TenantInfo, type UserInfo } from '@/api/auth'
import { resetTenantApiKey } from '@/api/tenant'
import { getApiBaseUrl } from '@/utils/api-base'
import { MessagePlugin } from 'tdesign-vue-next'
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
const { t, locale } = useI18n()
@@ -225,6 +236,7 @@ const userInfo = ref<UserInfo | null>(null)
const loading = ref(true)
const error = ref('')
const showApiKey = ref(false)
const resetting = ref(false)
/** WeKnora Lite (Wails): real API origin is loopback + dynamic port, not window.location.origin */
const wailsApiBaseURL = ref<string | null>(null)
const showDesktopPortSetting = ref(false)
@@ -441,6 +453,43 @@ const fallbackCopyText = (text: string) => {
document.body.removeChild(textArea)
}
const confirmResetApiKey = () => {
if (!tenantInfo.value?.id) {
MessagePlugin.warning(t('tenant.api.noKey'))
return
}
const dialog = DialogPlugin.confirm({
header: t('tenant.api.resetConfirmTitle'),
body: t('tenant.api.resetConfirmBody'),
confirmBtn: { content: t('tenant.api.resetConfirmOk'), theme: 'danger' },
cancelBtn: t('tenant.api.resetConfirmCancel'),
onConfirm: async () => {
await performResetApiKey()
dialog.destroy()
},
onClose: () => dialog.destroy(),
})
}
const performResetApiKey = async () => {
if (!tenantInfo.value?.id) return
resetting.value = true
try {
const resp = await resetTenantApiKey(tenantInfo.value.id)
if (resp.success && resp.data?.api_key) {
tenantInfo.value = { ...tenantInfo.value, api_key: resp.data.api_key }
showApiKey.value = true
MessagePlugin.success(t('tenant.api.resetSuccess'))
} else {
MessagePlugin.error(resp.message || t('tenant.api.resetFailed'))
}
} catch (err: any) {
MessagePlugin.error(err?.message || t('tenant.api.resetFailed'))
} finally {
resetting.value = false
}
}
const copyApiKey = async () => {
if (!tenantInfo.value?.api_key) {
MessagePlugin.warning(t('tenant.api.noKey'))
+48
View File
@@ -226,6 +226,54 @@ func (h *TenantHandler) UpdateTenant(c *gin.Context) {
})
}
// ResetAPIKey godoc
// @Summary 重置租户 API Key
// @Description 为指定租户生成一个新的 API Key,旧 Key 立即失效
// @Tags 租户管理
// @Accept json
// @Produce json
// @Param id path int true "租户ID"
// @Success 200 {object} map[string]interface{} "新生成的 API Key"
// @Failure 400 {object} errors.AppError "请求参数错误"
// @Failure 403 {object} errors.AppError "权限不足"
// @Security Bearer
// @Router /tenants/{id}/api-key [post]
func (h *TenantHandler) ResetAPIKey(c *gin.Context) {
ctx := c.Request.Context()
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
if err != nil {
logger.Errorf(ctx, "Invalid tenant ID: %s", secutils.SanitizeForLog(c.Param("id")))
c.Error(errors.NewBadRequestError("Invalid tenant ID"))
return
}
if _, ok := h.authorizeTenantAccess(c, id); !ok {
return
}
logger.Infof(ctx, "Resetting API key for tenant, ID: %d", id)
apiKey, err := h.service.UpdateAPIKey(ctx, id)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to reset API key: application error", appErr)
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to reset API key").WithDetails(err.Error()))
}
return
}
logger.Infof(ctx, "API key reset successfully, tenant ID: %d", id)
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"api_key": apiKey,
},
})
}
// DeleteTenant godoc
// @Summary 删除租户
// @Description 删除指定的租户
+1
View File
@@ -369,6 +369,7 @@ func RegisterTenantRoutes(r *gin.RouterGroup, handler *handler.TenantHandler) {
tenantRoutes.GET("/:id", handler.GetTenant)
tenantRoutes.PUT("/:id", handler.UpdateTenant)
tenantRoutes.DELETE("/:id", handler.DeleteTenant)
tenantRoutes.POST("/:id/api-key", handler.ResetAPIKey)
tenantRoutes.GET("", handler.ListTenants)
// Generic KV configuration management (tenant-level)