feature: add api key

This commit is contained in:
zhaoying
2025-12-16 13:54:41 +08:00
parent 36cab874fa
commit 44ceee3f42
18 changed files with 1028 additions and 169 deletions

View File

@@ -0,0 +1,102 @@
import { forwardRef, useImperativeHandle, useState } from 'react';
import { Switch, Button } from 'antd';
import clsx from 'clsx';
import { useTranslation } from 'react-i18next';
import type { ApiKey, ApiKeyModalRef } from '../types';
import RbModal from '@/components/RbModal'
import { getApiKey } from '@/api/apiKey';
import { formatDateTime } from '@/utils/format'
import Tag from '@/components/Tag'
import { maskApiKeys } from '@/utils/apiKeyReplacer';
const ApiKeyDetailModal = forwardRef<ApiKeyModalRef, { handleCopy: (content: string) => void }>(({ handleCopy }, ref) => {
const { t } = useTranslation();
const [visible, setVisible] = useState(false);
const [data, setData] = useState<ApiKey>({} as ApiKey)
// 封装取消方法,添加关闭弹窗逻辑
const handleClose = () => {
setVisible(false);
};
const handleOpen = (apiKey?: ApiKey) => {
if (apiKey?.id) {
getApiKey(apiKey.id)
.then((res) => {
setVisible(true);
setData(res as ApiKey)
})
}
};
// 暴露给父组件的方法
useImperativeHandle(ref, () => ({
handleOpen,
handleClose
}));
return (
<RbModal
title={t('apiKey.viewDetail')}
open={visible}
onCancel={handleClose}
>
<div className="rb:text-[#5B6167] rb:font-medium rb:leading-5 rb:mb-4">{t('apiKey.baseInfo')}</div>
{['id', 'name', 'is_expired', 'created_at'].map((key, index) => (
<div key={key} className={clsx("rb:flex rb:justify-between rb:gap-5 rb:font-regular rb:text-[14px]", {
'rb:mt-3': index !== 0
})}>
<span className="rb:text-[#5B6167]">{t(`apiKey.${key}`)}</span>
<span className="rb:text-right rb:flex-1 rb:text-ellipsis rb:overflow-hidden rb:whitespace-nowrap">
{ key === 'created_at'
? formatDateTime(data[key], 'YYYY-MM-DD HH:mm:ss')
: key === 'is_expired'
? <Tag>{data[key] ? t('apiKey.inactive') : t('apiKey.active')}</Tag>
: String(data[key as keyof ApiKey])
}
</span>
</div>
))}
<div className="rb:flex rb:items-center rb:justify-between rb:text-[#5B6167] rb:mt-5 rb:p-[8px_16px] rb:bg-[#FFFFFF] rb:border rb:border-[#DFE4ED] rb:rounded-lg rb:leading-5">
{maskApiKeys(data.api_key)}
<Button className="rb:px-2! rb:h-7! rb:group" onClick={() => handleCopy(data.api_key)}>
<div
className="rb:w-4 rb:h-4 rb:cursor-pointer rb:bg-cover rb:bg-[url('@/assets/images/copy.svg')] rb:group-hover:bg-[url('@/assets/images/copy_active.svg')]"
></div>
{t('common.copy')}
</Button>
</div>
<div className="rb:text-[#5B6167] rb:font-medium rb:leading-5 rb:my-4">{t('apiKey.permissionInfo')}</div>
<div className="rb:flex rb:justify-between rb:gap-5 rb:font-regular rb:text-[14px] rb:mt-3">
<span className="rb:text-[#5B6167]">{t(`apiKey.memoryEngine`)}</span>
<span>
<Switch checked={data.scopes?.includes('memory')} disabled />
</span>
</div>
<div className="rb:flex rb:justify-between rb:gap-5 rb:font-regular rb:text-[14px] rb:mt-3">
<span className="rb:text-[#5B6167]">{t(`apiKey.knowledgeBase`)}</span>
<span>
<Switch checked={data.scopes?.includes('rag')} disabled />
</span>
</div>
{/* 高级设置 */}
{data.expires_at && <>
<div className="rb:text-[#5B6167] rb:font-medium rb:leading-5 rb:my-4">{t('apiKey.advancedSettings')}</div>
<div className="rb:flex rb:justify-between rb:gap-5 rb:font-regular rb:text-[14px] rb:mt-3">
<span className="rb:text-[#5B6167]">{t(`apiKey.expires_at`)}</span>
<span>
{data.expires_at ? formatDateTime(data.expires_at as number, 'yyyy-MM-DD') : '-'}
</span>
</div>
</>}
</RbModal>
);
});
export default ApiKeyDetailModal;

View File

