feat: add permission data logic

This commit is contained in:
Joel 2024-10-15 19:20:59 +08:00
parent aa9028a607
commit 57f4dfdb6f
7 changed files with 171 additions and 79 deletions

View File

@ -1,33 +1,43 @@
'use client' 'use client'
import type { FC } from 'react' import type { FC } from 'react'
import React, { useState } from 'react' import React, { useCallback, useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import Modal from '@/app/components/base/modal' import Modal from '@/app/components/base/modal'
import OptionCard from '@/app/components/workflow/nodes/_base/components/option-card' import OptionCard from '@/app/components/workflow/nodes/_base/components/option-card'
import Button from '@/app/components/base/button' import Button from '@/app/components/base/button'
import type { Permissions } from '@/app/components/plugins/types'
enum PluginManagementOption { import { PermissionType } from '@/app/components/plugins/types'
Everyone = 'Everyone',
Admins = 'Admins',
NoOne = 'No one',
}
type Props = { type Props = {
show: boolean payload: Permissions
onHide: () => void onHide: () => void
onSave: (payload: Permissions) => void
} }
const PluginSettingModal: FC<Props> = ({ const PluginSettingModal: FC<Props> = ({
show, payload,
onHide, onHide,
onSave,
}) => { }) => {
const { t } = useTranslation() const { t } = useTranslation()
const [manageOption, setManageOption] = useState<PluginManagementOption>(PluginManagementOption.Everyone) const [tempPrivilege, setTempPrivilege] = useState<Permissions>(payload)
const [debugOption, setDebugOption] = useState<PluginManagementOption>(PluginManagementOption.Everyone) const handlePrivilegeChange = useCallback((key: string) => {
return (value: PermissionType) => {
setTempPrivilege({
...tempPrivilege,
[key]: value,
})
}
}, [tempPrivilege])
const handleSave = useCallback(() => {
onSave(tempPrivilege)
onHide()
}, [tempPrivilege])
return ( return (
<Modal <Modal
isShow={show} isShow
onClose={onHide} onClose={onHide}
closable closable
className='!p-0 w-[420px]' className='!p-0 w-[420px]'
@ -38,19 +48,19 @@ const PluginSettingModal: FC<Props> = ({
</div> </div>
<div className='flex px-6 py-3 flex-col justify-center items-start gap-4 self-stretch'> <div className='flex px-6 py-3 flex-col justify-center items-start gap-4 self-stretch'>
{[ {[
{ title: 'Who can install and manage plugins?', key: 'manage', value: manageOption, setValue: setManageOption }, { title: 'Who can install and manage plugins?', key: 'canInstall', value: tempPrivilege.canInstall },
{ title: 'Who can debug plugins?', key: 'debug', value: debugOption, setValue: setDebugOption }, { title: 'Who can debug plugins?', key: 'canDebugger', value: tempPrivilege.canDebugger },
].map(({ title, key, value, setValue }) => ( ].map(({ title, key, value }) => (
<div key={key} className='flex flex-col items-start gap-1 self-stretch'> <div key={key} className='flex flex-col items-start gap-1 self-stretch'>
<div className='flex m-h-6 items-center gap-0.5'> <div className='flex m-h-6 items-center gap-0.5'>
<span className='text-text-secondary system-sm-semibold'>{title}</span> <span className='text-text-secondary system-sm-semibold'>{title}</span>
</div> </div>
<div className='flex items-start gap-2 justify-between w-full'> <div className='flex items-start gap-2 justify-between w-full'>
{Object.values(PluginManagementOption).map(option => ( {[PermissionType.everyone, PermissionType.admin, PermissionType.noOne].map(option => (
<OptionCard <OptionCard
key={option} key={option}
title={option} title={option}
onSelect={() => setValue(option)} onSelect={() => handlePrivilegeChange(key)(option)}
selected={value === option} selected={value === option}
className="flex-1" className="flex-1"
/> />
@ -69,6 +79,7 @@ const PluginSettingModal: FC<Props> = ({
<Button <Button
className='min-w-[72px]' className='min-w-[72px]'
variant={'primary'} variant={'primary'}
onClick={handleSave}
> >
Save Save
</Button> </Button>

View File

@ -3,18 +3,29 @@
import type { ReactNode } from 'react' import type { ReactNode } from 'react'
import { import {
useRef, useRef,
useState,
} from 'react' } from 'react'
import { import {
createContext, createContext,
useContextSelector, useContextSelector,
} from 'use-context-selector' } from 'use-context-selector'
import type { Permissions } from '../types'
import { PermissionType } from '../types'
export type PluginPageContextValue = { export type PluginPageContextValue = {
containerRef: React.RefObject<HTMLDivElement> containerRef: React.RefObject<HTMLDivElement>
permissions: Permissions
setPermissions: (permissions: PluginPageContextValue['permissions']) => void
} }
export const PluginPageContext = createContext<PluginPageContextValue>({ export const PluginPageContext = createContext<PluginPageContextValue>({
containerRef: { current: null }, containerRef: { current: null },
permissions: {
canInstall: PermissionType.noOne,
canDebugger: PermissionType.noOne,
},
setPermissions: () => { },
}) })
type PluginPageContextProviderProps = { type PluginPageContextProviderProps = {
@ -29,11 +40,17 @@ export const PluginPageContextProvider = ({
children, children,
}: PluginPageContextProviderProps) => { }: PluginPageContextProviderProps) => {
const containerRef = useRef<HTMLDivElement>(null) const containerRef = useRef<HTMLDivElement>(null)
const [permissions, setPermissions] = useState<PluginPageContextValue['permissions']>({
canInstall: PermissionType.noOne,
canDebugger: PermissionType.noOne,
})
return ( return (
<PluginPageContext.Provider <PluginPageContext.Provider
value={{ value={{
containerRef, containerRef,
permissions,
setPermissions,
}} }}
> >
{children} {children}

View File

@ -9,6 +9,7 @@ import {
RiDragDropLine, RiDragDropLine,
RiEqualizer2Line, RiEqualizer2Line,
} from '@remixicon/react' } from '@remixicon/react'
import { useBoolean } from 'ahooks'
import InstallFromLocalPackage from '../install-plugin/install-from-local-package' import InstallFromLocalPackage from '../install-plugin/install-from-local-package'
import { import {
PluginPageContextProvider, PluginPageContextProvider,
@ -16,13 +17,14 @@ import {
} from './context' } from './context'
import InstallPluginDropdown from './install-plugin-dropdown' import InstallPluginDropdown from './install-plugin-dropdown'
import { useUploader } from './use-uploader' import { useUploader } from './use-uploader'
import usePermission from './use-permission'
import { useTabSearchParams } from '@/hooks/use-tab-searchparams' import { useTabSearchParams } from '@/hooks/use-tab-searchparams'
import { useModalContext } from '@/context/modal-context'
import Button from '@/app/components/base/button' import Button from '@/app/components/base/button'
import TabSlider from '@/app/components/base/tab-slider' import TabSlider from '@/app/components/base/tab-slider'
import ActionButton from '@/app/components/base/action-button' import ActionButton from '@/app/components/base/action-button'
import Tooltip from '@/app/components/base/tooltip' import Tooltip from '@/app/components/base/tooltip'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import PermissionSetModal from '@/app/components/plugins/permission-setting-modal/modal'
export type PluginPageProps = { export type PluginPageProps = {
plugins: React.ReactNode plugins: React.ReactNode
@ -33,7 +35,17 @@ const PluginPage = ({
marketplace, marketplace,
}: PluginPageProps) => { }: PluginPageProps) => {
const { t } = useTranslation() const { t } = useTranslation()
const { setShowPluginSettingModal } = useModalContext() as any const {
canInstall,
canDebugger,
canSetPermissions,
permissions,
setPermissions,
} = usePermission()
const [showPluginSettingModal, {
setTrue: setShowPluginSettingModal,
setFalse: setHidePluginSettingModal,
}] = useBoolean()
const [currentFile, setCurrentFile] = useState<File | null>(null) const [currentFile, setCurrentFile] = useState<File | null>(null)
const containerRef = usePluginPageContext(v => v.containerRef) const containerRef = usePluginPageContext(v => v.containerRef)
const options = useMemo(() => { const options = useMemo(() => {
@ -76,7 +88,11 @@ const PluginPage = ({
/> />
</div> </div>
<div className='flex flex-shrink-0 items-center gap-1'> <div className='flex flex-shrink-0 items-center gap-1'>
{canInstall && (
<InstallPluginDropdown /> <InstallPluginDropdown />
)}
{
canDebugger && (
<Tooltip <Tooltip
triggerMethod='click' triggerMethod='click'
popupContent={ popupContent={
@ -114,14 +130,18 @@ const PluginPage = ({
<RiBugLine className='w-4 h-4' /> <RiBugLine className='w-4 h-4' />
</Button> </Button>
</Tooltip> </Tooltip>
)
}
{
canSetPermissions && (
<Button <Button
className='w-full h-full p-2 text-components-button-secondary-text group' className='w-full h-full p-2 text-components-button-secondary-text group'
onClick={() => { onClick={setShowPluginSettingModal}
setShowPluginSettingModal()
}}
> >
<RiEqualizer2Line className='w-4 h-4' /> <RiEqualizer2Line className='w-4 h-4' />
</Button> </Button>
)
}
</div> </div>
</div> </div>
</div> </div>
@ -139,7 +159,7 @@ const PluginPage = ({
<span className="system-xs-regular">Drop plugin package here to install</span> <span className="system-xs-regular">Drop plugin package here to install</span>
</div> </div>
{currentFile && ( {currentFile && (
<InstallFromLocalPackage file={currentFile} onClose={removeFile ?? (() => {})} /> <InstallFromLocalPackage file={currentFile} onClose={removeFile ?? (() => { })} />
)} )}
<input <input
ref={fileUploader} ref={fileUploader}
@ -147,13 +167,21 @@ const PluginPage = ({
type="file" type="file"
id="fileUploader" id="fileUploader"
accept='.difypkg' accept='.difypkg'
onChange={fileChangeHandle ?? (() => {})} onChange={fileChangeHandle ?? (() => { })}
/> />
</> </>
)} )}
{ {
activeTab === 'discover' && marketplace activeTab === 'discover' && marketplace
} }
{showPluginSettingModal && (
<PermissionSetModal
payload={permissions}
onHide={setHidePluginSettingModal}
onSave={setPermissions}
/>
)}
</div> </div>
) )
} }

View File

@ -0,0 +1,39 @@
import { useEffect } from 'react'
import { PermissionType } from '../types'
import {
usePluginPageContext,
} from './context'
import { useAppContext } from '@/context/app-context'
const hasPermission = (permission: PermissionType, isAdmin: boolean) => {
if (permission === PermissionType.noOne)
return false
if (permission === PermissionType.everyone)
return true
return isAdmin
}
const usePermission = () => {
const { isCurrentWorkspaceManager, isCurrentWorkspaceOwner } = useAppContext()
const [permissions, setPermissions] = usePluginPageContext(v => [v.permissions, v.setPermissions])
const isAdmin = isCurrentWorkspaceManager || isCurrentWorkspaceOwner
useEffect(() => {
// TODO: fetch permissions from server
setPermissions({
canInstall: PermissionType.everyone,
canDebugger: PermissionType.everyone,
})
}, [])
return {
canInstall: hasPermission(permissions.canInstall, isAdmin),
canDebugger: hasPermission(permissions.canDebugger, isAdmin),
canSetPermissions: isAdmin,
permissions,
setPermissions,
}
}
export default usePermission

View File

@ -25,3 +25,14 @@ export type Plugin = {
settings: CredentialFormSchemaBase[] settings: CredentialFormSchemaBase[]
} }
} }
export enum PermissionType {
everyone = 'everyone',
admin = 'admin',
noOne = 'noOne',
}
export type Permissions = {
canInstall: PermissionType
canDebugger: PermissionType
}

View File

@ -5,7 +5,6 @@ import { useCallback, useState } from 'react'
import { createContext, useContext, useContextSelector } from 'use-context-selector' import { createContext, useContext, useContextSelector } from 'use-context-selector'
import { useRouter, useSearchParams } from 'next/navigation' import { useRouter, useSearchParams } from 'next/navigation'
import AccountSetting from '@/app/components/header/account-setting' import AccountSetting from '@/app/components/header/account-setting'
import PluginSettingModal from '@/app/components/plugins/plugin-setting/modal'
import ApiBasedExtensionModal from '@/app/components/header/account-setting/api-based-extension-page/modal' import ApiBasedExtensionModal from '@/app/components/header/account-setting/api-based-extension-page/modal'
import ModerationSettingModal from '@/app/components/app/configuration/toolbox/moderation/moderation-setting-modal' import ModerationSettingModal from '@/app/components/app/configuration/toolbox/moderation/moderation-setting-modal'
import ExternalDataToolModal from '@/app/components/app/configuration/tools/external-data-tool-modal' import ExternalDataToolModal from '@/app/components/app/configuration/tools/external-data-tool-modal'
@ -52,7 +51,6 @@ export type LoadBalancingEntryModalType = ModelModalType & {
} }
export type ModalContextState = { export type ModalContextState = {
setShowAccountSettingModal: Dispatch<SetStateAction<ModalState<string> | null>> setShowAccountSettingModal: Dispatch<SetStateAction<ModalState<string> | null>>
setShowPluginSettingModal: () => void
setShowApiBasedExtensionModal: Dispatch<SetStateAction<ModalState<ApiBasedExtension> | null>> setShowApiBasedExtensionModal: Dispatch<SetStateAction<ModalState<ApiBasedExtension> | null>>
setShowModerationSettingModal: Dispatch<SetStateAction<ModalState<ModerationConfig> | null>> setShowModerationSettingModal: Dispatch<SetStateAction<ModalState<ModerationConfig> | null>>
setShowExternalDataToolModal: Dispatch<SetStateAction<ModalState<ExternalDataTool> | null>> setShowExternalDataToolModal: Dispatch<SetStateAction<ModalState<ExternalDataTool> | null>>
@ -65,7 +63,6 @@ export type ModalContextState = {
} }
const ModalContext = createContext<ModalContextState>({ const ModalContext = createContext<ModalContextState>({
setShowAccountSettingModal: () => { }, setShowAccountSettingModal: () => { },
setShowPluginSettingModal: () => { },
setShowApiBasedExtensionModal: () => { }, setShowApiBasedExtensionModal: () => { },
setShowModerationSettingModal: () => { }, setShowModerationSettingModal: () => { },
setShowExternalDataToolModal: () => { }, setShowExternalDataToolModal: () => { },
@ -103,7 +100,6 @@ export const ModalContextProvider = ({
const router = useRouter() const router = useRouter()
const [showPricingModal, setShowPricingModal] = useState(searchParams.get('show-pricing') === '1') const [showPricingModal, setShowPricingModal] = useState(searchParams.get('show-pricing') === '1')
const [showAnnotationFullModal, setShowAnnotationFullModal] = useState(false) const [showAnnotationFullModal, setShowAnnotationFullModal] = useState(false)
const [showPluginSettingModal, setShowPluginSettingModal] = useState(false)
const handleCancelAccountSettingModal = () => { const handleCancelAccountSettingModal = () => {
setShowAccountSettingModal(null) setShowAccountSettingModal(null)
if (showAccountSettingModal?.onCancelCallback) if (showAccountSettingModal?.onCancelCallback)
@ -197,7 +193,6 @@ export const ModalContextProvider = ({
return ( return (
<ModalContext.Provider value={{ <ModalContext.Provider value={{
setShowAccountSettingModal, setShowAccountSettingModal,
setShowPluginSettingModal: () => setShowPluginSettingModal(true),
setShowApiBasedExtensionModal, setShowApiBasedExtensionModal,
setShowModerationSettingModal, setShowModerationSettingModal,
setShowExternalDataToolModal, setShowExternalDataToolModal,
@ -219,15 +214,6 @@ export const ModalContextProvider = ({
) )
} }
{
!!showPluginSettingModal && (
<PluginSettingModal
show={showPluginSettingModal}
onHide={() => setShowPluginSettingModal(false)}
/>
)
}
{ {
!!showApiBasedExtensionModal && ( !!showApiBasedExtensionModal && (
<ApiBasedExtensionModal <ApiBasedExtensionModal