secret-key-modal.tsx 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. 'use client'
  2. import {
  3. useEffect,
  4. useState,
  5. } from 'react'
  6. import { useTranslation } from 'react-i18next'
  7. import { PlusIcon, XMarkIcon } from '@heroicons/react/20/solid'
  8. import useSWR, { useSWRConfig } from 'swr'
  9. import { useContext } from 'use-context-selector'
  10. import copy from 'copy-to-clipboard'
  11. import SecretKeyGenerateModal from './secret-key-generate'
  12. import s from './style.module.css'
  13. import Modal from '@/app/components/base/modal'
  14. import Button from '@/app/components/base/button'
  15. import {
  16. createApikey as createAppApikey,
  17. delApikey as delAppApikey,
  18. fetchApiKeysList as fetchAppApiKeysList,
  19. } from '@/service/apps'
  20. import {
  21. createApikey as createDatasetApikey,
  22. delApikey as delDatasetApikey,
  23. fetchApiKeysList as fetchDatasetApiKeysList,
  24. } from '@/service/datasets'
  25. import type { CreateApiKeyResponse } from '@/models/app'
  26. import Tooltip from '@/app/components/base/tooltip'
  27. import Loading from '@/app/components/base/loading'
  28. import Confirm from '@/app/components/base/confirm'
  29. import I18n from '@/context/i18n'
  30. import { LanguagesSupported } from '@/i18n/language'
  31. import { useAppContext } from '@/context/app-context'
  32. type ISecretKeyModalProps = {
  33. isShow: boolean
  34. appId?: string
  35. onClose: () => void
  36. }
  37. const SecretKeyModal = ({
  38. isShow = false,
  39. appId,
  40. onClose,
  41. }: ISecretKeyModalProps) => {
  42. const { t } = useTranslation()
  43. const { currentWorkspace, isCurrentWorkspaceManager } = useAppContext()
  44. const [showConfirmDelete, setShowConfirmDelete] = useState(false)
  45. const [isVisible, setVisible] = useState(false)
  46. const [newKey, setNewKey] = useState<CreateApiKeyResponse | undefined>(undefined)
  47. const { mutate } = useSWRConfig()
  48. const commonParams = appId
  49. ? { url: `/apps/${appId}/api-keys`, params: {} }
  50. : { url: '/datasets/api-keys', params: {} }
  51. const fetchApiKeysList = appId ? fetchAppApiKeysList : fetchDatasetApiKeysList
  52. const { data: apiKeysList } = useSWR(commonParams, fetchApiKeysList)
  53. const [delKeyID, setDelKeyId] = useState('')
  54. const { locale } = useContext(I18n)
  55. // const [isCopied, setIsCopied] = useState(false)
  56. const [copyValue, setCopyValue] = useState('')
  57. useEffect(() => {
  58. if (copyValue) {
  59. const timeout = setTimeout(() => {
  60. setCopyValue('')
  61. }, 1000)
  62. return () => {
  63. clearTimeout(timeout)
  64. }
  65. }
  66. }, [copyValue])
  67. const onDel = async () => {
  68. setShowConfirmDelete(false)
  69. if (!delKeyID)
  70. return
  71. const delApikey = appId ? delAppApikey : delDatasetApikey
  72. const params = appId
  73. ? { url: `/apps/${appId}/api-keys/${delKeyID}`, params: {} }
  74. : { url: `/datasets/api-keys/${delKeyID}`, params: {} }
  75. await delApikey(params)
  76. mutate(commonParams)
  77. }
  78. const onCreate = async () => {
  79. const params = appId
  80. ? { url: `/apps/${appId}/api-keys`, body: {} }
  81. : { url: '/datasets/api-keys', body: {} }
  82. const createApikey = appId ? createAppApikey : createDatasetApikey
  83. const res = await createApikey(params)
  84. setVisible(true)
  85. setNewKey(res)
  86. mutate(commonParams)
  87. }
  88. const generateToken = (token: string) => {
  89. return `${token.slice(0, 3)}...${token.slice(-20)}`
  90. }
  91. const formatDate = (timestamp: string) => {
  92. if (locale === LanguagesSupported[0])
  93. return new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'long', day: 'numeric' }).format((+timestamp) * 1000)
  94. else
  95. return new Intl.DateTimeFormat('fr-CA', { year: 'numeric', month: '2-digit', day: '2-digit' }).format((+timestamp) * 1000)
  96. }
  97. return (
  98. <Modal isShow={isShow} onClose={onClose} title={`${t('appApi.apiKeyModal.apiSecretKey')}`} className={`${s.customModal} px-8 flex flex-col`}>
  99. <XMarkIcon className={`w-6 h-6 absolute cursor-pointer text-gray-500 ${s.close}`} onClick={onClose} />
  100. <p className='mt-1 text-[13px] text-gray-500 font-normal leading-5 flex-shrink-0'>{t('appApi.apiKeyModal.apiSecretKeyTips')}</p>
  101. {!apiKeysList && <div className='mt-4'><Loading /></div>}
  102. {
  103. !!apiKeysList?.data?.length && (
  104. <div className='flex flex-col flex-grow mt-4 overflow-hidden'>
  105. <div className='flex items-center flex-shrink-0 text-xs font-semibold text-gray-500 border-b border-solid h-9'>
  106. <div className='flex-shrink-0 w-64 px-3'>{t('appApi.apiKeyModal.secretKey')}</div>
  107. <div className='flex-shrink-0 px-3 w-28'>{t('appApi.apiKeyModal.created')}</div>
  108. <div className='flex-shrink-0 px-3 w-28'>{t('appApi.apiKeyModal.lastUsed')}</div>
  109. <div className='flex-grow px-3'></div>
  110. </div>
  111. <div className='flex-grow overflow-auto'>
  112. {apiKeysList.data.map(api => (
  113. <div className='flex items-center text-sm font-normal text-gray-700 border-b border-solid h-9' key={api.id}>
  114. <div className='flex-shrink-0 w-64 px-3 font-mono truncate'>{generateToken(api.token)}</div>
  115. <div className='flex-shrink-0 px-3 truncate w-28'>{formatDate(api.created_at)}</div>
  116. {/* <div className='flex-shrink-0 px-3 truncate w-28'>{dayjs((+api.created_at) * 1000).format('MMM D, YYYY')}</div> */}
  117. {/* <div className='flex-shrink-0 px-3 truncate w-28'>{api.last_used_at ? dayjs((+api.last_used_at) * 1000).format('MMM D, YYYY') : 'Never'}</div> */}
  118. <div className='flex-shrink-0 px-3 truncate w-28'>{api.last_used_at ? formatDate(api.last_used_at) : t('appApi.never')}</div>
  119. <div className='flex flex-grow px-3'>
  120. <Tooltip
  121. selector={`key-${api.token}`}
  122. content={copyValue === api.token ? `${t('appApi.copied')}` : `${t('appApi.copy')}`}
  123. className='z-10'
  124. >
  125. <div className={`flex items-center justify-center flex-shrink-0 w-6 h-6 mr-1 rounded-lg cursor-pointer hover:bg-gray-100 ${s.copyIcon} ${copyValue === api.token ? s.copied : ''}`} onClick={() => {
  126. // setIsCopied(true)
  127. copy(api.token)
  128. setCopyValue(api.token)
  129. }}></div>
  130. </Tooltip>
  131. { isCurrentWorkspaceManager
  132. && <div className={`flex items-center justify-center flex-shrink-0 w-6 h-6 rounded-lg cursor-pointer ${s.trashIcon}`} onClick={() => {
  133. setDelKeyId(api.id)
  134. setShowConfirmDelete(true)
  135. }}>
  136. </div>
  137. }
  138. </div>
  139. </div>
  140. ))}
  141. </div>
  142. </div>
  143. )
  144. }
  145. <div className='flex'>
  146. <Button type='default' className={`flex flex-shrink-0 mt-4 ${s.autoWidth}`} onClick={onCreate} disabled={ !currentWorkspace || currentWorkspace.role === 'normal'}>
  147. <PlusIcon className='flex flex-shrink-0 w-4 h-4' />
  148. <div className='text-xs font-medium text-gray-800'>{t('appApi.apiKeyModal.createNewSecretKey')}</div>
  149. </Button>
  150. </div>
  151. <SecretKeyGenerateModal className='flex-shrink-0' isShow={isVisible} onClose={() => setVisible(false)} newKey={newKey} />
  152. {showConfirmDelete && (
  153. <Confirm
  154. title={`${t('appApi.actionMsg.deleteConfirmTitle')}`}
  155. content={`${t('appApi.actionMsg.deleteConfirmTips')}`}
  156. isShow={showConfirmDelete}
  157. onClose={() => {
  158. setDelKeyId('')
  159. setShowConfirmDelete(false)
  160. }}
  161. onConfirm={onDel}
  162. onCancel={() => {
  163. setDelKeyId('')
  164. setShowConfirmDelete(false)
  165. }}
  166. />
  167. )}
  168. </Modal >
  169. )
  170. }
  171. export default SecretKeyModal