Skip to content

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

Reinstate old org invite flow endpoints (#27681)

Joshen Limd4116e9bfcf6
diff --git a/apps/studio/components/interfaces/Organization/TeamSettings/InviteMemberButton.tsx b/apps/studio/components/interfaces/Organization/TeamSettings/InviteMemberButton.tsx
index dc31cdc15f9..9928c2fa3eb 100644
--- a/apps/studio/components/interfaces/Organization/TeamSettings/InviteMemberButton.tsx
+++ b/apps/studio/components/interfaces/Organization/TeamSettings/InviteMemberButton.tsx
@@ -40,6 +40,8 @@ import {
Tooltip_Shadcn_,
} from 'ui'
import { useGetRolesManagementPermissions } from './TeamSettings.utils'
+import { useOrganizationMemberInviteCreateMutation } from 'data/organizations/organization-member-invite-create-mutation'
+import { isNil } from 'lodash'
export const InviteMemberButton = () => {
const { slug } = useParams()
@@ -81,6 +83,8 @@ export const InviteMemberButton = () => {
)
const { mutate: inviteMember, isLoading: isInviting } = useOrganizationCreateInvitationMutation()
+ const { mutate: inviteMemberOld, isLoading: isInvitingOld } =
+ useOrganizationMemberInviteCreateMutation()
const FormSchema = z.object({
email: z.string().email('Must be a valid email address').min(1, 'Email is required'),
@@ -102,6 +106,7 @@ export const InviteMemberButton = () => {
if (!slug) return console.error('Slug is required')
if (profile?.id === undefined) return console.error('Profile ID required')
+ const developerRole = orgScopedRoles.find((role) => role.name === 'Developer')
const existingMember = (members ?? []).find(
(member) => member.primary_email === values.email.toLowerCase()
)
@@ -113,28 +118,54 @@ export const InviteMemberButton = () => {
}
}
- inviteMember(
- {
- slug,
- email: values.email.toLowerCase(),
- roleId: Number(values.role),
- ...(!values.applyToOrg && values.projectRef ? { projects: [values.projectRef] } : {}),
- },
- {
- onSuccess: () => {
- toast.success('Successfully sent invitation to new member')
- setIsOpen(!isOpen)
+ if (projectLevelPermissionsEnabled) {
+ inviteMember(
+ {
+ slug,
+ email: values.email.toLowerCase(),
+ roleId: Number(values.role),
+ ...(!values.applyToOrg && values.projectRef ? { projects: [values.projectRef] } : {}),
+ },
+ {
+ onSuccess: () => {
+ toast.success('Successfully sent invitation to new member')
+ setIsOpen(!isOpen)
- const developerRole = orgScopedRoles.find((role) => role.name === 'Developer')
- form.reset({
- email: '',
- role: developerRole?.id.toString() ?? '',
- applyToOrg: true,
- projectRef: '',
- })
+ form.reset({
+ email: '',
+ role: developerRole?.id.toString() ?? '',
+ applyToOrg: true,
+ projectRef: '',
+ })
+ },
+ }
+ )
+ } else {
+ inviteMemberOld(
+ {
+ slug,
+ invitedEmail: values.email.toLowerCase(),
+ ownerId: profile.id,
+ roleId: Number(values.role),
},
- }
- )
+ {
+ onSuccess: (data) => {
+ if (isNil(data)) {
+ toast.error('Failed to add member')
+ } else {
+ toast.success('Successfully added new member')
+ setIsOpen(!isOpen)
+ form.reset({
+ email: '',
+ role: developerRole?.id.toString() ?? '',
+ applyToOrg: true,
+ projectRef: '',
+ })
+ }
+ },
+ }
+ )
+ }
}
useEffect(() => {
@@ -296,7 +327,7 @@ export const InviteMemberButton = () => {
autoFocus
{...field}
autoComplete="off"
- disabled={isInviting}
+ disabled={isInviting || isInvitingOld}
placeholder="Enter email address"
/>
</FormControl_Shadcn_>
@@ -307,7 +338,7 @@ export const InviteMemberButton = () => {
</DialogSection>
<DialogSectionSeparator />
<DialogSection className="pt-0">
- <Button block htmlType="submit" loading={isInviting} disabled={isInviting}>
+ <Button block htmlType="submit" loading={isInviting || isInvitingOld}>
Send invitation
</Button>
</DialogSection>
diff --git a/apps/studio/components/interfaces/Organization/TeamSettings/MemberActions.tsx b/apps/studio/components/interfaces/Organization/TeamSettings/MemberActions.tsx
index b8b5a4d55e2..0f3a3490db9 100644
--- a/apps/studio/components/interfaces/Organization/TeamSettings/MemberActions.tsx
+++ b/apps/studio/components/interfaces/Organization/TeamSettings/MemberActions.tsx
@@ -4,6 +4,7 @@ import { useState } from 'react'
import toast from 'react-hot-toast'
import { useParams } from 'common'
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { useOrganizationCreateInvitationMutation } from 'data/organization-members/organization-invitation-create-mutation'
import { useOrganizationDeleteInvitationMutation } from 'data/organization-members/organization-invitation-delete-mutation'
import { useOrganizationRolesV2Query } from 'data/organization-members/organization-roles-query'
@@ -14,7 +15,7 @@ import {
} from 'data/organizations/organization-members-query'
import { usePermissionsQuery } from 'data/permissions/permissions-query'
import { useProjectsQuery } from 'data/projects/projects-query'
-import { useCheckPermissions, useIsFeatureEnabled, useSelectedOrganization } from 'hooks'
+import { useCheckPermissions, useFlag, useIsFeatureEnabled, useSelectedOrganization } from 'hooks'
import { useProfile } from 'lib/profile'
import {
Button,
@@ -23,14 +24,12 @@ import {
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
- TooltipContent_Shadcn_,
- TooltipTrigger_Shadcn_,
- Tooltip_Shadcn_,
} from 'ui'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { useGetRolesManagementPermissions } from './TeamSettings.utils'
import { UpdateRolesPanel } from './UpdateRolesPanel/UpdateRolesPanel'
-import { ButtonTooltip } from 'components/ui/ButtonTooltip'
+import { useOrganizationMemberInviteDeleteMutation } from 'data/organizations/organization-member-invite-delete-mutation'
+import { useOrganizationMemberInviteCreateMutation } from 'data/organizations/organization-member-invite-create-mutation'
interface MemberActionsProps {
member: OrganizationMember
@@ -48,6 +47,7 @@ export const MemberActions = ({ member }: MemberActionsProps) => {
const { data: allProjects } = useProjectsQuery()
const { data: members } = useOrganizationMembersQuery({ slug })
const { data: allRoles } = useOrganizationRolesV2Query({ slug })
+ const projectLevelPermissionsEnabled = useFlag('projectLevelPermissions')
const orgScopedRoles = allRoles?.org_scoped_roles ?? []
const projectScopedRoles = allRoles?.project_scoped_roles ?? []
@@ -92,9 +92,20 @@ export const MemberActions = ({ member }: MemberActionsProps) => {
toast.error(`Failed to resend invitation: ${error.message}`)
},
})
+ const { mutate: inviteMemberOld, isLoading: isCreatingInviteOld } =
+ useOrganizationMemberInviteCreateMutation({
+ onSuccess: () => {
+ toast.success('Resent the invitation')
+ },
+ onError: (error) => {
+ toast.error(`Failed to resend the invidation: ${error.message}`)
+ },
+ })
const { mutate: deleteInvitation, isLoading: isDeletingInvite } =
useOrganizationDeleteInvitationMutation()
+ const { mutate: deleteInvitationOld, isLoading: isDeletingInviteOld } =
+ useOrganizationMemberInviteDeleteMutation()
const isLoading = isDeletingMember || isDeletingInvite || isCreatingInvite
@@ -111,28 +122,44 @@ export const MemberActions = ({ member }: MemberActionsProps) => {
if (!slug) return console.error('Slug is required')
if (!invitedId) return console.error('Member invited ID is required')
- deleteInvitation(
- { slug, id: invitedId, skipInvalidation: true },
- {
- onSuccess: () => {
- if (!member.primary_email) return toast.error('Email is required')
- const projectScopedRole = projectScopedRoles.find((role) => role.id === roleId)
- if (projectScopedRole !== undefined) {
- const projects = (projectScopedRole?.project_ids ?? [])
- .map((id) => allProjects?.find((p) => p.id === id)?.ref)
- .filter(Boolean) as string[]
- inviteMember({
+ if (projectLevelPermissionsEnabled) {
+ deleteInvitation(
+ { slug, id: invitedId, skipInvalidation: true },
+ {
+ onSuccess: () => {
+ if (!member.primary_email) return toast.error('Email is required')
+ const projectScopedRole = projectScopedRoles.find((role) => role.id === roleId)
+ if (projectScopedRole !== undefined) {
+ const projects = (projectScopedRole?.project_ids ?? [])
+ .map((id) => allProjects?.find((p) => p.id === id)?.ref)
+ .filter(Boolean) as string[]
+ inviteMember({
+ slug,
+ email: member.primary_email,
+ roleId: projectScopedRole.base_role_id,
+ projects,
+ })
+ } else {
+ inviteMember({ slug, email: member.primary_email, roleId })
+ }
+ },
+ }
+ )
+ } else {
+ deleteInvitationOld(
+ { slug, invitedId, invalidateDetail: false },
+ {
+ onSuccess: () => {
+ inviteMemberOld({
slug,
- email: member.primary_email,
- roleId: projectScopedRole.base_role_id,
- projects,
+ invitedEmail: member.primary_email!,
+ ownerId: invitedId,
+ roleId,
})
- } else {
- inviteMember({ slug, email: member.primary_email, roleId })
- }
- },
- }
- )
+ },
+ }
+ )
+ }
}
const handleRevokeInvitation = (member: OrganizationMember) => {
@@ -140,14 +167,17 @@ export const MemberActions = ({ member }: MemberActionsProps) => {
if (!slug) return console.error('Slug is required')
if (!invitedId) return console.error('Member invited ID is required')
- deleteInvitation(
- { slug, id: invitedId },
- {
- onSuccess: () => {
- toast.success('Successfully revoked the invitation.')
- },
- }
- )
+ if (projectLevelPermissionsEnabled) {
+ deleteInvitation(
+ { slug, id: invitedId },
+ { onSuccess: () => toast.success('Successfully revoked the invitation.') }
+ )
+ } else {
+ deleteInvitationOld(
+ { slug, invitedId },
+ { onSuccess: () => toast.success('Successfully revoked the invitation.') }
+ )
+ }
}
if (!canRemoveMember || (isPendingInviteAcceptance && !canResendInvite && !canRevokeInvite)) {
diff --git a/apps/studio/components/interfaces/OrganizationInvite/OrganizationInviteOld.tsx b/apps/studio/components/interfaces/OrganizationInvite/OrganizationInviteOld.tsx
new file mode 100644
index 00000000000..ae011e71a6f
--- /dev/null
+++ b/apps/studio/components/interfaces/OrganizationInvite/OrganizationInviteOld.tsx
@@ -0,0 +1,272 @@
+import { CheckSquare } from 'lucide-react'
+import Link from 'next/link'
+import { useRouter } from 'next/router'
+import { useEffect, useState } from 'react'
+import toast from 'react-hot-toast'
+
+import { useParams } from 'common'
+import { useOrganizationJoinDeclineMutation } from 'data/organizations/organization-join-decline-mutation'
+import { useOrganizationJoinMutation } from 'data/organizations/organization-join-mutation'
+import {
+ TokenInfo,
+ validateTokenInformation,
+} from 'data/organizations/organization-join-token-validation-query'
+import { useSignOut } from 'lib/auth'
+import { useProfile } from 'lib/profile'
+import { Button, Loading } from 'ui'
+
+export const OrganizationInviteOld = () => {
+ const router = useRouter()
+ const signOut = useSignOut()
+ const { profile } = useProfile()
+ const { slug, token, name } = useParams()
+
+ const [isSubmitting, setIsSubmitting] = useState(false)
+ const [error, setError] = useState<any>()
+ const [tokenValidationInfo, setTokenValidationInfo] = useState<TokenInfo>(undefined)
+ const [tokenInfoLoaded, setTokenInfoLoaded] = useState(false)
+
+ const {
+ token_does_not_exist,
+ sso_mismatch,
+ email_match,
+ expired_token,
+ organization_name,
+ invite_id,
+ } = tokenValidationInfo || {}
+
+ const loginRedirectLink = `/?returnTo=${encodeURIComponent(`/join?token=${token}&slug=${slug}`)}`
+
+ const { mutate: joinOrganization } = useOrganizationJoinMutation({
+ onSuccess: () => {
+ setIsSubmitting(false)
+ router.push('/')
+ },
+ onError: (error) => {
+ toast.error(`Failed to join organization: ${error.message}`)
+ setIsSubmitting(false)
+ },
+ })
+
+ const { mutate: declineOrganization } = useOrganizationJoinDeclineMutation({
+ onSuccess: () => {
+ setIsSubmitting(false)
+ router.push('/')
+ },
+ onError: (error) => {
+ toast.error(`Failed to decline invitation: ${error.message}`)
+ setIsSubmitting(false)
+ },
+ })
+
+ const isError =
+ error ||
+ !!(tokenInfoLoaded && sso_mismatch) ||
+ !!(tokenInfoLoaded && token_does_not_exist) ||
+ (tokenInfoLoaded && !email_match) ||
+ (tokenInfoLoaded && expired_token)
+
+ const ErrorMessage = () => {
+ const Container = ({ children }: { children: React.ReactNode }) => (
+ <div
+ className={[
+ 'flex flex-col items-center justify-center gap-3 text-sm',
+ isError ? 'text-foreground-light' : 'text-foreground',
+ ].join(' ')}
+ >
+ {children}
+ </div>
+ )
+
+ const message = error ? (
+ <p>There was an error requesting details for this invitation. ({error.message})</p>
+ ) : sso_mismatch ? (
+ <>
+ <p>SSO providers do not match.</p>
+ <p className="text-foreground-lighter">
+ This invitation comes from a different identity provider than the one you are currently
+ logged in with. Please use the same SSO provider instead.
+ </p>
+ </>
+ ) : token_does_not_exist ? (
+ <>
+ <p>The invite token is invalid.</p>
+ <p className="text-foreground-lighter">
+ Try copying and pasting the link from the invite email, or ask the organization owner to
+ invite you again.
+ </p>
+ </>
+ ) : !email_match ? (
+ <>
+ <p>
+ Your email address {profile?.primary_email} does not match the email address this
+ invitation was sent to.
+ </p>
+ <p className="text-foreground-lighter">
+ To accept this invitation, you will need to{' '}
+ <a
+ className="cursor-pointer text-brand"
+ onClick={async () => {
+ await signOut()
+ router.reload()
+ }}
+ >
+ sign out
+ </a>{' '}
+ and then sign in or create a new account using the same email address used in the
+ invitation.
+ </p>
+ </>
+ ) : expired_token ? (
+ <>
+ <p>The invite token has expired.</p>
+ <p className="text-foreground-lighter">
+ Please request a new one from the organization owner.
+ </p>
+ </>
+ ) : (
+ ''
+ )
+
+ return isError ? <Container>{message}</Container> : null
+ }
+
+ const Content = () => (
+ <>
+ <div className="flex flex-col gap-2 px-6 py-8">
+ <>
+ <p className="text-sm text-foreground">You have been invited to join </p>
+ {organization_name ? (
+ <>
+ <p className="text-3xl text-foreground">
+ {name ? name : organization_name ? `${organization_name}` : 'an organization'}
+ </p>
+ {!token_does_not_exist && (
+ <p className="text-sm text-foreground-lighter">an organization on Supabase</p>
+ )}
+ </>
+ ) : (
+ <>
+ <p className="text-3xl text-foreground">{'an organization'}</p>
+ </>
+ )}
+ {slug && (
+ <p className="text-xs text-foreground-lighter">{`organization slug: ${slug}`}</p>
+ )}
+ </>
+ </div>
+
+ <div
+ className={['border-t border-muted', isError ? 'bg-alternative' : 'bg-transparent'].join(
+ ' '
+ )}
+ >
+ <div className="flex flex-col gap-4 px-6 py-4 ">
+ {profile && !isError && (
+ <div className="flex flex-row items-center justify-center gap-3">
+ <Button onClick={handleDeclineJoinOrganization} htmlType="submit" type="default">
+ Decline
+ </Button>
+ <Button
+ onClick={handleJoinOrganization}
+ htmlType="submit"
+ loading={isSubmitting}
+ type="primary"
+ icon={<CheckSquare />}
+ >
+ Join organization
+ </Button>
+ </div>
+ )}
+
+ {tokenInfoLoaded && <ErrorMessage />}
+
+ {!profile && (
+ <div className="flex flex-col gap-3">
+ <p className="text-xs text-foreground-lighter">
+ You will need to sign in to accept this invitation
+ </p>
+ <div className="flex justify-center gap-3">
+ <Button asChild type="default">
+ <Link href={loginRedirectLink}>Sign in</Link>
+ </Button>
+ <Button asChild type="default">
+ <Link href={loginRedirectLink}>Create an account</Link>
+ </Button>
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ </>
+ )
+
+ async function handleJoinOrganization() {
+ if (!slug) return console.error('Slug is required')
+ if (!token) return console.error('Token is required')
+ setIsSubmitting(true)
+ joinOrganization({ slug, token })
+ }
+
+ async function handleDeclineJoinOrganization() {
+ if (!slug) return console.error('Slug is required')
+ if (!invite_id) return console.error('Invite ID is required')
+ setIsSubmitting(true)
+ declineOrganization({ slug, invited_id: invite_id })
+ }
+
+ useEffect(() => {
+ const fetchTokenInfo = async () => {
+ if (!slug) return console.error('Slug is required')
+ if (!token) return console.error('Token is required')
+
+ try {
+ const response = await validateTokenInformation({ slug, token })
+ setTokenInfoLoaded(true)
+ setTokenValidationInfo(response)
+ } catch (error) {
+ setError(error)
+ setTokenInfoLoaded(true)
+ }
+ }
+
+ if (!tokenInfoLoaded && token) {
+ fetchTokenInfo()
+ }
+
+ /**
+ * if params are empty then redirect
+ * user to the homepage of app
+ */
+ // if (!slug && !token) router.push('/')
+ }, [token, router.asPath])
+
+ return (
+ <div
+ className={[
+ 'flex h-full min-h-screen bg-studio',
+ 'w-full flex-col place-items-center',
+ 'items-center justify-center gap-8 px-5',
+ ].join(' ')}
+ >
+ <Link href="/projects" className="flex items-center justify-center gap-4">
+ <img
+ src={`${router.basePath}/img/supabase-logo.svg`}
+ alt="Supabase"
+ className="block h-[24px] cursor-pointer rounded"
+ />
+ </Link>
+ <div
+ className="
+ mx-auto overflow-hidden rounded-md border
+ border-muted bg-alternative text-center shadow
+ md:w-[400px]
+ "
+ >
+ <Loading active={!tokenInfoLoaded}>
+ <Content />
+ </Loading>
+ </div>
+ </div>
+ )
+}
diff --git a/apps/studio/pages/join.tsx b/apps/studio/pages/join.tsx
index 58f63aa217c..984c54902c4 100644
--- a/apps/studio/pages/join.tsx
+++ b/apps/studio/pages/join.tsx
@@ -4,9 +4,19 @@ import { useRouter } from 'next/router'
import { OrganizationInvite } from 'components/interfaces/OrganizationInvite/OrganizationInvite'
import { NextPageWithLayout } from 'types'
import { cn } from 'ui'
+import { useFlag } from 'hooks'
+import { OrganizationInviteOld } from 'components/interfaces/OrganizationInvite/OrganizationInviteOld'
const JoinOrganizationPage: NextPageWithLayout = () => {
const router = useRouter()
+ const isProjectLevelPermissionsEnabled = useFlag('projectLevelPermissions')
+
+ console.log({ isProjectLevelPermissionsEnabled })
+
+ // [Joshen] Can remove this once API changes are deployed to production
+ if (!isProjectLevelPermissionsEnabled) {
+ return <OrganizationInviteOld />
+ }
return (
<div