CreateBucketModal.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. // @ts-nocheck
  2. import { zodResolver } from '@hookform/resolvers/zod'
  3. import { useParams } from 'common'
  4. import { useState } from 'react'
  5. import { SubmitHandler, useForm } from 'react-hook-form'
  6. import { toast } from 'sonner'
  7. import {
  8. Button,
  9. Dialog,
  10. DialogContent,
  11. DialogFooter,
  12. DialogHeader,
  13. DialogSection,
  14. DialogSectionSeparator,
  15. DialogTitle,
  16. Form,
  17. FormControl,
  18. FormField,
  19. FormMessage,
  20. Input,
  21. Select,
  22. SelectContent,
  23. SelectItem,
  24. SelectTrigger,
  25. SelectValue,
  26. Switch,
  27. } from 'ui'
  28. import { Admonition } from 'ui-patterns/admonition'
  29. import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
  30. import z from 'zod'
  31. import { inverseValidBucketNameRegex, validBucketNameRegex } from './CreateBucketModal.utils'
  32. import { convertFromBytes, convertToBytes } from './StorageSettings/StorageSettings.utils'
  33. import { StorageSizeUnits } from '@/components/interfaces/Storage/StorageSettings/StorageSettings.constants'
  34. import { InlineLink } from '@/components/ui/InlineLink'
  35. import { useProjectStorageConfigQuery } from '@/data/config/project-storage-config-query'
  36. import { useBucketCreateMutation } from '@/data/storage/bucket-create-mutation'
  37. import { useSendEventMutation } from '@/data/telemetry/send-event-mutation'
  38. import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
  39. import { IS_PLATFORM } from '@/lib/constants'
  40. const FormSchema = z
  41. .object({
  42. name: z
  43. .string()
  44. .trim()
  45. .min(1, 'Please provide a name for your bucket')
  46. .max(100, 'Bucket name should be below 100 characters')
  47. .refine(
  48. (value) => !value.endsWith(' '),
  49. 'The name of the bucket cannot end with a whitespace'
  50. )
  51. .refine(
  52. (value) => value !== 'public',
  53. '"public" is a reserved name. Please choose another name'
  54. ),
  55. public: z.boolean().default(false),
  56. has_file_size_limit: z.boolean().default(false),
  57. formatted_size_limit: z.coerce
  58. .number()
  59. .min(0, 'File size upload limit has to be at least 0')
  60. .optional(),
  61. allowed_mime_types: z.string().trim().default(''),
  62. })
  63. .superRefine((data, ctx) => {
  64. if (!validBucketNameRegex.test(data.name)) {
  65. const [match] = data.name.match(inverseValidBucketNameRegex) ?? []
  66. ctx.addIssue({
  67. path: ['name'],
  68. code: z.ZodIssueCode.custom,
  69. message: !!match
  70. ? `Bucket name cannot contain the "${match}" character`
  71. : 'Bucket name contains an invalid special character',
  72. })
  73. }
  74. })
  75. const formId = 'create-storage-bucket-form'
  76. export type CreateBucketForm = z.infer<typeof FormSchema>
  77. interface CreateBucketModalProps {
  78. open: boolean
  79. onOpenChange: (value: boolean) => void
  80. }
  81. export const CreateBucketModal = ({ open, onOpenChange }: CreateBucketModalProps) => {
  82. const { ref } = useParams()
  83. const { data: org } = useSelectedOrganizationQuery()
  84. const [selectedUnit, setSelectedUnit] = useState<string>(StorageSizeUnits.MB)
  85. const [hasAllowedMimeTypes, setHasAllowedMimeTypes] = useState(false)
  86. const { data } = useProjectStorageConfigQuery({ projectRef: ref }, { enabled: IS_PLATFORM })
  87. const { value, unit } = convertFromBytes(data?.fileSizeLimit ?? 0)
  88. const formattedGlobalUploadLimit = `${value} ${unit}`
  89. const { mutate: sendEvent } = useSendEventMutation()
  90. const { mutateAsync: createBucket, isPending: isCreatingBucket } = useBucketCreateMutation({
  91. // [Joshen] Silencing the error here as it's being handled in onSubmit
  92. onError: () => {},
  93. })
  94. const form = useForm<CreateBucketForm>({
  95. resolver: zodResolver(FormSchema as any),
  96. defaultValues: {
  97. name: '',
  98. public: false,
  99. has_file_size_limit: false,
  100. formatted_size_limit: undefined,
  101. allowed_mime_types: '',
  102. },
  103. })
  104. const { formatted_size_limit: formattedSizeLimitError } = form.formState.errors
  105. const isPublicBucket = form.watch('public')
  106. const hasFileSizeLimit = form.watch('has_file_size_limit')
  107. const onSubmit: SubmitHandler<CreateBucketForm> = async (values) => {
  108. if (!ref) return console.error('Project ref is required')
  109. // [Joshen] Should shift this into superRefine in the form schema
  110. try {
  111. const fileSizeLimit =
  112. values.has_file_size_limit && values.formatted_size_limit !== undefined
  113. ? convertToBytes(values.formatted_size_limit, selectedUnit as StorageSizeUnits)
  114. : undefined
  115. const allowedMimeTypes =
  116. hasAllowedMimeTypes && values.allowed_mime_types.length > 0
  117. ? values.allowed_mime_types.split(',').map((x) => x.trim())
  118. : undefined
  119. if (!!fileSizeLimit && !!data?.fileSizeLimit && fileSizeLimit > data.fileSizeLimit) {
  120. return form.setError('formatted_size_limit', {
  121. type: 'manual',
  122. message: 'exceed_global_limit',
  123. })
  124. }
  125. await createBucket({
  126. projectRef: ref,
  127. id: values.name,
  128. type: 'STANDARD',
  129. isPublic: values.public,
  130. file_size_limit: fileSizeLimit,
  131. allowed_mime_types: allowedMimeTypes,
  132. })
  133. sendEvent({
  134. action: 'storage_bucket_created',
  135. properties: { bucketType: 'STANDARD' },
  136. groups: { project: ref ?? 'Unknown', organization: org?.slug ?? 'Unknown' },
  137. })
  138. toast.success(`Successfully created bucket ${values.name}`)
  139. form.reset()
  140. setSelectedUnit(StorageSizeUnits.MB)
  141. onOpenChange(false)
  142. } catch (error: any) {
  143. // Handle specific error cases for inline display
  144. const errorMessage = error.message?.toLowerCase() || ''
  145. if (
  146. errorMessage.includes('mime type') &&
  147. (errorMessage.includes('is not supported') || errorMessage.includes('not supported'))
  148. ) {
  149. // Set form error for the MIME types field
  150. form.setError('allowed_mime_types', {
  151. type: 'manual',
  152. message: 'Invalid MIME type format. Please check your input.',
  153. })
  154. } else {
  155. // For other errors, show a toast as fallback
  156. toast.error(`Failed to create bucket: ${error.message}`)
  157. }
  158. }
  159. }
  160. const handleClose = () => {
  161. form.reset()
  162. setSelectedUnit(StorageSizeUnits.MB)
  163. onOpenChange(false)
  164. }
  165. return (
  166. <Dialog
  167. open={open}
  168. onOpenChange={(open) => {
  169. if (!open) {
  170. handleClose()
  171. }
  172. }}
  173. >
  174. <DialogContent aria-describedby={undefined}>
  175. <DialogHeader>
  176. <DialogTitle>Create file bucket</DialogTitle>
  177. </DialogHeader>
  178. <DialogSectionSeparator />
  179. <Form {...form}>
  180. <form id={formId} onSubmit={form.handleSubmit(onSubmit)}>
  181. <DialogSection className="flex flex-col gap-y-2">
  182. <FormField
  183. key="name"
  184. name="name"
  185. control={form.control}
  186. render={({ field }) => (
  187. <FormItemLayout
  188. name="name"
  189. label="Bucket name"
  190. labelOptional="Cannot be changed after creation"
  191. >
  192. <FormControl>
  193. <Input
  194. id="name"
  195. data-1p-ignore
  196. data-lpignore="true"
  197. data-form-type="other"
  198. data-bwignore
  199. {...field}
  200. placeholder="Enter bucket name"
  201. />
  202. </FormControl>
  203. </FormItemLayout>
  204. )}
  205. />
  206. </DialogSection>
  207. <DialogSectionSeparator />
  208. <DialogSection className="space-y-3">
  209. <FormField
  210. key="public"
  211. name="public"
  212. control={form.control}
  213. render={({ field }) => (
  214. <FormItemLayout
  215. hideMessage
  216. name="public"
  217. label="Public bucket"
  218. description="Allow anyone to read objects without authorization"
  219. layout="flex"
  220. >
  221. <FormControl>
  222. <Switch
  223. id="public"
  224. size="large"
  225. checked={field.value}
  226. onCheckedChange={field.onChange}
  227. />
  228. </FormControl>
  229. </FormItemLayout>
  230. )}
  231. />
  232. {isPublicBucket && (
  233. <Admonition
  234. type="warning"
  235. title="Public buckets are not protected"
  236. description="Users can read objects in public buckets without any authorization. Row level security (RLS) policies are still required for other operations such as object uploads and deletes."
  237. />
  238. )}
  239. </DialogSection>
  240. <DialogSectionSeparator />
  241. <DialogSection className="space-y-2">
  242. <FormField
  243. key="has_file_size_limit"
  244. name="has_file_size_limit"
  245. control={form.control}
  246. render={({ field }) => (
  247. <FormItemLayout
  248. name="has_file_size_limit"
  249. label="Restrict file size"
  250. description="Prevent uploading of files larger than a specified limit"
  251. layout="flex"
  252. >
  253. <FormControl>
  254. <Switch
  255. id="has_file_size_limit"
  256. size="large"
  257. checked={field.value}
  258. onCheckedChange={field.onChange}
  259. />
  260. </FormControl>
  261. </FormItemLayout>
  262. )}
  263. />
  264. {hasFileSizeLimit && (
  265. <div>
  266. <FormField
  267. key="formatted_size_limit"
  268. name="formatted_size_limit"
  269. control={form.control}
  270. render={({ field }) => (
  271. <FormItemLayout
  272. hideMessage
  273. name="formatted_size_limit"
  274. label="File size limit"
  275. >
  276. <div className="grid grid-cols-12 gap-x-2">
  277. <div className="col-span-8">
  278. <FormControl>
  279. <Input
  280. id="formatted_size_limit"
  281. aria-label="File size limit"
  282. type="number"
  283. min={0}
  284. placeholder="0"
  285. {...field}
  286. />
  287. </FormControl>
  288. </div>
  289. <div className="col-span-4">
  290. <Select value={selectedUnit} onValueChange={setSelectedUnit}>
  291. <SelectTrigger aria-label="File size limit unit" size="small">
  292. <SelectValue>{selectedUnit}</SelectValue>
  293. </SelectTrigger>
  294. <SelectContent>
  295. {Object.values(StorageSizeUnits).map((unit: string) => (
  296. <SelectItem key={unit} value={unit} className="text-xs">
  297. {unit}
  298. </SelectItem>
  299. ))}
  300. </SelectContent>
  301. </Select>
  302. </div>
  303. </div>
  304. </FormItemLayout>
  305. )}
  306. />
  307. {formattedSizeLimitError?.message === 'exceed_global_limit' && (
  308. <FormMessage className="mt-2">
  309. Exceeds global limit of {formattedGlobalUploadLimit}. Increase limit in{' '}
  310. <InlineLink
  311. className="text-destructive decoration-destructive-500 hover:decoration-destructive"
  312. href={`/project/${ref}/storage/settings`}
  313. onClick={() => onOpenChange(false)}
  314. >
  315. Storage Settings
  316. </InlineLink>{' '}
  317. first.
  318. </FormMessage>
  319. )}
  320. {IS_PLATFORM && (
  321. <p className="text-sm text-foreground-lighter mt-2">
  322. This project has a{' '}
  323. <InlineLink
  324. className="text-foreground-light hover:text-foreground"
  325. href={`/project/${ref}/storage/settings`}
  326. onClick={() => onOpenChange(false)}
  327. >
  328. global file size limit
  329. </InlineLink>{' '}
  330. of {formattedGlobalUploadLimit}.
  331. </p>
  332. )}
  333. </div>
  334. )}
  335. </DialogSection>
  336. <DialogSectionSeparator />
  337. <DialogSection className="space-y-2">
  338. <FormItemLayout
  339. name="has_allowed_mime_types"
  340. label="Restrict MIME types"
  341. description="Allow only certain types of files to be uploaded"
  342. layout="flex"
  343. >
  344. <FormControl>
  345. <Switch
  346. id="has_allowed_mime_types"
  347. size="large"
  348. checked={hasAllowedMimeTypes}
  349. onCheckedChange={setHasAllowedMimeTypes}
  350. />
  351. </FormControl>
  352. </FormItemLayout>
  353. {hasAllowedMimeTypes && (
  354. <FormField
  355. key="allowed_mime_types"
  356. name="allowed_mime_types"
  357. control={form.control}
  358. render={({ field }) => (
  359. <FormItemLayout
  360. name="allowed_mime_types"
  361. label="Allowed MIME types"
  362. labelOptional="Comma separated values"
  363. description="Wildcards are allowed, e.g. image/*."
  364. >
  365. <FormControl>
  366. <Input
  367. id="allowed_mime_types"
  368. {...field}
  369. placeholder="e.g image/jpeg, image/png, audio/mpeg, video/mp4, etc"
  370. />
  371. </FormControl>
  372. </FormItemLayout>
  373. )}
  374. />
  375. )}
  376. </DialogSection>
  377. </form>
  378. </Form>
  379. <DialogFooter>
  380. <Button type="default" disabled={isCreatingBucket} onClick={() => onOpenChange(false)}>
  381. Cancel
  382. </Button>
  383. <Button
  384. form={formId}
  385. htmlType="submit"
  386. loading={isCreatingBucket}
  387. disabled={isCreatingBucket}
  388. >
  389. Create
  390. </Button>
  391. </DialogFooter>
  392. </DialogContent>
  393. </Dialog>
  394. )
  395. }