chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
@@ -0,0 +1,15 @@
|
||||
import { AuthCategory } from '../../types'
|
||||
import { getApi } from '../get-api'
|
||||
|
||||
it('keeps the legacy credential-info endpoint for tools', () => {
|
||||
expect(getApi({ category: AuthCategory.tool, provider: 'test-provider' }).getCredentialInfo).toBe(
|
||||
'/workspaces/current/tool-provider/builtin/test-provider/credential/info',
|
||||
)
|
||||
})
|
||||
|
||||
it.each([AuthCategory.datasource, AuthCategory.model, AuthCategory.trigger])(
|
||||
'does not request legacy credential info for %s',
|
||||
(category) => {
|
||||
expect(getApi({ category, provider: 'test-provider' }).getCredentialInfo).toBe('')
|
||||
},
|
||||
)
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
import type { PluginPayload } from '../../types'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import { createElement } from 'react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import { AuthCategory, CredentialTypeEnum } from '../../types'
|
||||
import {
|
||||
useAddPluginCredentialHook,
|
||||
useDeletePluginCredentialHook,
|
||||
useDeletePluginOAuthCustomClientHook,
|
||||
useGetPluginCredentialInfoHook,
|
||||
useGetPluginCredentialSchemaHook,
|
||||
useGetPluginOAuthClientSchemaHook,
|
||||
useGetPluginOAuthUrlHook,
|
||||
useInvalidPluginCredentialInfoHook,
|
||||
useInvalidPluginOAuthClientSchemaHook,
|
||||
useSetPluginDefaultCredentialHook,
|
||||
useSetPluginOAuthCustomClientHook,
|
||||
useUpdatePluginCredentialHook,
|
||||
} from '../use-credential'
|
||||
|
||||
// Mock service hooks
|
||||
const mockUseGetPluginCredentialInfo = vi.fn().mockReturnValue({ data: null, isLoading: false })
|
||||
const mockUseDeletePluginCredential = vi.fn().mockReturnValue({ mutateAsync: vi.fn() })
|
||||
const mockUseInvalidPluginCredentialInfo = vi.fn().mockReturnValue(vi.fn())
|
||||
const mockUseSetPluginDefaultCredential = vi.fn().mockReturnValue({ mutateAsync: vi.fn() })
|
||||
const mockUseGetPluginCredentialSchema = vi.fn().mockReturnValue({ data: [], isLoading: false })
|
||||
const mockUseAddPluginCredential = vi.fn().mockReturnValue({ mutateAsync: vi.fn() })
|
||||
const mockUseUpdatePluginCredential = vi.fn().mockReturnValue({ mutateAsync: vi.fn() })
|
||||
const mockUseGetPluginOAuthUrl = vi.fn().mockReturnValue({ mutateAsync: vi.fn() })
|
||||
const mockUseGetPluginOAuthClientSchema = vi.fn().mockReturnValue({ data: null, isLoading: false })
|
||||
const mockUseInvalidPluginOAuthClientSchema = vi.fn().mockReturnValue(vi.fn())
|
||||
const mockUseSetPluginOAuthCustomClient = vi.fn().mockReturnValue({ mutateAsync: vi.fn() })
|
||||
const mockUseDeletePluginOAuthCustomClient = vi.fn().mockReturnValue({ mutateAsync: vi.fn() })
|
||||
|
||||
vi.mock('@/service/use-plugins-auth', () => ({
|
||||
useGetPluginCredentialInfo: (...args: unknown[]) => mockUseGetPluginCredentialInfo(...args),
|
||||
useDeletePluginCredential: (...args: unknown[]) => mockUseDeletePluginCredential(...args),
|
||||
useInvalidPluginCredentialInfo: (...args: unknown[]) =>
|
||||
mockUseInvalidPluginCredentialInfo(...args),
|
||||
useSetPluginDefaultCredential: (...args: unknown[]) => mockUseSetPluginDefaultCredential(...args),
|
||||
useGetPluginCredentialSchema: (...args: unknown[]) => mockUseGetPluginCredentialSchema(...args),
|
||||
useAddPluginCredential: (...args: unknown[]) => mockUseAddPluginCredential(...args),
|
||||
useUpdatePluginCredential: (...args: unknown[]) => mockUseUpdatePluginCredential(...args),
|
||||
useGetPluginOAuthUrl: (...args: unknown[]) => mockUseGetPluginOAuthUrl(...args),
|
||||
useGetPluginOAuthClientSchema: (...args: unknown[]) => mockUseGetPluginOAuthClientSchema(...args),
|
||||
useInvalidPluginOAuthClientSchema: (...args: unknown[]) =>
|
||||
mockUseInvalidPluginOAuthClientSchema(...args),
|
||||
useSetPluginOAuthCustomClient: (...args: unknown[]) => mockUseSetPluginOAuthCustomClient(...args),
|
||||
useDeletePluginOAuthCustomClient: (...args: unknown[]) =>
|
||||
mockUseDeletePluginOAuthCustomClient(...args),
|
||||
}))
|
||||
|
||||
const toolPayload = {
|
||||
category: AuthCategory.tool,
|
||||
provider: 'test-provider',
|
||||
providerType: 'builtin',
|
||||
} satisfies PluginPayload
|
||||
|
||||
describe('use-credential hooks', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('useGetPluginCredentialInfoHook', () => {
|
||||
it('should call service with correct URL when enabled', () => {
|
||||
renderHook(() => useGetPluginCredentialInfoHook(toolPayload, true))
|
||||
expect(mockUseGetPluginCredentialInfo).toHaveBeenCalledWith(
|
||||
`/workspaces/current/tool-provider/builtin/${toolPayload.provider}/credential/info`,
|
||||
)
|
||||
})
|
||||
|
||||
it('should pass empty string when disabled', () => {
|
||||
renderHook(() => useGetPluginCredentialInfoHook(toolPayload, false))
|
||||
expect(mockUseGetPluginCredentialInfo).toHaveBeenCalledWith('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDeletePluginCredentialHook', () => {
|
||||
it('should call service with correct URL', () => {
|
||||
renderHook(() => useDeletePluginCredentialHook(toolPayload))
|
||||
expect(mockUseDeletePluginCredential).toHaveBeenCalledWith(toolPayload)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useInvalidPluginCredentialInfoHook', () => {
|
||||
it('should return a function that invalidates both credential info and tools', () => {
|
||||
const queryClient = new QueryClient()
|
||||
const builtInToolsKey = consoleQuery.workspaces.current.tools.builtin.get.queryKey()
|
||||
const customToolsKey = consoleQuery.workspaces.current.tools.api.get.queryKey()
|
||||
queryClient.setQueryData(builtInToolsKey, [])
|
||||
queryClient.setQueryData(customToolsKey, [])
|
||||
const { result } = renderHook(() => useInvalidPluginCredentialInfoHook(toolPayload), {
|
||||
wrapper: ({ children }) =>
|
||||
createElement(QueryClientProvider, { client: queryClient }, children),
|
||||
})
|
||||
|
||||
result.current()
|
||||
|
||||
const invalidFn = mockUseInvalidPluginCredentialInfo.mock.results[0]!.value
|
||||
expect(invalidFn).toHaveBeenCalled()
|
||||
expect(queryClient.getQueryState(builtInToolsKey)?.isInvalidated).toBe(true)
|
||||
expect(queryClient.getQueryState(customToolsKey)?.isInvalidated).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useSetPluginDefaultCredentialHook', () => {
|
||||
it('should call service with correct URL', () => {
|
||||
renderHook(() => useSetPluginDefaultCredentialHook(toolPayload))
|
||||
expect(mockUseSetPluginDefaultCredential).toHaveBeenCalledWith(toolPayload)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useGetPluginCredentialSchemaHook', () => {
|
||||
it('should call service with correct schema URL for API_KEY', () => {
|
||||
renderHook(() => useGetPluginCredentialSchemaHook(toolPayload, CredentialTypeEnum.API_KEY))
|
||||
expect(mockUseGetPluginCredentialSchema).toHaveBeenCalledWith(
|
||||
toolPayload,
|
||||
CredentialTypeEnum.API_KEY,
|
||||
)
|
||||
})
|
||||
|
||||
it('should call service with correct schema URL for OAUTH2', () => {
|
||||
renderHook(() => useGetPluginCredentialSchemaHook(toolPayload, CredentialTypeEnum.OAUTH2))
|
||||
expect(mockUseGetPluginCredentialSchema).toHaveBeenCalledWith(
|
||||
toolPayload,
|
||||
CredentialTypeEnum.OAUTH2,
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useAddPluginCredentialHook', () => {
|
||||
it('should call service with correct URL', () => {
|
||||
renderHook(() => useAddPluginCredentialHook(toolPayload))
|
||||
expect(mockUseAddPluginCredential).toHaveBeenCalledWith(toolPayload)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useUpdatePluginCredentialHook', () => {
|
||||
it('should call service with correct URL', () => {
|
||||
renderHook(() => useUpdatePluginCredentialHook(toolPayload))
|
||||
expect(mockUseUpdatePluginCredential).toHaveBeenCalledWith(toolPayload)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useGetPluginOAuthUrlHook', () => {
|
||||
it('should call service with correct URL', () => {
|
||||
renderHook(() => useGetPluginOAuthUrlHook(toolPayload))
|
||||
expect(mockUseGetPluginOAuthUrl).toHaveBeenCalledWith(toolPayload)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useGetPluginOAuthClientSchemaHook', () => {
|
||||
it('should call service with correct URL', () => {
|
||||
renderHook(() => useGetPluginOAuthClientSchemaHook(toolPayload))
|
||||
expect(mockUseGetPluginOAuthClientSchema).toHaveBeenCalledWith(toolPayload, true)
|
||||
})
|
||||
|
||||
it('should disable the service query when OAuth data is provided by the caller', () => {
|
||||
renderHook(() => useGetPluginOAuthClientSchemaHook(toolPayload, false))
|
||||
|
||||
expect(mockUseGetPluginOAuthClientSchema).toHaveBeenCalledWith(toolPayload, false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useInvalidPluginOAuthClientSchemaHook', () => {
|
||||
it('should call service with correct URL', () => {
|
||||
renderHook(() => useInvalidPluginOAuthClientSchemaHook(toolPayload))
|
||||
expect(mockUseInvalidPluginOAuthClientSchema).toHaveBeenCalledWith(toolPayload)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useSetPluginOAuthCustomClientHook', () => {
|
||||
it('should call service with correct URL', () => {
|
||||
renderHook(() => useSetPluginOAuthCustomClientHook(toolPayload))
|
||||
expect(mockUseSetPluginOAuthCustomClient).toHaveBeenCalledWith(toolPayload)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDeletePluginOAuthCustomClientHook', () => {
|
||||
it('should call service with correct URL', () => {
|
||||
renderHook(() => useDeletePluginOAuthCustomClientHook(toolPayload))
|
||||
expect(mockUseDeletePluginOAuthCustomClient).toHaveBeenCalledWith(toolPayload)
|
||||
})
|
||||
})
|
||||
})
|
||||
+200
@@ -0,0 +1,200 @@
|
||||
import type { ReactNode } from 'react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { act, renderHook } from '@testing-library/react'
|
||||
import * as React from 'react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { createDeferred } from '@/test/deferred'
|
||||
import { usePluginAuthAction } from '../../hooks/use-plugin-auth-action'
|
||||
import { AuthCategory } from '../../types'
|
||||
|
||||
const mockDeletePluginCredential = vi.fn().mockResolvedValue({})
|
||||
const mockSetPluginDefaultCredential = vi.fn().mockResolvedValue({})
|
||||
const mockUpdatePluginCredential = vi.fn().mockResolvedValue({})
|
||||
const toastMocks = vi.hoisted(() => ({
|
||||
call: vi.fn(),
|
||||
dismiss: vi.fn(),
|
||||
update: vi.fn(),
|
||||
promise: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/app/notifications', () => ({
|
||||
toast: Object.assign(toastMocks.call, {
|
||||
success: vi.fn((message: string, options?: Record<string, unknown>) =>
|
||||
toastMocks.call({ type: 'success', message, ...options }),
|
||||
),
|
||||
error: vi.fn((message: string, options?: Record<string, unknown>) =>
|
||||
toastMocks.call({ type: 'error', message, ...options }),
|
||||
),
|
||||
warning: vi.fn((message: string, options?: Record<string, unknown>) =>
|
||||
toastMocks.call({ type: 'warning', message, ...options }),
|
||||
),
|
||||
info: vi.fn((message: string, options?: Record<string, unknown>) =>
|
||||
toastMocks.call({ type: 'info', message, ...options }),
|
||||
),
|
||||
dismiss: toastMocks.dismiss,
|
||||
update: toastMocks.update,
|
||||
promise: toastMocks.promise,
|
||||
}),
|
||||
}))
|
||||
vi.mock('../../hooks/use-credential', () => ({
|
||||
useDeletePluginCredentialHook: () => ({
|
||||
mutateAsync: mockDeletePluginCredential,
|
||||
}),
|
||||
useSetPluginDefaultCredentialHook: () => ({
|
||||
mutateAsync: mockSetPluginDefaultCredential,
|
||||
}),
|
||||
useUpdatePluginCredentialHook: () => ({
|
||||
mutateAsync: mockUpdatePluginCredential,
|
||||
}),
|
||||
}))
|
||||
|
||||
const pluginPayload = {
|
||||
category: AuthCategory.tool,
|
||||
provider: 'test-provider',
|
||||
}
|
||||
|
||||
function createWrapper() {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
})
|
||||
return function Wrapper({ children }: { children: ReactNode }) {
|
||||
return React.createElement(QueryClientProvider, { client: queryClient }, children)
|
||||
}
|
||||
}
|
||||
|
||||
describe('usePluginAuthAction', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should open and close confirm dialog', () => {
|
||||
const { result } = renderHook(() => usePluginAuthAction(pluginPayload), {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
|
||||
act(() => {
|
||||
result.current.openConfirm('cred-1')
|
||||
})
|
||||
expect(result.current.deleteCredentialId).toBe('cred-1')
|
||||
|
||||
act(() => {
|
||||
result.current.closeConfirm()
|
||||
})
|
||||
expect(result.current.deleteCredentialId).toBeNull()
|
||||
})
|
||||
|
||||
it('opens deletion confirmation for the credential being edited', () => {
|
||||
const { result } = renderHook(() => usePluginAuthAction(pluginPayload), {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
|
||||
act(() => {
|
||||
result.current.handleEdit('cred-1', { key: 'value' })
|
||||
})
|
||||
expect(result.current.editValues).toEqual({ key: 'value' })
|
||||
|
||||
act(() => {
|
||||
result.current.handleRemove()
|
||||
})
|
||||
expect(result.current.deleteCredentialId).toBe('cred-1')
|
||||
})
|
||||
|
||||
it('should handle confirm delete', async () => {
|
||||
const mockOnUpdate = vi.fn()
|
||||
const { result } = renderHook(() => usePluginAuthAction(pluginPayload, mockOnUpdate), {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
|
||||
act(() => {
|
||||
result.current.openConfirm('cred-1')
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleConfirm()
|
||||
})
|
||||
|
||||
expect(mockDeletePluginCredential).toHaveBeenCalledWith({ credential_id: 'cred-1' })
|
||||
expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }))
|
||||
expect(mockOnUpdate).toHaveBeenCalled()
|
||||
expect(result.current.deleteCredentialId).toBeNull()
|
||||
})
|
||||
|
||||
it('should handle set default credential', async () => {
|
||||
const mockOnUpdate = vi.fn()
|
||||
const { result } = renderHook(() => usePluginAuthAction(pluginPayload, mockOnUpdate), {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleSetDefault('cred-1')
|
||||
})
|
||||
|
||||
expect(mockSetPluginDefaultCredential).toHaveBeenCalledWith('cred-1')
|
||||
expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }))
|
||||
expect(mockOnUpdate).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('should handle rename credential', async () => {
|
||||
const mockOnUpdate = vi.fn()
|
||||
const { result } = renderHook(() => usePluginAuthAction(pluginPayload, mockOnUpdate), {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleRename({
|
||||
credential_id: 'cred-1',
|
||||
name: 'New Name',
|
||||
})
|
||||
})
|
||||
|
||||
expect(mockUpdatePluginCredential).toHaveBeenCalledWith({
|
||||
credential_id: 'cred-1',
|
||||
name: 'New Name',
|
||||
})
|
||||
expect(toastMocks.call).toHaveBeenCalledWith(expect.objectContaining({ type: 'success' }))
|
||||
expect(mockOnUpdate).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('prevents concurrent actions until the pending deletion completes', async () => {
|
||||
const deletion = createDeferred<object>()
|
||||
mockDeletePluginCredential.mockReturnValueOnce(deletion.promise)
|
||||
const { result } = renderHook(() => usePluginAuthAction(pluginPayload), {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
act(() => result.current.openConfirm('cred-1'))
|
||||
let pending: Promise<void>
|
||||
act(() => {
|
||||
pending = result.current.handleConfirm()
|
||||
})
|
||||
expect(result.current.doingAction).toBe(true)
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleConfirm()
|
||||
await result.current.handleSetDefault('cred-2')
|
||||
await result.current.handleRename({ credential_id: 'cred-2', name: 'New name' })
|
||||
})
|
||||
expect(mockDeletePluginCredential).toHaveBeenCalledExactlyOnceWith({ credential_id: 'cred-1' })
|
||||
expect(mockSetPluginDefaultCredential).not.toHaveBeenCalled()
|
||||
expect(mockUpdatePluginCredential).not.toHaveBeenCalled()
|
||||
|
||||
await act(async () => {
|
||||
deletion.resolve({})
|
||||
await pending
|
||||
})
|
||||
expect(result.current.doingAction).toBe(false)
|
||||
expect(result.current.deleteCredentialId).toBeNull()
|
||||
})
|
||||
|
||||
it('should handle confirm without pending credential ID', async () => {
|
||||
const { result } = renderHook(() => usePluginAuthAction(pluginPayload), {
|
||||
wrapper: createWrapper(),
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleConfirm()
|
||||
})
|
||||
|
||||
expect(mockDeletePluginCredential).not.toHaveBeenCalled()
|
||||
expect(result.current.deleteCredentialId).toBeNull()
|
||||
})
|
||||
})
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
|
||||
import { AuthCategory, CredentialTypeEnum } from '../../types'
|
||||
import { usePluginAuth } from '../use-plugin-auth'
|
||||
|
||||
// Mock dependencies
|
||||
const mockCredentials = [
|
||||
{ id: '1', credential_type: CredentialTypeEnum.API_KEY, is_default: false },
|
||||
{ id: '2', credential_type: CredentialTypeEnum.OAUTH2, is_default: true },
|
||||
]
|
||||
|
||||
const mockCredentialInfo = vi.fn().mockReturnValue({
|
||||
credentials: mockCredentials,
|
||||
supported_credential_types: [CredentialTypeEnum.API_KEY, CredentialTypeEnum.OAUTH2],
|
||||
allow_custom_token: true,
|
||||
})
|
||||
|
||||
const mockInvalidate = vi.fn()
|
||||
|
||||
vi.mock('../use-credential', () => ({
|
||||
useGetPluginCredentialInfoHook: (_payload: unknown, enable?: boolean) => ({
|
||||
data: enable ? mockCredentialInfo() : undefined,
|
||||
isLoading: false,
|
||||
}),
|
||||
useInvalidPluginCredentialInfoHook: () => mockInvalidate,
|
||||
}))
|
||||
|
||||
const basePayload = {
|
||||
category: AuthCategory.tool,
|
||||
provider: 'test-provider',
|
||||
}
|
||||
|
||||
describe('usePluginAuth', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('should return authorized state when credentials exist', () => {
|
||||
const { result } = renderHook(() => usePluginAuth(basePayload, true))
|
||||
|
||||
expect(result.current.isAuthorized).toBe(true)
|
||||
expect(result.current.credentials).toEqual(mockCredentials)
|
||||
expect(result.current.canOAuth).toBe(true)
|
||||
expect(result.current.canApiKey).toBe(true)
|
||||
expect(result.current.notAllowCustomCredential).toBe(false)
|
||||
})
|
||||
|
||||
it('should return unauthorized when enable is false', () => {
|
||||
const { result } = renderHook(() => usePluginAuth(basePayload, false))
|
||||
|
||||
expect(result.current.isAuthorized).toBe(false)
|
||||
expect(result.current.credentials).toEqual([])
|
||||
})
|
||||
|
||||
it('should handle empty credentials', () => {
|
||||
mockCredentialInfo.mockReturnValueOnce({
|
||||
credentials: [],
|
||||
supported_credential_types: [],
|
||||
allow_custom_token: false,
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => usePluginAuth(basePayload, true))
|
||||
|
||||
expect(result.current.isAuthorized).toBe(false)
|
||||
expect(result.current.canOAuth).toBe(false)
|
||||
expect(result.current.canApiKey).toBe(false)
|
||||
expect(result.current.notAllowCustomCredential).toBe(true)
|
||||
})
|
||||
|
||||
it('should handle only API Key support', () => {
|
||||
mockCredentialInfo.mockReturnValueOnce({
|
||||
credentials: [{ id: '1' }],
|
||||
supported_credential_types: [CredentialTypeEnum.API_KEY],
|
||||
allow_custom_token: true,
|
||||
})
|
||||
|
||||
const { result } = renderHook(() => usePluginAuth(basePayload, true))
|
||||
|
||||
expect(result.current.canApiKey).toBe(true)
|
||||
expect(result.current.canOAuth).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { PluginPayload } from '../types'
|
||||
import { AuthCategory } from '../types'
|
||||
|
||||
export const getApi = ({ category = AuthCategory.tool, provider }: PluginPayload) => ({
|
||||
getCredentialInfo:
|
||||
category === AuthCategory.tool
|
||||
? `/workspaces/current/tool-provider/builtin/${provider}/credential/info`
|
||||
: '',
|
||||
})
|
||||
@@ -0,0 +1,89 @@
|
||||
import type { CredentialTypeEnum, PluginPayload } from '../types'
|
||||
import { useQueryClient } from '@tanstack/react-query'
|
||||
import { getToolListQueryKey } from '@/app/components/tools/utils/tool-list-query-key'
|
||||
import {
|
||||
useAddPluginCredential,
|
||||
useDeletePluginCredential,
|
||||
useDeletePluginOAuthCustomClient,
|
||||
useGetPluginCredentialInfo,
|
||||
useGetPluginCredentialSchema,
|
||||
useGetPluginOAuthClientSchema,
|
||||
useGetPluginOAuthUrl,
|
||||
useInvalidPluginCredentialInfo,
|
||||
useInvalidPluginOAuthClientSchema,
|
||||
useSetPluginDefaultCredential,
|
||||
useSetPluginOAuthCustomClient,
|
||||
useUpdatePluginCredential,
|
||||
} from '@/service/use-plugins-auth'
|
||||
import { getApi } from './get-api'
|
||||
|
||||
export const useGetPluginCredentialInfoHook = (
|
||||
pluginPayload: PluginPayload,
|
||||
enable?: boolean,
|
||||
includeCredentialIds?: string[],
|
||||
) => {
|
||||
const apiMap = getApi(pluginPayload)
|
||||
const ids = (includeCredentialIds ?? []).filter(Boolean)
|
||||
let url = enable ? apiMap.getCredentialInfo : ''
|
||||
if (url && ids.length > 0) {
|
||||
const qs = new URLSearchParams()
|
||||
for (const id of ids) qs.append('include_credential_ids', id)
|
||||
url = url + (url.includes('?') ? '&' : '?') + qs.toString()
|
||||
}
|
||||
return useGetPluginCredentialInfo(url)
|
||||
}
|
||||
|
||||
export const useDeletePluginCredentialHook = (pluginPayload: PluginPayload) => {
|
||||
return useDeletePluginCredential(pluginPayload)
|
||||
}
|
||||
|
||||
export const useInvalidPluginCredentialInfoHook = (pluginPayload: PluginPayload) => {
|
||||
const apiMap = getApi(pluginPayload)
|
||||
const invalidPluginCredentialInfo = useInvalidPluginCredentialInfo(apiMap.getCredentialInfo)
|
||||
const queryClient = useQueryClient()
|
||||
const toolListQueryKey = getToolListQueryKey(pluginPayload.providerType)
|
||||
|
||||
return () => {
|
||||
invalidPluginCredentialInfo()
|
||||
if (toolListQueryKey) queryClient.invalidateQueries({ queryKey: toolListQueryKey })
|
||||
}
|
||||
}
|
||||
|
||||
export const useSetPluginDefaultCredentialHook = (pluginPayload: PluginPayload) => {
|
||||
return useSetPluginDefaultCredential(pluginPayload)
|
||||
}
|
||||
|
||||
export const useGetPluginCredentialSchemaHook = (
|
||||
pluginPayload: PluginPayload,
|
||||
credentialType: CredentialTypeEnum,
|
||||
) => {
|
||||
return useGetPluginCredentialSchema(pluginPayload, credentialType)
|
||||
}
|
||||
|
||||
export const useAddPluginCredentialHook = (pluginPayload: PluginPayload) => {
|
||||
return useAddPluginCredential(pluginPayload)
|
||||
}
|
||||
|
||||
export const useUpdatePluginCredentialHook = (pluginPayload: PluginPayload) => {
|
||||
return useUpdatePluginCredential(pluginPayload)
|
||||
}
|
||||
|
||||
export const useGetPluginOAuthUrlHook = (pluginPayload: PluginPayload) => {
|
||||
return useGetPluginOAuthUrl(pluginPayload)
|
||||
}
|
||||
|
||||
export const useGetPluginOAuthClientSchemaHook = (pluginPayload: PluginPayload, enabled = true) => {
|
||||
return useGetPluginOAuthClientSchema(pluginPayload, enabled)
|
||||
}
|
||||
|
||||
export const useInvalidPluginOAuthClientSchemaHook = (pluginPayload: PluginPayload) => {
|
||||
return useInvalidPluginOAuthClientSchema(pluginPayload)
|
||||
}
|
||||
|
||||
export const useSetPluginOAuthCustomClientHook = (pluginPayload: PluginPayload) => {
|
||||
return useSetPluginOAuthCustomClient(pluginPayload)
|
||||
}
|
||||
|
||||
export const useDeletePluginOAuthCustomClientHook = (pluginPayload: PluginPayload) => {
|
||||
return useDeletePluginOAuthCustomClient(pluginPayload)
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
import type { PluginPayload } from '../types'
|
||||
import { useCallback, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { toast } from '@/app/notifications'
|
||||
import {
|
||||
useDeletePluginCredentialHook,
|
||||
useSetPluginDefaultCredentialHook,
|
||||
useUpdatePluginCredentialHook,
|
||||
} from '../hooks/use-credential'
|
||||
|
||||
export const usePluginAuthAction = (pluginPayload: PluginPayload, onUpdate?: () => void) => {
|
||||
const { t } = useTranslation(['common'])
|
||||
const pendingOperationCredentialId = useRef<string | null>(null)
|
||||
const [deleteCredentialId, setDeleteCredentialId] = useState<string | null>(null)
|
||||
const { mutateAsync: deletePluginCredential } = useDeletePluginCredentialHook(pluginPayload)
|
||||
const openConfirm = useCallback((credentialId?: string) => {
|
||||
if (credentialId) pendingOperationCredentialId.current = credentialId
|
||||
|
||||
setDeleteCredentialId(pendingOperationCredentialId.current)
|
||||
}, [])
|
||||
const closeConfirm = useCallback(() => {
|
||||
setDeleteCredentialId(null)
|
||||
pendingOperationCredentialId.current = null
|
||||
}, [])
|
||||
const [doingAction, setDoingAction] = useState(false)
|
||||
const doingActionRef = useRef(doingAction)
|
||||
const handleSetDoingAction = useCallback((doing: boolean) => {
|
||||
doingActionRef.current = doing
|
||||
setDoingAction(doing)
|
||||
}, [])
|
||||
const [editValues, setEditValues] = useState<Record<string, unknown> | null>(null)
|
||||
const handleConfirm = useCallback(async () => {
|
||||
if (doingActionRef.current) return
|
||||
if (!pendingOperationCredentialId.current) {
|
||||
setDeleteCredentialId(null)
|
||||
return
|
||||
}
|
||||
try {
|
||||
handleSetDoingAction(true)
|
||||
await deletePluginCredential({ credential_id: pendingOperationCredentialId.current })
|
||||
toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }))
|
||||
onUpdate?.()
|
||||
setDeleteCredentialId(null)
|
||||
pendingOperationCredentialId.current = null
|
||||
setEditValues(null)
|
||||
} finally {
|
||||
handleSetDoingAction(false)
|
||||
}
|
||||
}, [deletePluginCredential, onUpdate, t, handleSetDoingAction])
|
||||
const handleEdit = useCallback((id: string, values: Record<string, unknown>) => {
|
||||
pendingOperationCredentialId.current = id
|
||||
setEditValues(values)
|
||||
}, [])
|
||||
const handleRemove = useCallback(() => {
|
||||
setDeleteCredentialId(pendingOperationCredentialId.current)
|
||||
}, [])
|
||||
const { mutateAsync: setPluginDefaultCredential } =
|
||||
useSetPluginDefaultCredentialHook(pluginPayload)
|
||||
const handleSetDefault = useCallback(
|
||||
async (id: string) => {
|
||||
if (doingActionRef.current) return
|
||||
try {
|
||||
handleSetDoingAction(true)
|
||||
await setPluginDefaultCredential(id)
|
||||
toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }))
|
||||
onUpdate?.()
|
||||
} finally {
|
||||
handleSetDoingAction(false)
|
||||
}
|
||||
},
|
||||
[setPluginDefaultCredential, onUpdate, t, handleSetDoingAction],
|
||||
)
|
||||
const { mutateAsync: updatePluginCredential } = useUpdatePluginCredentialHook(pluginPayload)
|
||||
const handleRename = useCallback(
|
||||
async (payload: { credential_id: string; name: string }) => {
|
||||
if (doingActionRef.current) return
|
||||
try {
|
||||
handleSetDoingAction(true)
|
||||
await updatePluginCredential(payload)
|
||||
toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }))
|
||||
onUpdate?.()
|
||||
} finally {
|
||||
handleSetDoingAction(false)
|
||||
}
|
||||
},
|
||||
[updatePluginCredential, t, handleSetDoingAction, onUpdate],
|
||||
)
|
||||
|
||||
return {
|
||||
doingAction,
|
||||
handleSetDoingAction,
|
||||
openConfirm,
|
||||
closeConfirm,
|
||||
deleteCredentialId,
|
||||
setDeleteCredentialId,
|
||||
handleConfirm,
|
||||
editValues,
|
||||
setEditValues,
|
||||
handleEdit,
|
||||
handleRemove,
|
||||
handleSetDefault,
|
||||
handleRename,
|
||||
pendingOperationCredentialId,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { PluginPayload } from '../types'
|
||||
import { CredentialTypeEnum } from '../types'
|
||||
import {
|
||||
useGetPluginCredentialInfoHook,
|
||||
useInvalidPluginCredentialInfoHook,
|
||||
} from './use-credential'
|
||||
|
||||
export const usePluginAuth = (
|
||||
pluginPayload: PluginPayload,
|
||||
enable?: boolean,
|
||||
includeCredentialIds?: string[],
|
||||
) => {
|
||||
const { data, isLoading } = useGetPluginCredentialInfoHook(
|
||||
pluginPayload,
|
||||
enable,
|
||||
includeCredentialIds,
|
||||
)
|
||||
const isAuthorized = !!data?.credentials.length
|
||||
const canOAuth = data?.supported_credential_types.includes(CredentialTypeEnum.OAUTH2)
|
||||
const canApiKey = data?.supported_credential_types.includes(CredentialTypeEnum.API_KEY)
|
||||
const invalidPluginCredentialInfo = useInvalidPluginCredentialInfoHook(pluginPayload)
|
||||
|
||||
return {
|
||||
isAuthorized,
|
||||
canOAuth,
|
||||
canApiKey,
|
||||
isLoading,
|
||||
credentials: data?.credentials || [],
|
||||
notAllowCustomCredential: data?.allow_custom_token === false,
|
||||
invalidPluginCredentialInfo,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user