@@ -0,0 +1,153 @@
import { forwardRef, useImperativeHandle, useState } from 'react';
import { Form, Input, Switch, App, DatePicker } from 'antd';
import { useTranslation } from 'react-i18next';
import type { ApiKey, ApiKeyModalRef } from '../types';
import RbModal from '@/components/RbModal'
import dayjs from 'dayjs'
import { createApiKey, updateApiKey } from '@/api/apiKey';
const FormItem = Form.Item;
interface CreateModalProps {
refresh: () => void;
}
const ApiKeyModal = forwardRef<ApiKeyModalRef, CreateModalProps>(({
refresh,
}, ref) => {
const { t } = useTranslation();
const { message } = App.useApp();
const [visible, setVisible] = useState(false);
const [form] = Form.useForm<ApiKey>();
const [loading, setLoading] = useState(false);
const [editVo, setEditVo] = useState<ApiKey | null>(null);
// 封装取消方法,添加关闭弹窗逻辑
const handleClose = () => {
setVisible(false);
form.resetFields();
setLoading(false);
setEditVo(null);
};
const handleOpen = (apiKey?: ApiKey) => {
if (apiKey?.id) {
const { scopes = [], expires_at } = apiKey
// 编辑模式,填充表单
form.setFieldsValue({
name: apiKey.name,
description: apiKey.description,
memory: scopes.includes('memory'),
rag: scopes.includes('rag'),
expires_at: expires_at ? dayjs(expires_at) : undefined
});
setEditVo(apiKey);
}
setVisible(true);
};
// 封装保存方法,添加提交逻辑
const handleSave = async () => {
form.validateFields()
.then((values) => {
const { memory, rag, expires_at, ...rest } = values
let scopes = []
if (memory) {
scopes.push('memory')
}
if (rag) {
scopes.push('rag')
}
// 准备新的/更新的API Key数据
const apiKeyData = {
...rest,
scopes,
expires_at: expires_at ? dayjs(expires_at.valueOf()).endOf('day').valueOf() : null,
type: 'service'
};
setLoading(true)
const req = editVo?.id ? updateApiKey(editVo.id, apiKeyData as ApiKey) : createApiKey(apiKeyData as ApiKey)
req.then(() => {
refresh();
handleClose();
message.success(t(editVo ? 'common.updateSuccess' : 'common.createSuccess'));
})
.finally(() => setLoading(false))
})
}
// 暴露给父组件的方法
useImperativeHandle(ref, () => ({
handleOpen,
handleClose
}));
return (
<RbModal
title={editVo ? t('apiKey.updateApiKey') : t('apiKey.createApiKey')}
open={visible}
onCancel={handleClose}
okText={t('common.save')}
onOk={handleSave}
confirmLoading={loading}
>
<Form
form={form}
layout="vertical"
>
<div className="rb:text-[#5B6167] rb:font-medium rb:leading-5 rb:mb-4">{t('apiKey.baseInfo')}</div>
<FormItem
name="name"
label={t('apiKey.name')}
rules={[{ required: true, message: t('common.pleaseEnter') }]}
>
<Input placeholder={t('common.enter')} />
</FormItem>
<FormItem
name="description"
label={t('apiKey.description')}
>
<Input.TextArea placeholder={t('common.pleaseEnter')} rows={3} />
</FormItem>
<div className="rb:text-[#5B6167] rb:font-medium rb:leading-5 rb:mb-4">{t('apiKey.permissionInfo')}</div>
<FormItem
name="memory"
label={t('apiKey.memoryEngine')}
layout="horizontal"
valuePropName="checked"
>
<Switch />
</FormItem>
<FormItem
name="rag"
label={t('apiKey.knowledgeBase')}
layout="horizontal"
valuePropName="checked"
>
<Switch />
</FormItem>
{/* 高级设置 */}
<div className="rb:text-[#5B6167] rb:font-medium rb:leading-5 rb:mb-4">{t('apiKey.advancedSettings')}</div>
<FormItem
name="expires_at"
label={t('apiKey.expires_at')}
>
<DatePicker
className="rb:w-full"
disabledDate={(current) => current && current < dayjs().subtract(1, 'day').endOf('day')}
/>
</FormItem>
</Form>
</RbModal>
);
});
export default ApiKeyModal;

View File

