|
| 1 | +'use client' |
| 2 | + |
| 3 | +import { type ComponentType, useState } from 'react' |
| 4 | +import { |
| 5 | + ChipModal, |
| 6 | + ChipModalBody, |
| 7 | + ChipModalError, |
| 8 | + ChipModalField, |
| 9 | + ChipModalFooter, |
| 10 | + ChipModalHeader, |
| 11 | + SecretInput, |
| 12 | +} from '@sim/emcn' |
| 13 | +import { getErrorMessage } from '@sim/utils/errors' |
| 14 | +import { isApiClientError } from '@/lib/api/client/errors' |
| 15 | +import { |
| 16 | + resourceScopeFields, |
| 17 | + resourceScopeFromOwner, |
| 18 | + resourceScopeKey, |
| 19 | +} from '@/lib/core/resource-scope' |
| 20 | +import type { DatabaseConnectionDescriptor } from '@/lib/credentials/database-connections/descriptors' |
| 21 | +import type { ServiceAccountSecretFields } from '@/lib/credentials/service-account-secret' |
| 22 | +import { withBrandIcon } from '@/blocks/brand-icon' |
| 23 | +import { |
| 24 | + useCreateScopedCredential, |
| 25 | + useUpdateScopedCredential, |
| 26 | +} from '@/hooks/queries/scoped-credentials' |
| 27 | + |
| 28 | +interface DatabaseConnectionAccountModalProps { |
| 29 | + open: boolean |
| 30 | + onOpenChange: (open: boolean) => void |
| 31 | + workspaceId?: string |
| 32 | + organizationId?: string |
| 33 | + descriptor: DatabaseConnectionDescriptor |
| 34 | + serviceIcon: ComponentType<{ className?: string }> |
| 35 | + credentialId?: string |
| 36 | + initialDisplayName?: string |
| 37 | + initialDescription?: string |
| 38 | + onCreated?: (credentialId: string) => void |
| 39 | + onSubmitCredentials?: ( |
| 40 | + fields: ServiceAccountSecretFields & { displayName?: string; description?: string } |
| 41 | + ) => Promise<string> |
| 42 | + submitPending?: boolean |
| 43 | +} |
| 44 | + |
| 45 | +interface LoginFields { |
| 46 | + host: string |
| 47 | + port: string |
| 48 | + database: string |
| 49 | + username: string |
| 50 | + password: string |
| 51 | +} |
| 52 | + |
| 53 | +/** |
| 54 | + * Saved PostgreSQL, MySQL, and SQL Server connections share the standard |
| 55 | + * credential create/reconnect lifecycle; the server proves each with |
| 56 | + * `SELECT 1` before storing it. |
| 57 | + */ |
| 58 | +export function DatabaseConnectionAccountModal(props: DatabaseConnectionAccountModalProps) { |
| 59 | + if (!props.open) return null |
| 60 | + return ( |
| 61 | + <DatabaseConnectionAccountForm |
| 62 | + key={`${props.descriptor.providerId}:${resourceScopeKey(resourceScopeFromOwner(props))}:${props.credentialId ?? 'new'}`} |
| 63 | + {...props} |
| 64 | + /> |
| 65 | + ) |
| 66 | +} |
| 67 | + |
| 68 | +function DatabaseConnectionAccountForm({ |
| 69 | + open, |
| 70 | + onOpenChange, |
| 71 | + workspaceId, |
| 72 | + organizationId, |
| 73 | + descriptor, |
| 74 | + serviceIcon: ServiceIcon, |
| 75 | + credentialId, |
| 76 | + initialDisplayName, |
| 77 | + initialDescription, |
| 78 | + onCreated, |
| 79 | + onSubmitCredentials, |
| 80 | + submitPending, |
| 81 | +}: DatabaseConnectionAccountModalProps) { |
| 82 | + const [login, setLogin] = useState<LoginFields>({ |
| 83 | + host: '', |
| 84 | + port: String(descriptor.defaultPort), |
| 85 | + database: '', |
| 86 | + username: '', |
| 87 | + password: '', |
| 88 | + }) |
| 89 | + const [tls, setTls] = useState<Record<string, string>>(() => |
| 90 | + Object.fromEntries(descriptor.tls.map((field) => [field.id, field.defaultValue])) |
| 91 | + ) |
| 92 | + const [displayName, setDisplayName] = useState(initialDisplayName ?? '') |
| 93 | + const [description, setDescription] = useState(initialDescription ?? '') |
| 94 | + const [error, setError] = useState<string | null>(null) |
| 95 | + const createCredential = useCreateScopedCredential() |
| 96 | + const updateCredential = useUpdateScopedCredential() |
| 97 | + const isPending = |
| 98 | + createCredential.isPending || updateCredential.isPending || submitPending === true |
| 99 | + const action = credentialId ? 'Reconnect' : 'Add' |
| 100 | + const title = `${action} ${descriptor.label} connection` |
| 101 | + const disabled = |
| 102 | + isPending || |
| 103 | + !login.host.trim() || |
| 104 | + !login.port.trim() || |
| 105 | + !login.database.trim() || |
| 106 | + !login.username.trim() || |
| 107 | + !login.password |
| 108 | + const setLoginField = (field: keyof LoginFields, value: string) => { |
| 109 | + setLogin((current) => ({ ...current, [field]: value })) |
| 110 | + setError(null) |
| 111 | + } |
| 112 | + const submit = async () => { |
| 113 | + if (disabled) return |
| 114 | + setError(null) |
| 115 | + const serviceAccountJson = JSON.stringify({ |
| 116 | + host: login.host.trim(), |
| 117 | + port: Number(login.port), |
| 118 | + database: login.database.trim(), |
| 119 | + username: login.username.trim(), |
| 120 | + password: login.password, |
| 121 | + ...tls, |
| 122 | + }) |
| 123 | + try { |
| 124 | + let connectedId = credentialId |
| 125 | + if (onSubmitCredentials) { |
| 126 | + connectedId = await onSubmitCredentials({ |
| 127 | + serviceAccountJson, |
| 128 | + displayName: displayName.trim() || undefined, |
| 129 | + description: description.trim() || undefined, |
| 130 | + }) |
| 131 | + } else if (credentialId) { |
| 132 | + await updateCredential.mutateAsync({ |
| 133 | + ...resourceScopeFields(resourceScopeFromOwner({ workspaceId, organizationId })), |
| 134 | + credentialId, |
| 135 | + serviceAccountJson, |
| 136 | + displayName: displayName.trim() || undefined, |
| 137 | + description: description.trim() || null, |
| 138 | + }) |
| 139 | + } else { |
| 140 | + const created = await createCredential.mutateAsync({ |
| 141 | + ...resourceScopeFields(resourceScopeFromOwner({ workspaceId, organizationId })), |
| 142 | + type: 'service_account', |
| 143 | + providerId: descriptor.providerId, |
| 144 | + serviceAccountJson, |
| 145 | + displayName: displayName.trim() || undefined, |
| 146 | + description: description.trim() || undefined, |
| 147 | + }) |
| 148 | + connectedId = created.credential.id |
| 149 | + } |
| 150 | + if (connectedId) onCreated?.(connectedId) |
| 151 | + onOpenChange(false) |
| 152 | + } catch (submitError) { |
| 153 | + setError( |
| 154 | + isApiClientError(submitError) && submitError.code === 'duplicate_display_name' |
| 155 | + ? 'A credential with that name already exists. Choose a different display name.' |
| 156 | + : onSubmitCredentials |
| 157 | + ? getErrorMessage(submitError, `Could not verify the ${descriptor.label} connection.`) |
| 158 | + : `Could not verify the ${descriptor.label} connection. Check the connection details, network access, and database permissions.` |
| 159 | + ) |
| 160 | + } |
| 161 | + } |
| 162 | + return ( |
| 163 | + <ChipModal open={open} onOpenChange={onOpenChange} srTitle={title}> |
| 164 | + <ChipModalHeader icon={withBrandIcon(ServiceIcon)} onClose={() => onOpenChange(false)}> |
| 165 | + {title} |
| 166 | + </ChipModalHeader> |
| 167 | + <ChipModalBody> |
| 168 | + <ChipModalField |
| 169 | + type='input' |
| 170 | + title='Host' |
| 171 | + value={login.host} |
| 172 | + onChange={(value) => setLoginField('host', value)} |
| 173 | + placeholder='db.example.com' |
| 174 | + required |
| 175 | + autoComplete='off' |
| 176 | + /> |
| 177 | + <ChipModalField |
| 178 | + type='input' |
| 179 | + title='Port' |
| 180 | + value={login.port} |
| 181 | + onChange={(value) => setLoginField('port', value)} |
| 182 | + placeholder={String(descriptor.defaultPort)} |
| 183 | + required |
| 184 | + autoComplete='off' |
| 185 | + /> |
| 186 | + <ChipModalField |
| 187 | + type='input' |
| 188 | + title='Database' |
| 189 | + value={login.database} |
| 190 | + onChange={(value) => setLoginField('database', value)} |
| 191 | + placeholder='your_database' |
| 192 | + required |
| 193 | + autoComplete='off' |
| 194 | + /> |
| 195 | + <ChipModalField |
| 196 | + type='input' |
| 197 | + title='Username' |
| 198 | + value={login.username} |
| 199 | + onChange={(value) => setLoginField('username', value)} |
| 200 | + placeholder={descriptor.usernamePlaceholder} |
| 201 | + required |
| 202 | + autoComplete='off' |
| 203 | + /> |
| 204 | + <ChipModalField type='custom' title='Password' required> |
| 205 | + {(aria) => ( |
| 206 | + <SecretInput |
| 207 | + {...aria} |
| 208 | + value={login.password} |
| 209 | + onChange={(value) => setLoginField('password', value)} |
| 210 | + placeholder='Enter the database password' |
| 211 | + autoComplete='new-password' |
| 212 | + data-lpignore='true' |
| 213 | + /> |
| 214 | + )} |
| 215 | + </ChipModalField> |
| 216 | + {descriptor.tls.map((field) => ( |
| 217 | + <ChipModalField |
| 218 | + key={field.id} |
| 219 | + type='dropdown' |
| 220 | + title={field.label} |
| 221 | + value={tls[field.id] ?? field.defaultValue} |
| 222 | + onChange={(value) => { |
| 223 | + setTls((current) => ({ ...current, [field.id]: value })) |
| 224 | + setError(null) |
| 225 | + }} |
| 226 | + options={[...field.options]} |
| 227 | + placeholder={`Choose ${field.label.toLowerCase()}`} |
| 228 | + required |
| 229 | + hint={field.hint} |
| 230 | + /> |
| 231 | + ))} |
| 232 | + <ChipModalField |
| 233 | + type='input' |
| 234 | + title='Display name' |
| 235 | + value={displayName} |
| 236 | + onChange={setDisplayName} |
| 237 | + placeholder='Defaults to user@host/database' |
| 238 | + /> |
| 239 | + <ChipModalField |
| 240 | + type='textarea' |
| 241 | + title='Description' |
| 242 | + value={description} |
| 243 | + onChange={setDescription} |
| 244 | + placeholder='Optional description' |
| 245 | + maxLength={500} |
| 246 | + minHeight={80} |
| 247 | + /> |
| 248 | + <ChipModalError>{error}</ChipModalError> |
| 249 | + </ChipModalBody> |
| 250 | + <ChipModalFooter |
| 251 | + onCancel={() => onOpenChange(false)} |
| 252 | + secondaryActions={[ |
| 253 | + { |
| 254 | + label: 'Setup guide', |
| 255 | + onClick: () => window.open(descriptor.docsUrl, '_blank', 'noopener,noreferrer'), |
| 256 | + }, |
| 257 | + ]} |
| 258 | + primaryAction={{ |
| 259 | + label: isPending ? 'Verifying...' : `${action} connection`, |
| 260 | + onClick: submit, |
| 261 | + disabled, |
| 262 | + }} |
| 263 | + /> |
| 264 | + </ChipModal> |
| 265 | + ) |
| 266 | +} |
0 commit comments