Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat(studio): ui for oauth app create edit form (#51023)

kemal.earth64a6aa908594
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel/Authorization.test.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel/Authorization.test.tsx
new file mode 100644
index 00000000000..c7caf4b59f9
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel/Authorization.test.tsx
@@ -0,0 +1,135 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import { fireEvent, screen, waitFor } from '@testing-library/react'
+import { SubmitHandler, useForm } from 'react-hook-form'
+import { Form } from 'ui'
+import { describe, expect, test, vi } from 'vitest'
+import z from 'zod'
+
+import { OneTimeWithConfirmToggle } from './Authorization'
+import { customRender } from '@/tests/lib/custom-render'
+
+describe('OneTimeWithConfirmToggle', () => {
+ const schema = z
+ .object({
+ thing_to_enable: z.coerce.boolean(),
+ thing_to_enable_confirmed: z.coerce.boolean().optional(),
+ })
+ .superRefine((values, context) => {
+ if (values.thing_to_enable && !values.thing_to_enable_confirmed) {
+ context.addIssue({
+ code: 'custom',
+ path: ['thing_to_enable_confirmed'],
+ message: 'Please confirm you want to enable the thing',
+ })
+ }
+ })
+ type Schema = z.infer<typeof schema>
+
+ const TestForm = ({
+ defaultValues,
+ onSubmit,
+ }: {
+ defaultValues: Schema
+ onSubmit: SubmitHandler<Schema>
+ }) => {
+ const form = useForm<Schema>({
+ defaultValues,
+ resolver: zodResolver(schema),
+ })
+
+ return (
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)}>
+ <OneTimeWithConfirmToggle
+ control={form.control}
+ name="thing_to_enable"
+ confirmedName="thing_to_enable_confirmed"
+ label="Thing to enable"
+ description=""
+ warningBody="Careful"
+ />
+ <button tabIndex={0} type="submit">
+ Save
+ </button>
+ </form>
+ </Form>
+ )
+ }
+
+ test('It requires the confirmation field to be checked when enabled from initially disabled', async () => {
+ const onSubmit = vi.fn()
+ customRender(
+ <TestForm
+ defaultValues={{
+ thing_to_enable: false,
+ thing_to_enable_confirmed: false,
+ }}
+ onSubmit={onSubmit}
+ />
+ )
+
+ // Confirmation is hidden initially
+ expect(
+ screen.queryByLabelText(
+ 'I understand this is permanent. I can test it on a duplicate app first'
+ )
+ ).toBeNull()
+ fireEvent.click(await screen.findByLabelText('Thing to enable'))
+ // Confirmation is now visible
+ const confirmCheckbox = await screen.findByLabelText(
+ 'I understand this is permanent. I can test it on a duplicate app first'
+ )
+ fireEvent.click(await screen.findByText('Save'))
+ await screen.findByText('Please confirm you want to enable the thing')
+ expect(onSubmit).not.toHaveBeenCalled()
+ fireEvent.click(confirmCheckbox)
+ fireEvent.click(await screen.findByText('Save'))
+ await waitFor(() => expect(onSubmit).toHaveBeenCalled())
+ })
+
+ test('It does not requires the confirmation field to be checked when the field is not enabled', async () => {
+ const onSubmit = vi.fn()
+ customRender(
+ <TestForm
+ defaultValues={{
+ thing_to_enable: false,
+ thing_to_enable_confirmed: false,
+ }}
+ onSubmit={onSubmit}
+ />
+ )
+
+ // Confirmation is hidden initially
+ expect(
+ screen.queryByLabelText(
+ 'I understand this is permanent. I can test it on a duplicate app first'
+ )
+ ).toBeNull()
+ fireEvent.click(await screen.findByText('Save'))
+ await waitFor(() => expect(onSubmit).toHaveBeenCalled())
+ })
+
+ test('It does not allow to modify the field nor requires the confirmation field to be checked when the field is initially enabled', async () => {
+ const onSubmit = vi.fn()
+ customRender(
+ <TestForm
+ defaultValues={{
+ thing_to_enable: true,
+ thing_to_enable_confirmed: true,
+ }}
+ onSubmit={onSubmit}
+ />
+ )
+
+ // Confirmation is hidden initially
+ expect(
+ screen.queryByLabelText(
+ 'I understand this is permanent. I can test it on a duplicate app first'
+ )
+ ).toBeNull()
+ expect(screen.queryByLabelText('Thing to enable')).toBeDisabled()
+
+ fireEvent.click(await screen.findByText('Save'))
+ await waitFor(() => expect(onSubmit).toHaveBeenCalled())
+ })
+})
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel/Authorization.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel/Authorization.tsx
new file mode 100644
index 00000000000..d459a4f7155
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel/Authorization.tsx
@@ -0,0 +1,166 @@
+import { useId } from 'react'
+import { Control, FieldPath, FieldValues, useFormContext, useWatch } from 'react-hook-form'
+import { Checkbox, FormControl, FormField, Switch } from 'ui'
+import { Admonition } from 'ui-patterns/Admonition'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+
+import {
+ getAuthorizationPreviewExplanation,
+ getResultingGrantDescription,
+} from './Authorization.utils'
+import { FormSchemaWithOAuthAppScopedGrants } from './PublishAppSidePanel.utils'
+
+interface OneTimeWithConfirmToggleProps<TFieldValues extends FieldValues> {
+ control: Control<TFieldValues>
+ name: FieldPath<TFieldValues>
+ confirmedName: FieldPath<TFieldValues>
+ label: string
+ description: string
+ warningBody: string
+}
+
+export const OneTimeWithConfirmToggle = <TFieldValues extends FieldValues>({
+ control,
+ name,
+ confirmedName,
+ label,
+ description,
+ warningBody,
+}: OneTimeWithConfirmToggleProps<TFieldValues>) => {
+ const checkboxId = useId()
+ const { getFieldState } = useFormContext()
+ const isNewlyEnabled = useWatch({
+ control,
+ name,
+ compute: (value) => {
+ const fieldState = getFieldState(name)
+ return fieldState.isDirty && !!value
+ },
+ })
+
+ return (
+ <div className="space-y-3">
+ <FormItemLayout
+ layout="flex-row-reverse"
+ className="justify-between"
+ label={label}
+ description={description}
+ >
+ <FormField
+ control={control}
+ name={name}
+ render={({ field, fieldState }) => (
+ <FormControl>
+ <Switch
+ ref={field.ref}
+ // TS can't know this field value is a boolean
+ checked={!!field.value}
+ disabled={!!field.value && !fieldState.isDirty}
+ aria-label={label}
+ onCheckedChange={(checked) => {
+ field.onChange(checked)
+ }}
+ />
+ </FormControl>
+ )}
+ />
+ </FormItemLayout>
+ {isNewlyEnabled && (
+ <Admonition
+ type="warning"
+ layout="vertical"
+ title="This can't be turned off after you save"
+ >
+ <p>{warningBody}</p>
+ <FormField
+ control={control}
+ name={confirmedName}
+ render={({ field, fieldState }) => (
+ <>
+ <label htmlFor={checkboxId} className="flex items-start gap-2 pt-2 cursor-pointer">
+ <Checkbox
+ ref={field.ref}
+ id={checkboxId}
+ // TS can't know this field value is a boolean
+ checked={!!field.value}
+ onCheckedChange={(checked) => field.onChange(checked)}
+ className="mt-0.5"
+ aria-describedby={fieldState.invalid ? `${confirmedName}_error` : undefined}
+ />
+ <span className="text-sm text-foreground">
+ I understand this is permanent. I can test it on a duplicate app first
+ </span>
+ </label>
+ {fieldState.invalid ? (
+ <p className="text-destructive" id={`${confirmedName}_error`}>
+ {fieldState.error?.message}
+ </p>
+ ) : null}
+ </>
+ )}
+ />
+ </Admonition>
+ )}
+ </div>
+ )
+}
+
+export interface AuthorizationSectionProps {
+ control: Control<FormSchemaWithOAuthAppScopedGrants>
+}
+
+export const AuthorizationSection = ({ control }: AuthorizationSectionProps) => {
+ const { explanation, resultingGrant } = useWatch({
+ control,
+ name: ['member_bound_grant', 'project_scoping'],
+ compute: ([memberBoundGrant, projectScoping]) => ({
+ explanation: getAuthorizationPreviewExplanation(memberBoundGrant, projectScoping),
+ resultingGrant: getResultingGrantDescription(memberBoundGrant, projectScoping),
+ }),
+ })
+
+ return (
+ <div className="p-6 space-y-6">
+ <div className="flex flex-col">
+ <span className="text-sm text-foreground">Authorization</span>
+ <span className="text-sm text-foreground-light">
+ How your app is granted access when someone connects it
+ </span>
+ </div>
+
+ <OneTimeWithConfirmToggle
+ control={control}
+ label="Use the permissions of the person who connects"
+ description="Each member who connects gets their own grant, limited to what they can already do. When off, an owner approves one organization-wide grant."
+ warningBody="Existing connections keep working. Only new connections will use per-member grants."
+ name="member_bound_grant"
+ confirmedName="member_bound_grant_confirmed"
+ />
+
+ <OneTimeWithConfirmToggle
+ control={control}
+ label="Ask for specific projects"
+ description="Users pick which projects your app can reach. Requests to other projects return 403. When off, your app reaches every project in the organization."
+ warningBody="Make sure your app reads the returned scopes and handles denied requests before you turn this on."
+ name="project_scoping"
+ confirmedName="project_scoping_confirmed"
+ />
+
+ <Admonition
+ type="note"
+ layout="vertical"
+ title="What your app users will see when they connect"
+ >
+ <p>
+ An organization owner approves your app once. It can then reach every project in their
+ organization.
+ </p>
+ {explanation && <p>{explanation}</p>}
+ <p>
+ <span className="text-foreground-lighter">Resulting grant: </span>
+ <span className="text-foreground-light">{resultingGrant}</span>
+ </p>
+ </Admonition>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel/Authorization.utils.test.ts b/apps/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel/Authorization.utils.test.ts
new file mode 100644
index 00000000000..551fdba7c75
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel/Authorization.utils.test.ts
@@ -0,0 +1,83 @@
+import { describe, expect, test } from 'vitest'
+
+import {
+ AuthorizationToggleState,
+ getAuthorizationPreviewExplanation,
+ getResultingGrantDescription,
+ isAuthorizationConfirmationPending,
+} from './Authorization.utils'
+
+describe('getAuthorizationPreviewExplanation', () => {
+ test('returns null when both toggles are off', () => {
+ expect(getAuthorizationPreviewExplanation(false, false)).toBeNull()
+ })
+
+ test('describes per-member grants when only that toggle is on', () => {
+ expect(getAuthorizationPreviewExplanation(true, false)).toContain('each member approves')
+ })
+
+ test('describes project selection when only that toggle is on', () => {
+ expect(getAuthorizationPreviewExplanation(false, true)).toContain(
+ 'an organization owner approves'
+ )
+ })
+
+ test('describes both when both toggles are on', () => {
+ expect(getAuthorizationPreviewExplanation(true, true)).toContain(
+ 'each member approves your app and picks'
+ )
+ })
+})
+
+describe('getResultingGrantDescription', () => {
+ test('returns legacy behaviour when both toggles are off', () => {
+ expect(getResultingGrantDescription(false, false)).toEqual(
+ 'Legacy behaviour, unchanged from today.'
+ )
+ })
+
+ test('returns per-member org-wide grant when only member-bound is on', () => {
+ expect(getResultingGrantDescription(true, false)).toEqual(
+ 'One grant per member, organization-wide.'
+ )
+ })
+
+ test('returns single scoped grant when only project scoping is on', () => {
+ expect(getResultingGrantDescription(false, true)).toEqual(
+ 'One organization grant, limited to chosen projects.'
+ )
+ })
+
+ test('returns per-member scoped grant when both are on', () => {
+ expect(getResultingGrantDescription(true, true)).toEqual(
+ 'One grant per member, limited to chosen projects.'
+ )
+ })
+})
+
+describe('isAuthorizationConfirmationPending', () => {
+ const off: AuthorizationToggleState = { checked: false, locked: false, confirmed: false }
+
+ test('is false when both toggles are off', () => {
+ expect(isAuthorizationConfirmationPending(off, off)).toBe(false)
+ })
+
+ test('is true when a toggle is newly enabled but not confirmed', () => {
+ const newlyEnabled: AuthorizationToggleState = {
+ checked: true,
+ locked: false,
+ confirmed: false,
+ }
+ expect(isAuthorizationConfirmationPending(newlyEnabled, off)).toBe(true)
+ })
+
+ test('is false when a newly enabled toggle has been confirmed', () => {
+ const confirmed: AuthorizationToggleState = { checked: true, locked: false, confirmed: true }
+ expect(isAuthorizationConfirmationPending(confirmed, off)).toBe(false)
+ })
+
+ test('is false when an enabled toggle is locked, regardless of confirmation', () => {
+ const locked: AuthorizationToggleState = { checked: true, locked: true, confirmed: false }
+ expect(isAuthorizationConfirmationPending(locked, off)).toBe(false)
+ })
+})
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel/Authorization.utils.ts b/apps/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel/Authorization.utils.ts
new file mode 100644
index 00000000000..a6404ba5d6e
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel/Authorization.utils.ts
@@ -0,0 +1,47 @@
+export interface AuthorizationToggleState {
+ checked: boolean
+ locked: boolean
+ confirmed: boolean
+}
+
+export function getAuthorizationPreviewExplanation(
+ isMemberBoundGrant: boolean,
+ isProjectScopingEnabled: boolean
+): string | null {
+ if (isMemberBoundGrant && isProjectScopingEnabled) {
+ return 'After you confirm, each member approves your app and picks which of their projects it can reach. It can do only what they can already do there.'
+ }
+ if (isMemberBoundGrant) {
+ return 'After you confirm, each member approves your app themselves. It can do only what that member can already do, across every project they can access.'
+ }
+ if (isProjectScopingEnabled) {
+ return 'After you confirm, an organization owner approves your app and picks which projects it can reach.'
+ }
+ return null
+}
+
+export function getResultingGrantDescription(
+ isMemberBoundGrant: boolean,
+ isProjectScopingEnabled: boolean
+): string {
+ if (isMemberBoundGrant && isProjectScopingEnabled) {
+ return 'One grant per member, limited to chosen projects.'
+ }
+ if (isMemberBoundGrant) {
+ return 'One grant per member, organization-wide.'
+ }
+ if (isProjectScopingEnabled) {
+ return 'One organization grant, limited to chosen projects.'
+ }
+ return 'Legacy behaviour, unchanged from today.'
+}
+
+export function isAuthorizationConfirmationPending(
+ memberBoundGrant: AuthorizationToggleState,
+ projectScoping: AuthorizationToggleState
+): boolean {
+ const isPending = (toggle: AuthorizationToggleState) =>
+ toggle.checked && !toggle.locked && !toggle.confirmed
+
+ return isPending(memberBoundGrant) || isPending(projectScoping)
+}
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel/PublishAppSidePanel.utils.ts b/apps/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel/PublishAppSidePanel.utils.ts
new file mode 100644
index 00000000000..a46d5f0da11
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel/PublishAppSidePanel.utils.ts
@@ -0,0 +1,49 @@
+import * as z from 'zod'
+
+import { isValidHttpUrl } from '@/lib/helpers'
+
+export const formSchema = z.object({
+ name: z.string().min(1, 'Please provide a name for your application'),
+ website: z
+ .string()
+ .min(1, 'Please provide a URL for your site')
+ .url('Please provide a URL for your site')
+ .refine((value) => isValidHttpUrl(value), 'Please provide a valid URL for your site'),
+ redirect_uris: z
+ .array(
+ z.object({
+ id: z.string(),
+ value: z.string().min(1, 'Please provide a URL').url('Please provide a URL'),
+ }),
+ { required_error: 'Please provide at least one callback URL' }
+ )
+ .min(1, 'Please provide at least one callback URL'),
+})
+
+export type FormSchema = z.infer<typeof formSchema>
+
+export const formSchemaWithOAuthAppScopedGrants = formSchema
+ .extend({
+ member_bound_grant: z.coerce.boolean(),
+ member_bound_grant_confirmed: z.coerce.boolean().optional(),
+ project_scoping: z.coerce.boolean(),
+ project_scoping_confirmed: z.coerce.boolean().optional(),
+ })
+ .superRefine((values, context) => {
+ if (values.member_bound_grant && !values.member_bound_grant_confirmed) {
+ context.addIssue({
+ code: 'custom',
+ path: ['member_bound_grant_confirmed'],
+ message: 'Please confirm you want to use the permissions of the person who connects',
+ })
+ }
+ if (values.project_scoping && !values.project_scoping_confirmed) {
+ context.addIssue({
+ code: 'custom',
+ path: ['project_scoping_confirmed'],
+ message: 'Please confirm you want users to select specific projects',
+ })
+ }
+ })
+
+export type FormSchemaWithOAuthAppScopedGrants = z.infer<typeof formSchemaWithOAuthAppScopedGrants>
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel/index.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel/index.tsx
index d3210a835aa..143205936b5 100644
--- a/apps/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel/index.tsx
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/PublishAppSidePanel/index.tsx
@@ -1,9 +1,9 @@
import { zodResolver } from '@hookform/resolvers/zod'
import type { OAuthScope } from '@supabase/shared-types/out/constants'
-import { useParams } from 'common'
+import { useFlag, useParams } from 'common'
import { Edit, Upload } from 'lucide-react'
import { ChangeEvent, useEffect, useRef, useState } from 'react'
-import { SubmitHandler, useFieldArray, useForm, useWatch } from 'react-hook-form'
+import { Control, SubmitHandler, useFieldArray, useForm, useWatch } from 'react-hook-form'
import { toast } from 'sonner'
import {
AlertDialog,
@@ -31,10 +31,16 @@ import {
SidePanel,
} from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
-import * as z from 'zod'
import { AuthorizeRequesterDetails } from '../AuthorizeRequesterDetails'
import { OAuthSecrets } from '../OAuthSecrets/OAuthSecrets'
+import { AuthorizationSection } from './Authorization'
+import {
+ formSchema,
+ FormSchema,
+ FormSchemaWithOAuthAppScopedGrants,
+ formSchemaWithOAuthAppScopedGrants,
+} from './PublishAppSidePanel.utils'
import { ScopesPanel } from './Scopes'
import { DocsButton } from '@/components/ui/DocsButton'
import { Shortcut } from '@/components/ui/Shortcut'
@@ -45,7 +51,7 @@ import {
import { useOAuthAppUpdateMutation } from '@/data/oauth/oauth-app-update-mutation'
import type { OAuthApp } from '@/data/oauth/oauth-apps-query'
import { DOCS_URL } from '@/lib/constants'
-import { isValidHttpUrl, uuidv4 } from '@/lib/helpers'
+import { uuidv4 } from '@/lib/helpers'
import { uploadAttachment } from '@/lib/upload'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
@@ -56,25 +62,10 @@ export interface PublishAppSidePanelProps {
onCreateSuccess: (app: OAuthAppCreateResponse) => void
}
-const formSchema = z.object({
- name: z.string().min(1, 'Please provide a name for your application'),
- website: z
- .string()
- .min(1, 'Please provide a URL for your site')
- .url('Please provide a URL for your site')
- .refine((value) => isValidHttpUrl(value), 'Please provide a valid URL for your site'),
- redirect_uris: z
- .array(
- z.object({
- id: z.string(),
- value: z.string().min(1, 'Please provide a URL').url('Please provide a URL'),
- }),
- { required_error: 'Please provide at least one callback URL' }
- )
- .min(1, 'Please provide at least one callback URL'),
-})
-
-const getFormDefaultValues = (selectedApp: OAuthApp | undefined) => {
+const getFormDefaultValues = (
+ selectedApp: OAuthApp | undefined,
+ withOAuthAppScopedGrants = false
+): FormSchema => {
if (selectedApp) {
return {
name: selectedApp.name,
@@ -83,13 +74,36 @@ const getFormDefaultValues = (selectedApp: OAuthApp | undefined) => {
selectedApp.redirect_uris?.map((url) => {
return { id: uuidv4(), value: url }
}) ?? [],
+ ...(withOAuthAppScopedGrants
+ ? {
+ // TODO: read the next 4 props from the selected app once implemented in backend
+ // Set to true to verify it can't be changed once enabled
+ member_bound_grant: true,
+ member_bound_grant_confirmed: true,
+ // Set to false to verify it can be changed if it wasn't enabled before
+ project_scoping: false,
+ project_scoping_confirmed: false,
+ }
+ : {}),
}
}
- return { name: '', website: '', redirect_uris: [{ id: uuidv4(), value: '' }] }
+ return {
+ name: '',
+ website: '',
+ redirect_uris: [{ id: uuidv4(), value: '' }],
+ ...(withOAuthAppScopedGrants
+ ? {
+ member_bound_grant: false,
+ member_bound_grant_confirmed: false,
+ project_scoping: false,
+ project_scoping_confirmed: false,
+ }
+ : {}),
+ }
}
-type FormSchema = z.infer<typeof formSchema>
+const FORM_ID = 'publish-oauth-app-form'
export const PublishAppSidePanel = ({
visible,
@@ -99,6 +113,7 @@ export const PublishAppSidePanel = ({
}: PublishAppSidePanelProps) => {
const { slug } = useParams()
const uploadButtonRef = useRef<HTMLInputElement | null>(null)
+ const areOAuthAppScopedGrantsEnabled = useFlag('OauthAppScopedGrants')
const { mutateAsync: createOAuthApp } = useOAuthAppCreateMutation({
onSuccess: (res, variables) => {
@@ -141,7 +156,8 @@ export const PublishAppSidePanel = ({
const onFileUpload = async (event: ChangeEvent<HTMLInputElement>) => {
event.persist()
- const [file] = event.target.files || (event as any).dataTransfer.items
+ const file = event.target.files?.[0]
+ if (!file) return
setIconFile(file)
setIconUrl(URL.createObjectURL(file))
event.target.value = ''
@@ -189,19 +205,25 @@ export const PublishAppSidePanel = ({
}
}
- const form = useForm<FormSchema>({
- defaultValues: getFormDefaultValues(selectedApp),
- resolver: zodResolver(formSchema),
+ const form = useForm<
+ typeof areOAuthAppScopedGrantsEnabled extends true
+ ? FormSchemaWithOAuthAppScopedGrants
+ : FormSchema
+ >({
+ defaultValues: getFormDefaultValues(selectedApp, areOAuthAppScopedGrantsEnabled),
+ resolver: zodResolver(
+ areOAuthAppScopedGrantsEnabled ? formSchemaWithOAuthAppScopedGrants : formSchema
+ ),
})
const { reset } = form
const { errors, isSubmitting } = form.formState
useEffect(() => {
if (visible) {
- const defaultValues = getFormDefaultValues(selectedApp)
+ const defaultValues = getFormDefaultValues(selectedApp, areOAuthAppScopedGrantsEnabled)
reset(defaultValues)
}
- }, [visible, selectedApp, reset])
+ }, [visible, selectedApp, reset, areOAuthAppScopedGrantsEnabled])
const name = useWatch({ name: 'name', control: form.control })
const website = useWatch({ name: 'website', control: form.control })
@@ -217,227 +239,223 @@ export const PublishAppSidePanel = ({
return (
<SidePanel
- hideFooter
size="large"
visible={visible}
header={
selectedApp !== undefined ? 'Update OAuth application' : 'Publish a new OAuth application'
}
onCancel={() => onClose()}
+ customFooter={
+ <div className="flex items-center justify-between w-full px-4 sm:px-6 py-4 border-t bg-overlay">
+ <Button
+ onClick={() => setShowPreview(true)}
+ disabled={name.length === 0 || website.length === 0}
+ >
+ Preview consent for users
+ </Button>
+ <div className="flex items-center space-x-2">
+ <Button disabled={isSubmitting} onClick={() => onClose()}>
+ Cancel
+ </Button>
+ <Shortcut
+ id={SHORTCUT_IDS.ORG_OAUTH_APPS_SUBMIT}
+ onTrigger={() => form.handleSubmit(onSubmit)()}
+ options={{ enabled: visible && !isSubmitting }}
+ side="top"
+ >
+ <Button
+ variant="primary"
+ type="submit"
+ form={FORM_ID}
+ loading={isSubmitting}
+ disabled={isSubmitting}
+ >
+ Confirm
+ </Button>
+ </Shortcut>
+ </div>
+ </div>
+ }
>
<Form {...form}>
- <form onSubmit={form.handleSubmit(onSubmit)}>
- <div className="h-full flex flex-col">
- <div className="grow">
- <SidePanel.Content>
- <div className="py-4 flex items-start justify-between gap-10">
- <div className="space-y-4 w-full">
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormItemLayout
- layout="vertical"
- label="Application name"
- description={selectedApp?.id && `ID: ${selectedApp.id}`}
- >
- <FormControl className="col-span-6">
- <Input {...field} />
- </FormControl>
- </FormItemLayout>
- )}
- />
- <FormField
- control={form.control}
- name="website"
- render={({ field }) => (
- <FormItemLayout layout="vertical" label="Website URL">
- <FormControl className="col-span-6">
- <Input {...field} placeholder="https://my-website.com" />
- </FormControl>
- </FormItemLayout>
- )}
- />
+ <form id={FORM_ID} onSubmit={form.handleSubmit(onSubmit)}>
+ <SidePanel.Content>
+ <div className="py-4 flex items-start justify-between gap-10">
+ <div className="space-y-4 w-full">
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItemLayout
+ layout="vertical"
+ label="Application name"
+ description={selectedApp?.id && `ID: ${selectedApp.id}`}
+ >
+ <FormControl className="col-span-6">
+ <Input {...field} />
+ </FormControl>
+ </FormItemLayout>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name="website"
+ render={({ field }) => (
+ <FormItemLayout layout="vertical" label="Website URL">
+ <FormControl className="col-span-6">
+ <Input {...field} placeholder="https://my-website.com" />
+ </FormControl>
+ </FormItemLayout>
+ )}
+ />
+ </div>
+ <div>
+ {iconUrl !== undefined ? (
+ <div
+ className={cn(
+ 'shadow-sm transition group relative',
+ 'bg-center bg-cover bg-no-repeat',
+ 'mt-4 mr-4 space-y-2 rounded-full h-[120px] w-[120px] flex flex-col items-center justify-center'
+ )}
+ style={{
+ backgroundImage: iconUrl ? `url("${iconUrl}")` : 'none',
+ }}
+ >
+ <div className="absolute bottom-1 right-1">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button className="px-1">
+ <Edit />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" side="bottom">
+ <DropdownMenuItem
+ key="upload"
+ onClick={() => {
+ uploadButtonRef.current?.click()
+ }}
+ >
+ <p>Upload image</p>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ key="remove"
+ onClick={() => {
+ setIconFile(undefined)
+ setIconUrl(undefined)
+ }}
+ >
+ <p>Remove image</p>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
</div>
- <div>
- {iconUrl !== undefined ? (
- <div
- className={cn(
- 'shadow-sm transition group relative',
- 'bg-center bg-cover bg-no-repeat',
- 'mt-4 mr-4 space-y-2 rounded-full h-[120px] w-[120px] flex flex-col items-center justify-center'
- )}
- style={{
- backgroundImage: iconUrl ? `url("${iconUrl}")` : 'none',
- }}
- >
- <div className="absolute bottom-1 right-1">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button className="px-1">
- <Edit />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" side="bottom">
- <DropdownMenuItem
- key="upload"
- onClick={() => {
- if (uploadButtonRef.current)
- (uploadButtonRef.current as any).click()
- }}
- >
- <p>Upload image</p>
- </DropdownMenuItem>
- <DropdownMenuItem
- key="remove"
- onClick={() => {
- setIconFile(undefined)
- setIconUrl(undefined)
- }}
- >
- <p>Remove image</p>
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </div>
- ) : (
- <div
- className={cn(
- 'border border-strong transition opacity-75 hover:opacity-100',
- 'mt-4 mr-4 space-y-2 rounded-full h-[120px] w-[120px] flex flex-col items-center justify-center cursor-pointer'
- )}
- onClick={() => {
- if (uploadButtonRef.current) (uploadButtonRef.current as any).click()
- }}
- >
- <Upload size={18} strokeWidth={1.5} className="text-foreground" />
- <p className="text-xs text-foreground-light">Upload logo</p>
- </div>
+ ) : (
+ <div
+ className={cn(
+ 'border border-strong transition opacity-75 hover:opacity-100',
+ 'mt-4 mr-4 space-y-2 rounded-full h-[120px] w-[120px] flex flex-col items-center justify-center cursor-pointer'
)}
- <input
- multiple
- type="file"
- ref={uploadButtonRef}
- className="hidden"
- accept="image/png, image/jpeg"
- onChange={onFileUpload}
- />
+ onClick={() => {
+ uploadButtonRef.current?.click()
+ }}
+ >
+ <Upload size={18} strokeWidth={1.5} className="text-foreground" />
+ <p className="text-xs text-foreground-light">Upload logo</p>
</div>
- </div>
- </SidePanel.Content>
+ )}
+ <input
+ multiple
+ type="file"
+ ref={uploadButtonRef}
+ className="hidden"
+ accept="image/png, image/jpeg"
+ onChange={onFileUpload}
+ />
+ </div>
+ </div>
+ </SidePanel.Content>
- <SidePanel.Separator />
+ <SidePanel.Separator />
+ <SidePanel.Content className="py-4">
+ <div className="mb-2 flex items-center justify-between">
+ <div>
+ <p className="text-foreground text-sm">Authorization callback URLs</p>
+ <p className="text-sm text-foreground-light">
+ All URLs must use HTTPS, except for localhost
+ </p>
+ </div>
+ <Button onClick={() => appendCallbackUrl({ id: uuidv4(), value: '' })}>
+ Add URL
+ </Button>
+ </div>
+ <div className="space-y-2 pb-2">
+ {callbackUrlsFields.map((url, index) => (
+ <FormField
+ key={url.id}
+ control={form.control}
+ name={`redirect_uris.${index}.value`}
+ render={({ field }) => (
+ <FormItemLayout
+ layout="vertical"
+ label={<span className="sr-only">Callback URL</span>}
+ >
+ <FormControl>
+ <InputGroup>
+ <InputGroupInput {...field} placeholder="e.g https://my-website.com" />
+ {callbackUrlsFields.length > 1 ? (
+ <InputGroupAddon align="inline-end">
+ <InputGroupButton
+ variant="default"
+ onClick={() => removeCallbackUrl(index)}
+ >
+ Remove
+ </InputGroupButton>
+ </InputGroupAddon>
+ ) : null}
+ </InputGroup>
+ </FormControl>
+ </FormItemLayout>
+ )}
+ />
+ ))}
+ {errors.redirect_uris?.root != null ? (
+ <p className="text-red-900 text-sm">{errors.redirect_uris?.root.message}</p>
+ ) : null}
+ </div>
+ </SidePanel.Content>
+
+ {selectedApp !== undefined && (
+ <>
+ <SidePanel.Separator />
<SidePanel.Content className="py-4">
- <div className="mb-2 flex items-center justify-between">
- <div>
- <p className="text-foreground text-sm">Authorization callback URLs</p>
- <p className="text-sm text-foreground-light">
- All URLs must use HTTPS, except for localhost
- </p>
- </div>
- <Button onClick={() => appendCallbackUrl({ id: uuidv4(), value: '' })}>
- Add URL
- </Button>
- </div>
- <div className="space-y-2 pb-2">
- {callbackUrlsFields.map((url, index) => (
- <FormField
- key={url.id}
- control={form.control}
- name={`redirect_uris.${index}.value`}
- render={({ field }) => (
- <FormItemLayout
- layout="vertical"
- label={<span className="sr-only">Callback URL</span>}
- >
- <FormControl>
- <InputGroup>
- <InputGroupInput
- {...field}
- placeholder="e.g https://my-website.com"
- />
- {callbackUrlsFields.length > 1 ? (
- <InputGroupAddon align="inline-end">
- <InputGroupButton
- variant="default"
- onClick={() => removeCallbackUrl(index)}
- >
- Remove
- </InputGroupButton>
- </InputGroupAddon>
- ) : null}
- </InputGroup>
- </FormControl>
- </FormItemLayout>
- )}
- />
- ))}
- {errors.redirect_uris?.root != null ? (
- <p className="text-red-900 text-sm">{errors.redirect_uris?.root.message}</p>
- ) : null}
- </div>
+ <OAuthSecrets selectedApp={selectedApp} />
</SidePanel.Content>
+ </>
+ )}
- {selectedApp !== undefined && (
- <>
- <SidePanel.Separator />
- <SidePanel.Content className="py-4">
- <OAuthSecrets selectedApp={selectedApp} />
- </SidePanel.Content>
- </>
- )}
-
+ {isFormSchemaWithOAuthAppScopedGrants(form.control, areOAuthAppScopedGrantsEnabled) && (
+ <>
<SidePanel.Separator />
- <div className="p-6 ">
- <div className="flex items-start justify-between space-x-4 pb-4">
- <div className="flex flex-col">
- <span className="text-sm text-foreground">Application permissions</span>
- <span className="text-sm text-foreground-light">
- The application permissions are organized in scopes and will be presented to
- the user when adding an app to their organization and all of its projects.
- </span>
- </div>
- <DocsButton href={`${DOCS_URL}/guides/platform/oauth-apps/oauth-scopes`} />
- </div>
+ <AuthorizationSection control={form.control} />
+ </>
+ )}
- <ScopesPanel scopes={scopes} setScopes={setScopes} />
+ <SidePanel.Separator />
+ <div className="p-6 ">
+ <div className="flex items-start justify-between space-x-4 pb-4">
+ <div className="flex flex-col">
+ <span className="text-sm text-foreground">Application permissions</span>
+ <span className="text-sm text-foreground-light">
+ The application permissions are organized in scopes and will be presented to the
+ user when adding an app to their organization and all of its projects.
+ </span>
</div>
+ <DocsButton href={`${DOCS_URL}/guides/platform/oauth-apps/oauth-scopes`} />
</div>
- <SidePanel.Separator />
-
- <SidePanel.Content>
- <div className="pt-2 pb-3 flex items-center justify-between">
- <Button
- onClick={() => setShowPreview(true)}
- disabled={name.length === 0 || website.length === 0}
- >
- Preview consent for users
- </Button>
- <div className="flex items-center space-x-2">
- <Button disabled={isSubmitting} onClick={() => onClose()}>
- Cancel
- </Button>
- <Shortcut
- id={SHORTCUT_IDS.ORG_OAUTH_APPS_SUBMIT}
- onTrigger={() => form.handleSubmit(onSubmit)()}
- options={{ enabled: visible && !isSubmitting }}
- side="top"
- >
- <Button
- variant="primary"
- type="submit"
- loading={isSubmitting}
- disabled={isSubmitting}
- >
- Confirm
- </Button>
- </Shortcut>
- </div>
- </div>
- </SidePanel.Content>
+ <ScopesPanel scopes={scopes} setScopes={setScopes} />
</div>
<AlertDialog open={showPreview} onOpenChange={(open) => setShowPreview(open)}>
@@ -472,3 +490,10 @@ export const PublishAppSidePanel = ({
</SidePanel>
)
}
+
+const isFormSchemaWithOAuthAppScopedGrants = (
+ _schema: Control<FormSchema> | Control<FormSchemaWithOAuthAppScopedGrants>,
+ withOAuthAppScopedGrants: boolean
+): _schema is Control<FormSchemaWithOAuthAppScopedGrants> => {
+ return withOAuthAppScopedGrants
+}