@@ -0,0 +1,125 @@
import React, { useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, App, Space } from 'antd';
import clsx from 'clsx';
import { DeleteOutlined, EditOutlined, EyeOutlined } from '@ant-design/icons';
import type { ApiKey, ApiKeyModalRef } from './types';
import ApiKeyModal from './components/ApiKeyModal';
import ApiKeyDetailModal from './components/ApiKeyDetailModal';
import RbCard from '@/components/RbCard/Card'
import { getApiKeyListUrl, deleteApiKey } from '@/api/apiKey';
import PageScrollList, { type PageScrollListRef } from '@/components/PageScrollList'
import { formatDateTime } from '@/utils/format';
import Tag from '@/components/Tag'
import copy from 'copy-to-clipboard'
import { maskApiKeys } from '@/utils/apiKeyReplacer';
const ApiKeyManagement: React.FC = () => {
const { t } = useTranslation();
const { modal, message } = App.useApp();
const apiKeyModalRef = useRef<ApiKeyModalRef>(null);
const apiKeyDetailModalRef = useRef<ApiKeyModalRef>(null)
const scrollListRef = useRef<PageScrollListRef>(null)
const refresh = () => {
scrollListRef.current?.refresh();
}
const handleEdit = (item?: ApiKey) => {
apiKeyModalRef.current?.handleOpen(item);
}
const handleView = (item: ApiKey) => {
apiKeyDetailModalRef.current?.handleOpen(item);
}
const handleDelete = (item: ApiKey) => {
modal.confirm({
title: t('common.confirmDeleteDesc', { name: item.name }),
okText: t('common.delete'),
okType: 'danger',
onOk: () => {
deleteApiKey(item.id)
.then(() => {
refresh();
message.success(t('common.deleteSuccess'))
})
}
})
}
const handleCopy = (content: string) => {
copy(content)
message.success(t('common.copySuccess'))
}
return (
<>
<div className="rb:flex rb:justify-end rb:mb-3 rb:p-4">
<Button type="primary" onClick={() => handleEdit()}>
{t('apiKey.createApiKey')}
</Button>
</div>
<PageScrollList
ref={scrollListRef}
url={getApiKeyListUrl}
query={{ is_active: true, type: 'service' }}
column={2}
renderItem={(item: Record<string, unknown>) => {
let apiKeyItem = item as unknown as ApiKey
return (
<RbCard
title={apiKeyItem.name}
>
{['id', 'is_expired', 'created_at'].map((key, index) => (
<div key={key} className={clsx("rb:flex rb:justify-between rb:gap-5 rb:font-regular rb:text-[14px]", {
'rb:mt-3': index !== 0
})}>
<span className="rb:text-[#5B6167]">{t(`apiKey.${key}`)}</span>
<span>
{ key === 'created_at'
? formatDateTime(apiKeyItem[key], 'YYYY-MM-DD HH:mm:ss')
: key === 'is_expired'
? <Tag>{apiKeyItem[key] ? t('apiKey.inactive') : t('apiKey.active')}</Tag>
: String(apiKeyItem[key as keyof ApiKey])
}
</span>
</div>
))}
<div className="rb:flex rb:items-center rb:justify-between rb:text-[#5B6167] rb:mt-5 rb:p-[8px_16px] rb:bg-[#FFFFFF] rb:border rb:border-[#DFE4ED] rb:rounded-lg rb:leading-5">
{maskApiKeys(apiKeyItem.api_key)}
<Button className="rb:px-2! rb:h-7! rb:group" onClick={() => handleCopy(apiKeyItem.api_key)}>
<div
className="rb:w-4 rb:h-4 rb:cursor-pointer rb:bg-cover rb:bg-[url('@/assets/images/copy.svg')] rb:group-hover:bg-[url('@/assets/images/copy_active.svg')]"
></div>
{t('common.copy')}
</Button>
</div>
<Space className="rb:pt-2 rb:min-h-6.25">
{apiKeyItem.scopes?.includes('memory') && <Tag>{t('apiKey.memoryEngine')}</Tag>}
{apiKeyItem.scopes?.includes('rag') && <Tag color="success">{t('apiKey.knowledgeBase')}</Tag>}
</Space>
<div className="rb:mt-5 rb:flex rb:justify-end rb:gap-2.5">
<Button icon={<EyeOutlined />} onClick={() => handleView(apiKeyItem)}></Button>
<Button icon={<EditOutlined />} onClick={() => handleEdit(apiKeyItem)}></Button>
<Button icon={<DeleteOutlined />} onClick={() => handleDelete(apiKeyItem)}></Button>
</div>
</RbCard>
);
}}
/>
<ApiKeyModal
ref={apiKeyModalRef}
refresh={refresh}
/>
<ApiKeyDetailModal
ref={apiKeyDetailModalRef}
handleCopy={handleCopy}
/>
</>
);
};
export default ApiKeyManagement;

View File

@@ -0,0 +1,40 @@
import type { Dayjs } from 'dayjs'
import { maskApiKeys } from '@/utils/apiKeyReplacer'
export interface ApiKey {
id: string;
name: string;
description?: string;
type: 'agent' | 'multi_agent' | 'workflow' | 'service';
scopes?: string[]; // 'memory' | 'rag' | 'app'
api_key: string;
is_active: boolean;
is_expired: boolean;
created_at: number;
expires_at?: number | Dayjs;
memory?: boolean;
rag?: boolean;
updated_at: string;
qps_limit?: number;
daily_request_limit?: number;
rate_limit?: number;
total_requests: number;
quota_used: number;
quota_limit: number;
}
export interface ApiKeyModalRef {
handleOpen: (apiKey?: ApiKey) => void;
handleClose: () => void;
}
/**
* 获取掩码后的API密钥
*/
export const getMaskedApiKey = (apiKey: string): string => {
return maskApiKeys(apiKey)
}