InviteMemberButton.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. import { zodResolver } from '@hookform/resolvers/zod'
  2. import { PermissionAction } from '@supabase/shared-types/out/constants'
  3. import { useParams } from 'common'
  4. import { UserPlus } from 'lucide-react'
  5. import { useEffect, useState } from 'react'
  6. import { useForm } from 'react-hook-form'
  7. import { toast } from 'sonner'
  8. import {
  9. Button,
  10. Dialog,
  11. DialogContent,
  12. DialogFooter,
  13. DialogHeader,
  14. DialogSection,
  15. DialogSectionSeparator,
  16. DialogTitle,
  17. DialogTrigger,
  18. ExpandingTextArea,
  19. Form,
  20. FormControl,
  21. FormField,
  22. Select,
  23. SelectContent,
  24. SelectGroup,
  25. SelectItem,
  26. SelectTrigger,
  27. SelectValue,
  28. Switch,
  29. } from 'ui'
  30. import { Admonition } from 'ui-patterns/admonition'
  31. import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
  32. import * as z from 'zod'
  33. import {
  34. BatchInvitationResult,
  35. buildProjectPayload,
  36. buildSsoPayload,
  37. categorizeInviteEmails,
  38. emailSchema,
  39. parseEmails,
  40. } from './InviteMemberButton.utils'
  41. import { useGetRolesManagementPermissions } from './TeamSettings.utils'
  42. import { DiscardChangesConfirmationDialog } from '@/components/ui-patterns/Dialogs/DiscardChangesConfirmationDialog'
  43. import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
  44. import { DocsButton } from '@/components/ui/DocsButton'
  45. import { OrganizationProjectSelector } from '@/components/ui/OrganizationProjectSelector'
  46. import { UpgradePlanButton } from '@/components/ui/UpgradePlanButton'
  47. import { useOrganizationCreateInvitationMutation } from '@/data/organization-members/organization-invitation-create-mutation'
  48. import { useOrganizationRolesV2Query } from '@/data/organization-members/organization-roles-query'
  49. import { useOrganizationMembersQuery } from '@/data/organizations/organization-members-query'
  50. import { useOrgSSOConfigQuery } from '@/data/sso/sso-config-query'
  51. import { useHasAccessToProjectLevelPermissions } from '@/data/subscriptions/org-subscription-query'
  52. import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'
  53. import { doPermissionsCheck, useGetPermissions } from '@/hooks/misc/useCheckPermissions'
  54. import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
  55. import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
  56. import { useConfirmOnClose } from '@/hooks/ui/useConfirmOnClose'
  57. import { DOCS_URL } from '@/lib/constants'
  58. import { MANAGED_BY } from '@/lib/constants/infrastructure'
  59. import { useProfile } from '@/lib/profile'
  60. export const InviteMemberButton = () => {
  61. const { slug } = useParams()
  62. const { profile } = useProfile()
  63. const { data: organization } = useSelectedOrganizationQuery()
  64. const { permissions: permissions } = useGetPermissions()
  65. const { organizationMembersCreate: organizationMembersCreationEnabled } = useIsFeatureEnabled([
  66. 'organization_members:create',
  67. ])
  68. const [isOpen, setIsOpen] = useState(false)
  69. const [projectDropdownOpen, setProjectDropdownOpen] = useState(false)
  70. const { data: members } = useOrganizationMembersQuery({ slug })
  71. const { data: allRoles, isSuccess } = useOrganizationRolesV2Query({ slug })
  72. const orgScopedRoles = allRoles?.org_scoped_roles ?? []
  73. const { data: ssoConfig } = useOrgSSOConfigQuery({ orgSlug: slug })
  74. const hasSsoProvider = !!ssoConfig && ssoConfig !== null
  75. const defaultValues = {
  76. email: '',
  77. role: orgScopedRoles.find((role) => role.name === 'Developer')?.id.toString() ?? '',
  78. applyToOrg: true,
  79. projectRef: '',
  80. requireSso: 'auto' as const,
  81. }
  82. const { hasAccess: hasAccessToSso } = useCheckEntitlements('auth.platform.sso')
  83. const hasAccessToProjectLevelPermissions = useHasAccessToProjectLevelPermissions(slug as string)
  84. const userMemberData = members?.find((m) => m.gotrue_id === profile?.gotrue_id)
  85. const hasOrgRole =
  86. (userMemberData?.role_ids ?? []).length === 1 &&
  87. orgScopedRoles.some((r) => r.id === userMemberData?.role_ids[0])
  88. const isStripeProjectsOrg = organization?.managed_by === MANAGED_BY.STRIPE_PROJECTS
  89. const { rolesAddable } = useGetRolesManagementPermissions(
  90. organization?.slug,
  91. orgScopedRoles,
  92. permissions ?? []
  93. )
  94. const canInviteMembers =
  95. hasOrgRole &&
  96. rolesAddable.length > 0 &&
  97. orgScopedRoles.some(({ id: role_id }) =>
  98. doPermissionsCheck(
  99. permissions,
  100. PermissionAction.CREATE,
  101. 'user_invites',
  102. { resource: { role_id } },
  103. organization?.slug
  104. )
  105. )
  106. const { mutateAsync: inviteMemberAsync, isPending: isInviting } =
  107. useOrganizationCreateInvitationMutation()
  108. const FormSchema = z
  109. .object({
  110. email: emailSchema,
  111. role: z.string().min(1, 'Role is required'),
  112. applyToOrg: z.boolean(),
  113. projectRef: z.string(),
  114. requireSso: z.enum(['auto', 'sso', 'non-sso']),
  115. })
  116. .superRefine((data, ctx) => {
  117. if (!data.applyToOrg && !data.projectRef) {
  118. ctx.addIssue({
  119. code: z.ZodIssueCode.custom,
  120. message: 'A project must be selected',
  121. path: ['projectRef'],
  122. })
  123. }
  124. })
  125. const form = useForm<z.infer<typeof FormSchema>>({
  126. mode: 'onSubmit',
  127. reValidateMode: 'onChange',
  128. resolver: zodResolver(FormSchema as any),
  129. defaultValues,
  130. })
  131. const { applyToOrg, projectRef, email } = form.watch()
  132. const emailCount = parseEmails(email ?? '').length
  133. const onInviteMember = async (values: z.infer<typeof FormSchema>) => {
  134. if (!slug) return console.error('Slug is required')
  135. if (profile?.id === undefined) return console.error('Profile ID required')
  136. const emails = parseEmails(values.email).map((e) => e.toLowerCase())
  137. const { alreadyInvited, alreadyMembers, toInvite } = categorizeInviteEmails(
  138. emails,
  139. members ?? []
  140. )
  141. if (alreadyInvited.length > 0) {
  142. toast.error(
  143. alreadyInvited.length === 1
  144. ? `${alreadyInvited[0]} has already been invited to this organization`
  145. : `${alreadyInvited.length} emails have already been invited to this organization`
  146. )
  147. }
  148. if (alreadyMembers.length > 0) {
  149. toast.error(
  150. alreadyMembers.length === 1
  151. ? `${alreadyMembers[0]} is already in this organization`
  152. : `${alreadyMembers.length} emails are already in this organization`
  153. )
  154. }
  155. if (alreadyInvited.length > 0 || alreadyMembers.length > 0) {
  156. if (toInvite.length === 0) return
  157. }
  158. const projectPayload = buildProjectPayload(values.applyToOrg, values.projectRef)
  159. const ssoPayload = buildSsoPayload(values.requireSso)
  160. let result: BatchInvitationResult
  161. try {
  162. result = (await inviteMemberAsync({
  163. slug,
  164. emails: toInvite,
  165. roleId: Number(values.role),
  166. ...projectPayload,
  167. ...ssoPayload,
  168. })) as BatchInvitationResult
  169. } catch {
  170. return // onError callback already showed the toast
  171. }
  172. const { succeeded, failed } = result
  173. if (succeeded.length > 0) {
  174. toast.success(
  175. succeeded.length === 1
  176. ? 'Successfully sent invitation to new member'
  177. : `Successfully sent invitations to ${succeeded.length} new members`
  178. )
  179. }
  180. for (const { email, error } of failed) {
  181. toast.error(`Failed to invite ${email}: ${error}`)
  182. }
  183. if (succeeded.length > 0) {
  184. closeInviteDialog()
  185. }
  186. }
  187. useEffect(() => {
  188. if (isSuccess && isOpen) {
  189. const developerRoleId = orgScopedRoles
  190. .find((role) => role.name === 'Developer')
  191. ?.id.toString()
  192. if (developerRoleId !== undefined && form.getValues('role') === '') {
  193. form.setValue('role', developerRoleId, { shouldDirty: false })
  194. }
  195. }
  196. // eslint-disable-next-line react-hooks/exhaustive-deps
  197. }, [isSuccess, isOpen])
  198. const hasUnsavedChanges = form.formState.isDirty
  199. const closeInviteDialog = () => {
  200. setProjectDropdownOpen(false)
  201. setIsOpen(false)
  202. form.reset(defaultValues)
  203. }
  204. const {
  205. confirmOnClose,
  206. handleOpenChange,
  207. modalProps: discardChangesModalProps,
  208. } = useConfirmOnClose({
  209. checkIsDirty: () => hasUnsavedChanges,
  210. onClose: closeInviteDialog,
  211. })
  212. return (
  213. <Dialog open={isOpen} onOpenChange={handleOpenChange}>
  214. <DialogTrigger asChild>
  215. <ButtonTooltip
  216. type="primary"
  217. disabled={!canInviteMembers}
  218. icon={<UserPlus size={14} />}
  219. className="pointer-events-auto grow md:grow-0"
  220. onClick={() => setIsOpen(true)}
  221. tooltip={{
  222. content: {
  223. side: 'bottom',
  224. text: !organizationMembersCreationEnabled
  225. ? 'Inviting members is currently disabled'
  226. : !canInviteMembers
  227. ? 'You need additional permissions to invite members to this organization'
  228. : undefined,
  229. },
  230. }}
  231. >
  232. Invite members
  233. </ButtonTooltip>
  234. </DialogTrigger>
  235. <DialogContent size="medium">
  236. <DialogHeader>
  237. <DialogTitle>Invite team members</DialogTitle>
  238. </DialogHeader>
  239. <DialogSectionSeparator />
  240. <Admonition
  241. type="note"
  242. showIcon={false}
  243. title="Single Sign-On (SSO) available"
  244. layout={!hasAccessToSso ? 'vertical' : 'horizontal'}
  245. className="rounded-none border-t-0 border-x-0 px-5"
  246. description="Enforce login via your company identity provider for added security and access control. Available on Team plan and above."
  247. actions={
  248. <>
  249. <DocsButton href={`${DOCS_URL}/guides/platform/sso`} />
  250. {!hasAccessToSso && (
  251. <UpgradePlanButton
  252. plan="Team"
  253. source="inviteMemberSSO"
  254. featureProposition="enable Single Sign-on (SSO)"
  255. />
  256. )}
  257. </>
  258. }
  259. />
  260. <Form {...form}>
  261. <form
  262. id="organization-invitation"
  263. className="flex flex-col gap-y-4"
  264. onSubmit={form.handleSubmit(onInviteMember)}
  265. >
  266. <DialogSection className="flex flex-col gap-y-4 pb-2">
  267. <FormField
  268. name="role"
  269. control={form.control}
  270. render={({ field }) => (
  271. <FormItemLayout label="Role">
  272. <FormControl>
  273. <Select value={field.value} onValueChange={field.onChange}>
  274. <SelectTrigger className="text-sm capitalize">
  275. {orgScopedRoles.find((role) => role.id === Number(field.value))?.name ??
  276. 'Unknown'}
  277. </SelectTrigger>
  278. <SelectContent>
  279. <SelectGroup>
  280. {orgScopedRoles.map((role) => {
  281. const canAssignRole = rolesAddable.includes(role.id)
  282. const isOwnerRole = role.name === 'Owner'
  283. const disabledForStripe = isStripeProjectsOrg && isOwnerRole
  284. const disabled = !canAssignRole || disabledForStripe
  285. const disabledReason = disabledForStripe
  286. ? 'Cannot be assigned in Stripe Projects organizations'
  287. : !canAssignRole
  288. ? 'Additional permissions required to assign role'
  289. : undefined
  290. return (
  291. <SelectItem
  292. key={role.id}
  293. value={role.id.toString()}
  294. className="text-sm"
  295. disabled={disabled}
  296. >
  297. <div className="flex flex-col gap-0.5">
  298. <span>{role.name}</span>
  299. {disabledReason && (
  300. <span className="text-xs text-foreground-lighter">
  301. {disabledReason}
  302. </span>
  303. )}
  304. </div>
  305. </SelectItem>
  306. )
  307. })}
  308. </SelectGroup>
  309. </SelectContent>
  310. </Select>
  311. </FormControl>
  312. </FormItemLayout>
  313. )}
  314. />
  315. {hasSsoProvider && (
  316. <FormField
  317. name="requireSso"
  318. control={form.control}
  319. render={({ field }) => (
  320. <FormItemLayout
  321. label="Invitation type"
  322. description="Choose how the invitee should authenticate"
  323. >
  324. <FormControl>
  325. <Select value={field.value} onValueChange={field.onChange}>
  326. <SelectTrigger>
  327. <SelectValue placeholder="Automatic (based on your account)" />
  328. </SelectTrigger>
  329. <SelectContent>
  330. <SelectGroup>
  331. <SelectItem value="auto">
  332. Automatic (based on your account)
  333. </SelectItem>
  334. <SelectItem value="sso">Require SSO authentication</SelectItem>
  335. <SelectItem value="non-sso">Email/password authentication</SelectItem>
  336. </SelectGroup>
  337. </SelectContent>
  338. </Select>
  339. </FormControl>
  340. </FormItemLayout>
  341. )}
  342. />
  343. )}
  344. {hasAccessToProjectLevelPermissions && (
  345. <FormField
  346. name="applyToOrg"
  347. control={form.control}
  348. render={({ field }) => (
  349. <FormItemLayout layout="flex" label="Grant this role on all projects">
  350. <FormControl>
  351. <Switch checked={field.value} onCheckedChange={field.onChange} />
  352. </FormControl>
  353. </FormItemLayout>
  354. )}
  355. />
  356. )}
  357. {!applyToOrg && (
  358. <FormField
  359. name="projectRef"
  360. control={form.control}
  361. render={({ field }) => (
  362. <FormItemLayout
  363. label="Select a project"
  364. description="Project access can be adjusted after the user joins"
  365. >
  366. <FormControl>
  367. <OrganizationProjectSelector
  368. fetchOnMount
  369. sameWidthAsTrigger
  370. checkPosition="left"
  371. selectedRef={projectRef}
  372. open={projectDropdownOpen}
  373. setOpen={setProjectDropdownOpen}
  374. searchPlaceholder="Search project..."
  375. onSelect={(project) => field.onChange(project.ref)}
  376. onInitialLoad={(projects) => field.onChange(projects[0]?.ref ?? '')}
  377. />
  378. </FormControl>
  379. </FormItemLayout>
  380. )}
  381. />
  382. )}
  383. <FormField
  384. name="email"
  385. control={form.control}
  386. render={({ field }) => (
  387. <FormItemLayout label="Email addresses">
  388. <FormControl>
  389. <ExpandingTextArea
  390. autoFocus
  391. {...field}
  392. autoComplete="off"
  393. disabled={isInviting}
  394. placeholder="name@example.com, name2@example.com, ..."
  395. className="max-h-48"
  396. data-1p-ignore
  397. data-lpignore="true"
  398. data-form-type="other"
  399. data-bwignore
  400. />
  401. </FormControl>
  402. </FormItemLayout>
  403. )}
  404. />
  405. </DialogSection>
  406. <DialogFooter className="justify-between!">
  407. <Button type="default" onClick={confirmOnClose}>
  408. Cancel
  409. </Button>
  410. <Button type="primary" htmlType="submit" loading={isInviting}>
  411. {emailCount >= 2 ? 'Send invitations' : 'Send invitation'}
  412. </Button>
  413. </DialogFooter>
  414. </form>
  415. </Form>
  416. </DialogContent>
  417. <DiscardChangesConfirmationDialog
  418. {...discardChangesModalProps}
  419. description="Are you sure you want to discard your changes? Your invitation will not be sent."
  420. />
  421. </Dialog>
  422. )
  423. }