The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Reinstate feat: allow removing multiple redirect urls (#29405) (#29417)
Joshen Limf5ac01ec2e74
diff --git a/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.tsx b/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.tsxnew file mode 100644index 00000000000..53449175aa6--- /dev/null+++ b/apps/studio/components/interfaces/Auth/RedirectUrls/AddNewURLModal.tsx@@ -0,0 +1,162 @@+import { zodResolver } from '@hookform/resolvers/zod'+import { Plus, Trash } from 'lucide-react'+import { useEffect } from 'react'+import { useFieldArray, useForm } from 'react-hook-form'+import { toast } from 'sonner'+import * as z from 'zod'++import { useParams } from 'common'+import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'+import {+ Button,+ cn,+ DialogSectionSeparator,+ Form_Shadcn_,+ FormControl_Shadcn_,+ FormField_Shadcn_,+ Modal,+ ScrollArea,+} from 'ui'+import { Input } from 'ui-patterns/DataInputs/Input'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import { Label } from '@ui/components/shadcn/ui/label'++const MAX_URLS_LENGTH = 2 * 1024++interface AddNewURLModalProps {+ visible: boolean+ allowList: string[]+ onClose: () => void+}++export const AddNewURLModal = ({ visible, allowList, onClose }: AddNewURLModalProps) => {+ const { ref } = useParams()+ const { mutate: updateAuthConfig, isLoading: isUpdatingConfig } = useAuthConfigUpdateMutation()++ const FormSchema = z.object({+ urls: z+ .object({+ value: z+ .string()+ .min(1, 'Please provide a value')+ .url('Please provide a valid URL')+ .refine((value) => !allowList.includes(value), {+ message: 'URL already exists in the allow list',+ }),+ })+ .array()+ .default([]),+ })++ const initialValues = { urls: [{ value: '' }] }+ const form = useForm<z.infer<typeof FormSchema>>({+ resolver: zodResolver(FormSchema),+ defaultValues: initialValues,+ })++ const { fields, append, remove } = useFieldArray({+ name: 'urls',+ control: form.control,+ })++ const onSubmit = (data: z.infer<typeof FormSchema>) => {+ const payload = allowList+ .concat(data.urls.map((url) => url.value.replace(/,\s*$/, '')))+ .toString()++ if (payload.length > MAX_URLS_LENGTH) {+ return toast.error('Too many redirect URLs, please remove some or try to use wildcards')+ } else {+ updateAuthConfig(+ { projectRef: ref!, config: { URI_ALLOW_LIST: payload } },+ {+ onError: (error) => {+ toast.error(`Failed to add URL(s): ${error?.message}`)+ },+ onSuccess: () => {+ toast.success(`Successfully added ${fields.length} URL${fields.length > 1 ? 's' : ''}`)+ form.reset(initialValues)+ onClose()+ },+ }+ )+ }+ }++ useEffect(() => {+ if (visible) form.reset(initialValues)+ }, [visible])++ return (+ <Modal+ hideFooter+ size="medium"+ className="!max-w-[440px]"+ visible={visible}+ onCancel={() => {+ form.reset(initialValues)+ onClose()+ }}+ header="Add new redirect URLs"+ description="This will add a URL to a list of allowed URLs that can interact with your Authentication services for this project."+ >+ <Form_Shadcn_ {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)}>+ <Modal.Content className="flex flex-col gap-y-2 px-0">+ <Label className="px-5">URL</Label>+ <ScrollArea className={cn(fields.length > 4 ? 'h-[220px]' : '')}>+ <div className="px-5 py-1 flex flex-col gap-y-2">+ {fields.map((field, index) => (+ <FormField_Shadcn_+ control={form.control}+ key={field.id}+ name={`urls.${index}.value`}+ render={({ field: inputField }) => (+ <FormItemLayout className="[&>div>div]:mt-0">+ <FormControl_Shadcn_>+ <div className="flex items-center gap-x-2 [&>div]:w-full">+ <Input placeholder="https://mydomain.com" {...inputField} />+ <Button+ type="default"+ size="small"+ icon={<Trash />}+ className="px-2"+ disabled={fields.length === 1}+ onClick={() => remove(index)}+ />+ </div>+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />+ ))}+ </div>+ </ScrollArea>+ <div className="px-5">+ <Button+ type="default"+ className="w-min"+ icon={<Plus strokeWidth={1.5} />}+ onClick={() => append({ value: '' })}+ >+ Add URL+ </Button>+ </div>+ </Modal.Content>+ <DialogSectionSeparator />+ <Modal.Content>+ <Button+ block+ htmlType="submit"+ size="small"+ disabled={isUpdatingConfig}+ loading={isUpdatingConfig}+ >+ Save URLs+ </Button>+ </Modal.Content>+ </form>+ </Form_Shadcn_>+ </Modal>+ )+}diff --git a/apps/studio/components/interfaces/Auth/RedirectUrls/RedirectUrlList.tsx b/apps/studio/components/interfaces/Auth/RedirectUrls/RedirectUrlList.tsxindex 938b838df17..e34d9195ff6 100644--- a/apps/studio/components/interfaces/Auth/RedirectUrls/RedirectUrlList.tsx+++ b/apps/studio/components/interfaces/Auth/RedirectUrls/RedirectUrlList.tsx@@ -1,41 +1,119 @@-import { noop } from 'lodash'-import { Button } from 'ui'+import { PermissionAction } from '@supabase/shared-types/out/constants'+import { Globe, Trash } from 'lucide-react'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'import { EmptyListState } from 'components/ui/States'-import ValueContainer from './ValueContainer'-import { Globe, Trash } from 'lucide-react'+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'+import { Button, Checkbox_Shadcn_ } from 'ui'+import { ValueContainer } from './ValueContainer'interface RedirectUrlListProps {- URI_ALLOW_LIST_ARRAY: string[]- canUpdate: boolean- onSelectUrlToDelete: (url: string) => void+ allowList: string[]+ selectedUrls: string[]+ onSelectUrl: (urls: string[]) => void+ onSelectAddURL: () => void+ onSelectRemoveURLs: () => void+ onSelectClearSelection: () => void}-const RedirectUrlList = ({- URI_ALLOW_LIST_ARRAY,- canUpdate,- onSelectUrlToDelete = noop,+export const RedirectUrlList = ({+ allowList,+ selectedUrls,+ onSelectUrl,+ onSelectAddURL,+ onSelectRemoveURLs,+ onSelectClearSelection,}: RedirectUrlListProps) => {+ const canUpdateConfig = useCheckPermissions(PermissionAction.UPDATE, 'custom_config_gotrue')++ // [Joshen] One for next time: maybe shift this into a reusable logic since it+ // seems like we can use this in multiple places for future+ const onClickUrl = (event: any, url: string) => {+ if (event.shiftKey) {+ const urlIdx = allowList.indexOf(url)+ const idxLatest = allowList.indexOf(selectedUrls[selectedUrls.length - 1])++ const newSelectedUrls =+ urlIdx > idxLatest+ ? allowList.slice(idxLatest + 1, urlIdx + 1)+ : allowList.slice(urlIdx, idxLatest)++ const urlsNotSelectedYet = newSelectedUrls.filter((x) => !selectedUrls.includes(x))++ if (urlsNotSelectedYet.length > 0) {+ onSelectUrl([+ ...selectedUrls,+ ...(urlIdx > idxLatest ? newSelectedUrls : newSelectedUrls.reverse()),+ ])+ } else {+ const urlsToRemove = newSelectedUrls.concat([selectedUrls[selectedUrls.length - 1]])+ onSelectUrl(selectedUrls.filter((x) => !urlsToRemove.includes(x)))+ }+ } else {+ const isSelected = selectedUrls.includes(url)+ const newSelectedUrls = isSelected+ ? selectedUrls.filter((selectedUrl) => selectedUrl !== url)+ : [...selectedUrls, url]+ onSelectUrl(newSelectedUrls)+ }+ }+return (<div className="-space-y-px">- {URI_ALLOW_LIST_ARRAY.length > 0 ? (- URI_ALLOW_LIST_ARRAY.map((url) => {- return (- <ValueContainer key={url}>- <div className="flex items-center gap-4 font-mono">- <span className="text-foreground-lighter">- <Globe strokeWidth={2} size={14} />- </span>- <span className="text-sm">{url}</span>- </div>- {canUpdate && (- <Button type="default" icon={<Trash />} onClick={() => onSelectUrlToDelete(url)}>- Remove- </Button>- )}- </ValueContainer>- )- })+ <ValueContainer className="py-3 flex items-center justify-between">+ <p className="text-foreground-light text-sm">Total URLs: {allowList.length}</p>+ {selectedUrls.length > 0 ? (+ <div className="flex items-center gap-x-2">+ <Button type="default" onClick={() => onSelectClearSelection()}>+ Clear selection+ </Button>+ <ButtonTooltip+ type="default"+ disabled={!canUpdateConfig}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to remove redirect URLs',+ },+ }}+ icon={<Trash />}+ onClick={() => (selectedUrls.length > 0 ? onSelectRemoveURLs() : null)}+ >+ Remove ({selectedUrls.length})+ </ButtonTooltip>+ </div>+ ) : (+ <ButtonTooltip+ disabled={!canUpdateConfig}+ onClick={() => onSelectAddURL()}+ tooltip={{+ content: {+ side: 'bottom',+ text: 'You need additional permissions to update redirect URLs',+ },+ }}+ >+ Add URL+ </ButtonTooltip>+ )}+ </ValueContainer>+ {allowList.length > 0 ? (+ <>+ {allowList.map((url) => {+ const isSelected = selectedUrls.includes(url)+ return (+ <ValueContainer key={url} isSelected={isSelected} onClick={(e) => onClickUrl(e, url)}>+ <div className={`flex items-center gap-4 font-mono group w-full`}>+ <div className="w-5 h-5 flex items-center justify-center">+ <Checkbox_Shadcn_ checked={isSelected} onChange={(e) => onClickUrl(e, url)} />+ </div>+ <Globe strokeWidth={2} size={14} className="text-foreground-lighter" />+ <span className="text-sm flex-grow">{url}</span>+ </div>+ </ValueContainer>+ )+ })}+ </>) : (<divclassName={[@@ -52,5 +130,3 @@ const RedirectUrlList = ({</div>)}--export default RedirectUrlListdiff --git a/apps/studio/components/interfaces/Auth/RedirectUrls/RedirectUrls.tsx b/apps/studio/components/interfaces/Auth/RedirectUrls/RedirectUrls.tsxindex de9f7208475..fb5d458f8d2 100644--- a/apps/studio/components/interfaces/Auth/RedirectUrls/RedirectUrls.tsx+++ b/apps/studio/components/interfaces/Auth/RedirectUrls/RedirectUrls.tsx@@ -1,33 +1,28 @@-import { PermissionAction } from '@supabase/shared-types/out/constants'-import { useParams } from 'common'import { ExternalLink } from 'lucide-react'import Link from 'next/link'import { useMemo, useState } from 'react'import { toast } from 'sonner'-import { object, string } from 'yup'-import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import { useParams } from 'common'import { FormHeader } from 'components/ui/Forms/FormHeader'import { HorizontalShimmerWithIcon } from 'components/ui/Shimmers/Shimmers'import { useAuthConfigQuery } from 'data/auth/auth-config-query'import { useAuthConfigUpdateMutation } from 'data/auth/auth-config-update-mutation'-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'import {AlertDescription_Shadcn_,AlertTitle_Shadcn_,Alert_Shadcn_,Button,- DialogSectionSeparator,- Form,- Input,Modal,WarningIcon,} from 'ui'-import { urlRegex } from '../Auth.constants'-import RedirectUrlList from './RedirectUrlList'-import ValueContainer from './ValueContainer'+import { AddNewURLModal } from './AddNewURLModal'+import { RedirectUrlList } from './RedirectUrlList'+import { ValueContainer } from './ValueContainer'++const MAX_URLS_LENGTH = 2 * 1024-const RedirectUrls = () => {+export const RedirectUrls = () => {const { ref: projectRef } = useParams()const {data: authConfig,@@ -45,58 +40,28 @@ const RedirectUrls = () => {}, [authConfig?.URI_ALLOW_LIST])const [open, setOpen] = useState(false)- const [selectedUrlToDelete, setSelectedUrlToDelete] = useState<string>()+ const [openRemoveSelected, setOpenRemoveSelected] = useState(false)+ const [selectedUrls, setSelectedUrls] = useState<string[]>([])- const canUpdateConfig = useCheckPermissions(PermissionAction.UPDATE, 'custom_config_gotrue')+ const onConfirmDeleteUrl = async (urls?: string[]) => {+ if (!urls || urls.length === 0) return- const newUrlSchema = object({- url: string().matches(urlRegex, 'URL is not valid').required(),- })-- const onAddNewUrl = async (values: any) => {- if (!values.url) {- return- }-- const payload = URI_ALLOW_LIST_ARRAY- // remove any trailing commas- payload.push(values.url.replace(/,\s*$/, ''))-- const payloadString = payload.toString()-- if (payloadString.length > 2 * 1024) {+ // Remove selectedUrl from array and update+ const payload = URI_ALLOW_LIST_ARRAY.filter((url: string) => !selectedUrls.includes(url))+ const payloadString = payload.join(',')+ if (payloadString.length > MAX_URLS_LENGTH) {return toast.error('Too many redirect URLs, please remove some or try to use wildcards')}-updateAuthConfig({ projectRef: projectRef!, config: { URI_ALLOW_LIST: payloadString } },{onError: (error) => {- toast.error(`Failed to update URL: ${error?.message}`)+ toast.error(`Failed to remove URL(s): ${error?.message}`)},onSuccess: () => {- setOpen(false)- toast.success('Successfully added URL')- },- }- )- }-- const onConfirmDeleteUrl = async (url?: string) => {- if (!url) return-- // Remove selectedUrl from array and update- const payload = URI_ALLOW_LIST_ARRAY.filter((e: string) => e !== url)-- updateAuthConfig(- { projectRef: projectRef!, config: { URI_ALLOW_LIST: payload.toString() } },- {- onError: (error) => {- toast.error(`Failed to remove URL: ${error?.message}`)- },- onSuccess: () => {- setSelectedUrlToDelete(undefined)- toast.success('Successfully removed URL')+ setSelectedUrls([])+ setOpenRemoveSelected(false)+ toast.success('Successfully removed URL(s)')},})@@ -119,18 +84,6 @@ const RedirectUrls = () => {Documentation</Link></Button>- <ButtonTooltip- disabled={!canUpdateConfig}- onClick={() => setOpen(true)}- tooltip={{- content: {- side: 'bottom',- text: 'You need additional permissions to update redirect URLs',- },- }}- >- Add URL- </ButtonTooltip></div></div>{isLoading && (@@ -152,64 +105,44 @@ const RedirectUrls = () => {)}{isSuccess && (<RedirectUrlList- URI_ALLOW_LIST_ARRAY={URI_ALLOW_LIST_ARRAY}- canUpdate={canUpdateConfig}- onSelectUrlToDelete={setSelectedUrlToDelete}+ allowList={URI_ALLOW_LIST_ARRAY}+ selectedUrls={selectedUrls}+ onSelectUrl={setSelectedUrls}+ onSelectAddURL={() => setOpen(true)}+ onSelectClearSelection={() => setSelectedUrls([])}+ onSelectRemoveURLs={() => setOpenRemoveSelected(true)}/>)}- <Modal- hideFooter- size="small"++ <AddNewURLModalvisible={open}- onCancel={() => setOpen(!open)}- header="Add a new URL"- description="This will add a URL to a list of allowed URLs that can interact with your Authentication services for this project."- >- <Form- validateOnBlur- id="new-redirect-url-form"- initialValues={{ url: '' }}- validationSchema={newUrlSchema}- onSubmit={onAddNewUrl}- >- {() => {- return (- <>- <Modal.Content>- <Input id="url" name="url" label="URL" placeholder="https://mydomain.com" />- </Modal.Content>- <DialogSectionSeparator />- <Modal.Content>- <Button- block- form="new-redirect-url-form"- htmlType="submit"- size="small"- disabled={isUpdatingConfig}- loading={isUpdatingConfig}- >- Add URL- </Button>- </Modal.Content>- </>- )- }}- </Form>- </Modal>+ allowList={URI_ALLOW_LIST_ARRAY}+ onClose={() => setOpen(false)}+ />+<ModalhideFooter- size="small"- visible={selectedUrlToDelete !== undefined}- header="Remove URL"- onCancel={() => setSelectedUrlToDelete(undefined)}+ size="large"+ visible={openRemoveSelected}+ header="Remove URLs"+ onCancel={() => {+ setSelectedUrls([])+ setOpenRemoveSelected(false)+ }}><Modal.Content><p className="mb-2 text-sm text-foreground-light">- Are you sure you want to remove{' '}- <span className="text-foreground">{selectedUrlToDelete}</span>?+ Are you sure you want to remove the following URLs?</p>+ <ul className="list-disc pl-4 mb-2">+ {selectedUrls.map((url, index) => (+ <li key={index} className="text-foreground-light text-sm">+ {url}+ </li>+ ))}+ </ul><p className="text-foreground-light text-sm">- This URL will no longer work with your authentication configuration.+ These URLs will no longer work with your authentication configuration.</p></Modal.Content><Modal.Separator />@@ -218,7 +151,10 @@ const RedirectUrls = () => {blocktype="default"size="medium"- onClick={() => setSelectedUrlToDelete(undefined)}+ onClick={() => {+ setSelectedUrls([])+ setOpenRemoveSelected(false)+ }}>Cancel</Button>@@ -227,7 +163,7 @@ const RedirectUrls = () => {size="medium"type="warning"loading={isUpdatingConfig}- onClick={() => onConfirmDeleteUrl(selectedUrlToDelete)}+ onClick={() => onConfirmDeleteUrl(selectedUrls)}>{isUpdatingConfig ? 'Removing...' : 'Remove URL'}</Button>@@ -236,5 +172,3 @@ const RedirectUrls = () => {</div>)}--export default RedirectUrlsdiff --git a/apps/studio/components/interfaces/Auth/RedirectUrls/ValueContainer.tsx b/apps/studio/components/interfaces/Auth/RedirectUrls/ValueContainer.tsxindex ec36304761c..6addd4f97ec 100644--- a/apps/studio/components/interfaces/Auth/RedirectUrls/ValueContainer.tsx+++ b/apps/studio/components/interfaces/Auth/RedirectUrls/ValueContainer.tsx@@ -1,17 +1,32 @@-import { PropsWithChildren } from 'react'+import { PropsWithChildren, MouseEvent } from 'react'-const ValueContainer = ({ children }: PropsWithChildren<{}>) => (+import { cn } from 'ui'++interface ValueContainerProps {+ isSelected?: boolean+ className?: string+ onClick?: (event: MouseEvent<HTMLElement>) => void+}++export const ValueContainer = ({+ children,+ isSelected = false,+ className,+ onClick,+}: PropsWithChildren<ValueContainerProps>) => (<div- className="- bg-surface-100 border-default text-foreground flex items-center- justify-between gap-2- border px-6- py-4 text-sm- first:rounded-tr first:rounded-tl last:rounded-br last:rounded-bl- "+ className={cn(+ 'bg-surface-100 hover:bg-surface-200 border-default text-foreground flex items-center',+ 'transition justify-between gap-2 border px-6 py-4 text-sm',+ 'first:rounded-tr first:rounded-tl last:rounded-br last:rounded-bl',+ isSelected ? '!bg-surface-300' : '',+ onClick ? 'cursor-pointer' : '',+ className+ )}+ onClick={(e) => {+ if (onClick) onClick(e)+ }}>{children}</div>)--export default ValueContainerdiff --git a/apps/studio/components/ui/ResourceExhaustionWarningBanner/ResourceExhaustionWarningBanner.tsx b/apps/studio/components/ui/ResourceExhaustionWarningBanner/ResourceExhaustionWarningBanner.tsxindex 7c8a71982cb..912f31856ba 100644--- a/apps/studio/components/ui/ResourceExhaustionWarningBanner/ResourceExhaustionWarningBanner.tsx+++ b/apps/studio/components/ui/ResourceExhaustionWarningBanner/ResourceExhaustionWarningBanner.tsx@@ -68,8 +68,6 @@ const ResourceExhaustionWarningBanner = () => {: RESOURCE_WARNING_MESSAGES[activeWarnings[0] as keyof typeof RESOURCE_WARNING_MESSAGES]?.metric- console.log({ metric })-const correctionUrl = (metric === undefined? undefineddiff --git a/apps/studio/pages/project/[ref]/auth/url-configuration.tsx b/apps/studio/pages/project/[ref]/auth/url-configuration.tsxindex 0d59eb7935c..36aae336e66 100644--- a/apps/studio/pages/project/[ref]/auth/url-configuration.tsx+++ b/apps/studio/pages/project/[ref]/auth/url-configuration.tsx@@ -1,6 +1,6 @@import { PermissionAction } from '@supabase/shared-types/out/constants'-import RedirectUrls from 'components/interfaces/Auth/RedirectUrls/RedirectUrls'+import { RedirectUrls } from 'components/interfaces/Auth/RedirectUrls/RedirectUrls'import SiteUrl from 'components/interfaces/Auth/SiteUrl/SiteUrl'import AuthLayout from 'components/layouts/AuthLayout/AuthLayout'import { FormsContainer } from 'components/ui/Forms/FormsContainer'