Skip to content

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

Chore/swap use check permissions with use async check project permissions part 7 (#38581)

Joshen Lim7650926b7762
diff --git a/apps/studio/components/interfaces/Billing/Payment/PaymentMethods/CurrentPaymentMethod.tsx b/apps/studio/components/interfaces/Billing/Payment/PaymentMethods/CurrentPaymentMethod.tsx
index 557f8ee2f31..31480f91c49 100644
--- a/apps/studio/components/interfaces/Billing/Payment/PaymentMethods/CurrentPaymentMethod.tsx
+++ b/apps/studio/components/interfaces/Billing/Payment/PaymentMethods/CurrentPaymentMethod.tsx
@@ -1,12 +1,12 @@
+import { PermissionAction, SupportCategories } from '@supabase/shared-types/out/constants'
import { CreditCardIcon } from 'lucide-react'
import Link from 'next/link'
-import { PermissionAction, SupportCategories } from '@supabase/shared-types/out/constants'
import { useParams } from 'common'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { useOrganizationPaymentMethodsQuery } from 'data/organizations/organization-payment-methods-query'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { Button } from 'ui'
import CreditCard from './CreditCard'
@@ -31,7 +31,7 @@ const CurrentPaymentMethod = () => {
const defaultPaymentMethod = paymentMethods?.data.find((pm) => pm.is_default)
- const canReadPaymentMethods = useCheckPermissions(
+ const { can: canReadPaymentMethods } = useAsyncCheckProjectPermissions(
PermissionAction.BILLING_READ,
'stripe.payment_methods'
)
diff --git a/apps/studio/components/interfaces/Billing/Payment/PaymentMethods/PaymentMethods.tsx b/apps/studio/components/interfaces/Billing/Payment/PaymentMethods/PaymentMethods.tsx
index b850afc7d13..95d7d1b1076 100644
--- a/apps/studio/components/interfaces/Billing/Payment/PaymentMethods/PaymentMethods.tsx
+++ b/apps/studio/components/interfaces/Billing/Payment/PaymentMethods/PaymentMethods.tsx
@@ -19,17 +19,14 @@ import PartnerManagedResource from 'components/ui/PartnerManagedResource'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { useOrganizationPaymentMethodsQuery } from 'data/organizations/organization-payment-methods-query'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
-import {
- useAsyncCheckProjectPermissions,
- useCheckPermissions,
-} from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
+import { MANAGED_BY } from 'lib/constants/infrastructure'
import { getURL } from 'lib/helpers'
import { Alert, Button } from 'ui'
import ChangePaymentMethodModal from './ChangePaymentMethodModal'
import CreditCard from './CreditCard'
import DeletePaymentMethodModal from './DeletePaymentMethodModal'
-import { MANAGED_BY } from 'lib/constants/infrastructure'
const PaymentMethods = () => {
const { slug } = useParams()
@@ -47,9 +44,9 @@ const PaymentMethods = () => {
isSuccess,
} = useOrganizationPaymentMethodsQuery({ slug })
- const { isSuccess: isPermissionsLoaded, can: canReadPaymentMethods } =
+ const { can: canReadPaymentMethods, isSuccess: isPermissionsLoaded } =
useAsyncCheckProjectPermissions(PermissionAction.BILLING_READ, 'stripe.payment_methods')
- const canUpdatePaymentMethods = useCheckPermissions(
+ const { can: canUpdatePaymentMethods } = useAsyncCheckProjectPermissions(
PermissionAction.BILLING_WRITE,
'stripe.payment_methods'
)
diff --git a/apps/studio/components/interfaces/Database/Hooks/HooksList/HooksList.tsx b/apps/studio/components/interfaces/Database/Hooks/HooksList/HooksList.tsx
index 7340883f745..a53ac137264 100644
--- a/apps/studio/components/interfaces/Database/Hooks/HooksList/HooksList.tsx
+++ b/apps/studio/components/interfaces/Database/Hooks/HooksList/HooksList.tsx
@@ -10,10 +10,7 @@ import { DocsButton } from 'components/ui/DocsButton'
import NoSearchResults from 'components/ui/NoSearchResults'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import { useDatabaseHooksQuery } from 'data/database-triggers/database-triggers-query'
-import {
- useAsyncCheckProjectPermissions,
- usePermissionsLoaded,
-} from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { noop } from 'lib/void'
import { Input } from 'ui'
@@ -49,11 +46,8 @@ export const HooksList = ({
)
const filteredHookSchemas = lodashMap(uniqBy(filteredHooks, 'schema'), 'schema')
- const { can: canCreateWebhooks } = useAsyncCheckProjectPermissions(
- PermissionAction.TENANT_SQL_ADMIN_WRITE,
- 'triggers'
- )
- const isPermissionsLoaded = usePermissionsLoaded()
+ const { can: canCreateWebhooks, isSuccess: isPermissionsLoaded } =
+ useAsyncCheckProjectPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'triggers')
return (
<div className="w-full space-y-4">
diff --git a/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx b/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx
index d9265a582ce..f6e1fa8bc17 100644
--- a/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx
+++ b/apps/studio/components/interfaces/Organization/AuditLogs/AuditLogs.tsx
@@ -8,7 +8,7 @@ import { useEffect, useState } from 'react'
import { LogDetailsPanel } from 'components/interfaces/AuditLogs'
import { LogsDatePicker } from 'components/interfaces/Settings/Logs/Logs.DatePickers'
-import { ScaffoldContainerLegacy } from 'components/layouts/Scaffold'
+import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'
import Table from 'components/to-be-cleaned/Table'
import AlertError from 'components/ui/AlertError'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
@@ -23,7 +23,7 @@ import {
import { useOrganizationMembersQuery } from 'data/organizations/organization-members-query'
import { useOrganizationsQuery } from 'data/organizations/organizations-query'
import { useProjectsQuery } from 'data/projects/projects-query'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import {
AlertDescription_Shadcn_,
AlertTitle_Shadcn_,
@@ -32,13 +32,15 @@ import {
WarningIcon,
} from 'ui'
+const logsUpgradeError = 'upgrade to Team or Enterprise Plan to access audit logs.'
+
// [Joshen considerations]
// - Maybe fix the height of the table to the remaining height of the viewport, so that the search input is always visible
// - We'll need pagination as well if the audit logs get too large, but that needs to be implemented on the API side first if possible
// - I've hidden time input in the date picker for now cause the time support in the component is a bit iffy, need to investigate
// - Maybe a rule to follow from here is just everytime we call dayjs, use UTC(), one TZ to rule them all
-const AuditLogs = () => {
+export const AuditLogs = () => {
const { slug } = useParams()
const currentTime = dayjs().utc().set('millisecond', 0)
const [dateSortDesc, setDateSortDesc] = useState(true)
@@ -52,7 +54,8 @@ const AuditLogs = () => {
projects: [], // project_ref[]
})
- const canReadAuditLogs = useCheckPermissions(PermissionAction.READ, 'notifications')
+ const { can: canReadAuditLogs, isLoading: isLoadingPermissions } =
+ useAsyncCheckProjectPermissions(PermissionAction.READ, 'notifications')
const { data: projectsData } = useProjectsQuery()
const projects = projectsData?.projects ?? []
@@ -69,13 +72,15 @@ const AuditLogs = () => {
{
enabled: canReadAuditLogs,
retry: false,
+ refetchOnWindowFocus: (query) => {
+ return !query.state.error?.message.endsWith(logsUpgradeError)
+ },
}
)
const activeMembers = (members ?? []).filter((x) => !x.invited_at)
const roles = [...(rolesData?.org_scoped_roles ?? []), ...(rolesData?.project_scoped_roles ?? [])]
- const retentionPeriod = data?.retention_period ?? 0
const logs = data?.result ?? []
const sortedLogs = logs
?.sort((a, b) =>
@@ -99,8 +104,6 @@ const AuditLogs = () => {
})
const currentOrganization = organizations?.find((o) => o.slug === slug)
- const minDate = dayjs().subtract(retentionPeriod, 'days')
- const maxDate = dayjs()
// This feature depends on the subscription tier of the user. Free user can view logs up to 1 day
// in the past. The API limits the logs to maximum of 1 day and 5 minutes so when the page is
@@ -119,300 +122,296 @@ const AuditLogs = () => {
return () => clearInterval(interval)
}, [dateRange.from, dateRange.to])
- if (!canReadAuditLogs) {
- return (
- <ScaffoldContainerLegacy>
- <NoPermission resourceText="view organization audit logs" />
- </ScaffoldContainerLegacy>
- )
- }
-
return (
<>
- <ScaffoldContainerLegacy>
- <div className="space-y-4 flex flex-col">
- <div className="flex items-center justify-between">
- <div className="flex items-center space-x-2">
- <p className="text-xs prose">Filter by</p>
- <FilterPopover
- name="Users"
- options={activeMembers}
- labelKey="username"
- valueKey="gotrue_id"
- activeOptions={filters.users}
- onSaveFilters={(values) => setFilters({ ...filters, users: values })}
- />
- <FilterPopover
- name="Projects"
- options={
- projects?.filter((p) => p.organization_id === currentOrganization?.id) ?? []
- }
- labelKey="name"
- valueKey="ref"
- activeOptions={filters.projects}
- onSaveFilters={(values) => setFilters({ ...filters, projects: values })}
- />
- <LogsDatePicker
- hideWarnings
- value={dateRange}
- onSubmit={(value) => setDateRange(value)}
- helpers={[
- {
- text: 'Last 1 hour',
- calcFrom: () => dayjs().subtract(1, 'hour').toISOString(),
- calcTo: () => dayjs().toISOString(),
- },
- {
- text: 'Last 3 hours',
- calcFrom: () => dayjs().subtract(3, 'hour').toISOString(),
- calcTo: () => dayjs().toISOString(),
- },
+ <ScaffoldContainer>
+ <ScaffoldSection isFullWidth>
+ <div className="space-y-4 flex flex-col">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center space-x-2">
+ <p className="text-xs prose">Filter by</p>
+ <FilterPopover
+ name="Users"
+ options={activeMembers}
+ labelKey="username"
+ valueKey="gotrue_id"
+ activeOptions={filters.users}
+ onSaveFilters={(values) => setFilters({ ...filters, users: values })}
+ />
+ <FilterPopover
+ name="Projects"
+ options={
+ projects?.filter((p) => p.organization_id === currentOrganization?.id) ?? []
+ }
+ labelKey="name"
+ valueKey="ref"
+ activeOptions={filters.projects}
+ onSaveFilters={(values) => setFilters({ ...filters, projects: values })}
+ />
+ <LogsDatePicker
+ hideWarnings
+ value={dateRange}
+ onSubmit={(value) => setDateRange(value)}
+ helpers={[
+ {
+ text: 'Last 1 hour',
+ calcFrom: () => dayjs().subtract(1, 'hour').toISOString(),
+ calcTo: () => dayjs().toISOString(),
+ },
+ {
+ text: 'Last 3 hours',
+ calcFrom: () => dayjs().subtract(3, 'hour').toISOString(),
+ calcTo: () => dayjs().toISOString(),
+ },
- {
- text: 'Last 6 hours',
- calcFrom: () => dayjs().subtract(6, 'hour').toISOString(),
- calcTo: () => dayjs().toISOString(),
- },
- {
- text: 'Last 12 hours',
- calcFrom: () => dayjs().subtract(12, 'hour').toISOString(),
- calcTo: () => dayjs().toISOString(),
- },
- {
- text: 'Last 24 hours',
- calcFrom: () => dayjs().subtract(1, 'day').toISOString(),
- calcTo: () => dayjs().toISOString(),
- },
- ]}
- />
- {isSuccess && (
- <>
- <div className="h-[20px] border-r border-strong !ml-4 !mr-2" />
- <p className="prose text-xs">Viewing {sortedLogs.length} logs in total</p>
- </>
- )}
+ {
+ text: 'Last 6 hours',
+ calcFrom: () => dayjs().subtract(6, 'hour').toISOString(),
+ calcTo: () => dayjs().toISOString(),
+ },
+ {
+ text: 'Last 12 hours',
+ calcFrom: () => dayjs().subtract(12, 'hour').toISOString(),
+ calcTo: () => dayjs().toISOString(),
+ },
+ {
+ text: 'Last 24 hours',
+ calcFrom: () => dayjs().subtract(1, 'day').toISOString(),
+ calcTo: () => dayjs().toISOString(),
+ },
+ ]}
+ />
+ {isSuccess && (
+ <>
+ <div className="h-[20px] border-r border-strong !ml-4 !mr-2" />
+ <p className="prose text-xs">Viewing {sortedLogs.length} logs in total</p>
+ </>
+ )}
+ </div>
+ <Button
+ type="default"
+ disabled={isLoading || isRefetching}
+ icon={<RefreshCw className={isRefetching ? 'animate-spin' : ''} />}
+ onClick={() => refetch()}
+ >
+ {isRefetching ? 'Refreshing' : 'Refresh'}
+ </Button>
</div>
- <Button
- type="default"
- disabled={isLoading || isRefetching}
- icon={<RefreshCw className={isRefetching ? 'animate-spin' : ''} />}
- onClick={() => refetch()}
- >
- {isRefetching ? 'Refreshing' : 'Refresh'}
- </Button>
- </div>
- {isLoading && (
- <div className="space-y-2">
- <ShimmeringLoader />
- <ShimmeringLoader className="w-3/4" />
- <ShimmeringLoader className="w-1/2" />
- </div>
- )}
+ {isLoading || isLoadingPermissions ? (
+ <div className="space-y-2">
+ <ShimmeringLoader />
+ <ShimmeringLoader className="w-3/4" />
+ <ShimmeringLoader className="w-1/2" />
+ </div>
+ ) : !canReadAuditLogs ? (
+ <NoPermission resourceText="view organization audit logs" />
+ ) : null}
- {isError ? (
- error.message.endsWith('upgrade to Team or Enterprise Plan to access audit logs.') ? (
- <Alert_Shadcn_
- variant="default"
- title="Organization Audit Logs are not available on Free or Pro plans"
- >
- <WarningIcon />
- <div className="flex flex-col md:flex-row pt-1 gap-4">
- <div className="grow">
- <AlertTitle_Shadcn_>
- Organization Audit Logs are not available on Free or Pro plans
- </AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_ className="flex flex-row justify-between gap-3">
- <p>
- Upgrade to Team or Enterprise to view up to 28 days of Audit Logs for your
- organization.
- </p>
- </AlertDescription_Shadcn_>
- </div>
+ {isError ? (
+ error.message.endsWith(logsUpgradeError) ? (
+ <Alert_Shadcn_
+ variant="default"
+ title="Organization Audit Logs are not available on Free or Pro plans"
+ >
+ <WarningIcon />
+ <div className="flex flex-col md:flex-row pt-1 gap-4">
+ <div className="grow">
+ <AlertTitle_Shadcn_>
+ Organization Audit Logs are not available on Free or Pro plans
+ </AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_ className="flex flex-row justify-between gap-3">
+ <p>
+ Upgrade to Team or Enterprise to view up to 28 days of Audit Logs for your
+ organization.
+ </p>
+ </AlertDescription_Shadcn_>
+ </div>
- <div className="flex items-center">
- <Button type="primary" asChild>
- <Link href={`/org/${slug}/billing?panel=subscriptionPlan&source=auditLogs`}>
- Upgrade subscription
- </Link>
- </Button>
+ <div className="flex items-center">
+ <Button type="primary" asChild>
+ <Link href={`/org/${slug}/billing?panel=subscriptionPlan&source=auditLogs`}>
+ Upgrade subscription
+ </Link>
+ </Button>
+ </div>
</div>
- </div>
- </Alert_Shadcn_>
- ) : error.message.includes('range exceeded') ? (
- <Alert_Shadcn_ variant="destructive" title="Date range too large">
- <WarningIcon />
- <AlertTitle_Shadcn_>Date range too large</AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_>
- The selected date range exceeds the maximum allowed period. Please select a
- smaller time range.
- </AlertDescription_Shadcn_>
- </Alert_Shadcn_>
- ) : (
- <AlertError error={error} subject="Failed to retrieve audit logs" />
- )
- ) : null}
-
- {isSuccess && (
- <>
- {logs.length === 0 ? (
- <div className="bg-surface-100 border rounded p-4 flex items-center justify-between">
- <p className="prose text-sm">
- Your organization does not have any audit logs available yet
- </p>
- </div>
- ) : logs.length > 0 && sortedLogs.length === 0 ? (
- <div className="bg-surface-100 border rounded p-4 flex items-center justify-between">
- <p className="prose text-sm">No audit logs found based on the filters applied</p>
- </div>
+ </Alert_Shadcn_>
+ ) : error.message.includes('range exceeded') ? (
+ <Alert_Shadcn_ variant="destructive" title="Date range too large">
+ <WarningIcon />
+ <AlertTitle_Shadcn_>Date range too large</AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>
+ The selected date range exceeds the maximum allowed period. Please select a
+ smaller time range.
+ </AlertDescription_Shadcn_>
+ </Alert_Shadcn_>
) : (
- <Table
- head={[
- <Table.th key="user" className="py-2">
- User
- </Table.th>,
- <Table.th key="action" className="py-2">
- Action
- </Table.th>,
- <Table.th key="target" className="py-2">
- Target
- </Table.th>,
- <Table.th key="date" className="py-2">
- <div className="flex items-center space-x-2">
- <p>Date</p>
+ <AlertError error={error} subject="Failed to retrieve audit logs" />
+ )
+ ) : null}
- <ButtonTooltip
- type="text"
- className="px-1"
- icon={
- dateSortDesc ? (
- <ArrowDown strokeWidth={1.5} size={14} />
- ) : (
- <ArrowUp strokeWidth={1.5} size={14} />
- )
- }
- onClick={() => setDateSortDesc(!dateSortDesc)}
- tooltip={{
- content: {
- side: 'bottom',
- text: dateSortDesc ? 'Sort latest first' : 'Sort earliest first',
- },
- }}
- />
- </div>
- </Table.th>,
- <Table.th key="actions" className="py-2"></Table.th>,
- ]}
- body={
- sortedLogs?.map((log) => {
- const user = (members ?? []).find(
- (member) => member.gotrue_id === log.actor.id
- )
- const role = roles.find((role) => user?.role_ids?.[0] === role.id)
- const project = projects?.find(
- (project) => project.ref === log.target.metadata.project_ref
- )
- const organization = organizations?.find(
- (org) => org.slug === log.target.metadata.org_slug
- )
+ {isSuccess && (
+ <>
+ {logs.length === 0 ? (
+ <div className="bg-surface-100 border rounded p-4 flex items-center justify-between">
+ <p className="prose text-sm">
+ Your organization does not have any audit logs available yet
+ </p>
+ </div>
+ ) : logs.length > 0 && sortedLogs.length === 0 ? (
+ <div className="bg-surface-100 border rounded p-4 flex items-center justify-between">
+ <p className="prose text-sm">
+ No audit logs found based on the filters applied
+ </p>
+ </div>
+ ) : (
+ <Table
+ head={[
+ <Table.th key="user" className="py-2">
+ User
+ </Table.th>,
+ <Table.th key="action" className="py-2">
+ Action
+ </Table.th>,
+ <Table.th key="target" className="py-2">
+ Target
+ </Table.th>,
+ <Table.th key="date" className="py-2">
+ <div className="flex items-center space-x-2">
+ <p>Date</p>
- const hasStatusCode = log.action.metadata[0]?.status !== undefined
- const userIcon =
- user === undefined ? (
- <div className="flex h-[30px] w-[30px] items-center justify-center border-2 rounded-full border-strong">
- <p>?</p>
- </div>
- ) : user?.invited_id || user?.username === user?.primary_email ? (
- <div className="flex h-[30px] w-[30px] items-center justify-center border-2 rounded-full border-strong">
- <User size={18} strokeWidth={2} />
- </div>
- ) : (
- <Image
- alt={user?.username}
- src={`https://github.com/${user?.username ?? ''}.png?size=80`}
- width="30"
- height="30"
- className="border rounded-full"
+ <ButtonTooltip
+ type="text"
+ className="px-1"
+ icon={
+ dateSortDesc ? (
+ <ArrowDown strokeWidth={1.5} size={14} />
+ ) : (
+ <ArrowUp strokeWidth={1.5} size={14} />
+ )
+ }
+ onClick={() => setDateSortDesc(!dateSortDesc)}
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text: dateSortDesc ? 'Sort latest first' : 'Sort earliest first',
+ },
+ }}
/>
+ </div>
+ </Table.th>,
+ <Table.th key="actions" className="py-2"></Table.th>,
+ ]}
+ body={
+ sortedLogs?.map((log) => {
+ const user = (members ?? []).find(
+ (member) => member.gotrue_id === log.actor.id
)
+ const role = roles.find((role) => user?.role_ids?.[0] === role.id)
+ const project = projects?.find(
+ (project) => project.ref === log.target.metadata.project_ref
+ )
+ const organization = organizations?.find(
+ (org) => org.slug === log.target.metadata.org_slug
+ )
+
+ const hasStatusCode = log.action.metadata[0]?.status !== undefined
+ const userIcon =
+ user === undefined ? (
+ <div className="flex h-[30px] w-[30px] items-center justify-center border-2 rounded-full border-strong">
+ <p>?</p>
+ </div>
+ ) : user?.invited_id || user?.username === user?.primary_email ? (
+ <div className="flex h-[30px] w-[30px] items-center justify-center border-2 rounded-full border-strong">
+ <User size={18} strokeWidth={2} />
+ </div>
+ ) : (
+ <Image
+ alt={user?.username}
+ src={`https://github.com/${user?.username ?? ''}.png?size=80`}
+ width="30"
+ height="30"
+ className="border rounded-full"
+ />
+ )
- return (
- <Table.tr
- key={log.occurred_at}
- onClick={() => setSelectedLog(log)}
- className="cursor-pointer hover:!bg-alternative transition duration-100"
- >
- <Table.td>
- <div className="flex items-center space-x-4">
- <div>{userIcon}</div>
- <div>
- <p className="text-foreground-light">{user?.username ?? '-'}</p>
- {role && (
- <p className="mt-0.5 text-xs text-foreground-light">
- {role?.name}
+ return (
+ <Table.tr
+ key={log.occurred_at}
+ onClick={() => setSelectedLog(log)}
+ className="cursor-pointer hover:!bg-alternative transition duration-100"
+ >
+ <Table.td>
+ <div className="flex items-center space-x-4">
+ <div>{userIcon}</div>
+ <div>
+ <p className="text-foreground-light">{user?.username ?? '-'}</p>
+ {role && (
+ <p className="mt-0.5 text-xs text-foreground-light">
+ {role?.name}
+ </p>
+ )}
+ </div>
+ </div>
+ </Table.td>
+ <Table.td className="max-w-[250px]">
+ <div className="flex items-center space-x-2">
+ {hasStatusCode && (
+ <p className="bg-surface-200 rounded px-1 flex items-center justify-center text-xs font-mono border">
+ {log.action.metadata[0].status}
</p>
)}
- </div>
- </div>
- </Table.td>
- <Table.td className="max-w-[250px]">
- <div className="flex items-center space-x-2">
- {hasStatusCode && (
- <p className="bg-surface-200 rounded px-1 flex items-center justify-center text-xs font-mono border">
- {log.action.metadata[0].status}
+ <p className="truncate" title={log.action.name}>
+ {log.action.name}
</p>
- )}
- <p className="truncate" title={log.action.name}>
- {log.action.name}
+ </div>
+ </Table.td>
+ <Table.td>
+ <p
+ className="text-foreground-light max-w-[230px] truncate"
+ title={project?.name ?? organization?.name ?? '-'}
+ >
+ {project?.name
+ ? 'Project: '
+ : organization?.name
+ ? 'Organization: '
+ : null}
+ {project?.name ?? organization?.name ?? 'Unknown'}
</p>
- </div>
- </Table.td>
- <Table.td>
- <p
- className="text-foreground-light max-w-[230px] truncate"
- title={project?.name ?? organization?.name ?? '-'}
- >
- {project?.name
- ? 'Project: '
- : organization?.name
- ? 'Organization: '
- : null}
- {project?.name ?? organization?.name ?? 'Unknown'}
- </p>
- <p
- className="text-foreground-light text-xs mt-0.5 truncate"
- title={
- log.target.metadata.project_ref ?? log.target.metadata.org_slug
- }
- >
- {log.target.metadata.project_ref
- ? 'Ref: '
- : log.target.metadata.org_slug
- ? 'Slug: '
- : null}
- {log.target.metadata.project_ref ?? log.target.metadata.org_slug}
- </p>
- </Table.td>
- <Table.td>
- {dayjs(log.occurred_at).format('DD MMM YYYY, HH:mm:ss')}
- </Table.td>
- <Table.td align="right">
- <Button type="default">View details</Button>
- </Table.td>
- </Table.tr>
- )
- }) ?? []
- }
- />
- )}
- </>
- )}
- </div>
- </ScaffoldContainerLegacy>
+ <p
+ className="text-foreground-light text-xs mt-0.5 truncate"
+ title={
+ log.target.metadata.project_ref ?? log.target.metadata.org_slug
+ }
+ >
+ {log.target.metadata.project_ref
+ ? 'Ref: '
+ : log.target.metadata.org_slug
+ ? 'Slug: '
+ : null}
+ {log.target.metadata.project_ref ?? log.target.metadata.org_slug}
+ </p>
+ </Table.td>
+ <Table.td>
+ {dayjs(log.occurred_at).format('DD MMM YYYY, HH:mm:ss')}
+ </Table.td>
+ <Table.td align="right">
+ <Button type="default">View details</Button>
+ </Table.td>
+ </Table.tr>
+ )
+ }) ?? []
+ }
+ />
+ )}
+ </>
+ )}
+ </div>
+ </ScaffoldSection>
+ </ScaffoldContainer>
<LogDetailsPanel selectedLog={selectedLog} onClose={() => setSelectedLog(undefined)} />
</>
)
}
-
-export default AuditLogs
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerData.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerData.tsx
index 0431d6c4cd0..073177cae61 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerData.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingCustomerData/BillingCustomerData.tsx
@@ -16,10 +16,7 @@ import { useOrganizationCustomerProfileQuery } from 'data/organizations/organiza
import { useOrganizationCustomerProfileUpdateMutation } from 'data/organizations/organization-customer-profile-update-mutation'
import { useOrganizationTaxIdQuery } from 'data/organizations/organization-tax-id-query'
import { useOrganizationTaxIdUpdateMutation } from 'data/organizations/organization-tax-id-update-mutation'
-import {
- useAsyncCheckProjectPermissions,
- useCheckPermissions,
-} from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { Button, Card, CardFooter, Form_Shadcn_ as Form } from 'ui'
import {
@@ -33,9 +30,9 @@ export const BillingCustomerData = () => {
const { slug } = useParams()
const { data: selectedOrganization } = useSelectedOrganizationQuery()
- const { isSuccess: isPermissionsLoaded, can: canReadBillingCustomerData } =
+ const { can: canReadBillingCustomerData, isSuccess: isPermissionsLoaded } =
useAsyncCheckProjectPermissions(PermissionAction.BILLING_READ, 'stripe.customer')
- const canUpdateBillingCustomerData = useCheckPermissions(
+ const { can: canUpdateBillingCustomerData } = useAsyncCheckProjectPermissions(
PermissionAction.BILLING_WRITE,
'stripe.customer'
)
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/BillingEmail.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/BillingEmail.tsx
index 9584fd770d9..2864351ff57 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/BillingEmail.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/BillingEmail.tsx
@@ -18,10 +18,7 @@ import { FormSection, FormSectionContent } from 'components/ui/Forms/FormSection
import NoPermission from 'components/ui/NoPermission'
import { useOrganizationCustomerProfileQuery } from 'data/organizations/organization-customer-profile-query'
import { useOrganizationUpdateMutation } from 'data/organizations/organization-update-mutation'
-import {
- useAsyncCheckProjectPermissions,
- useCheckPermissions,
-} from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { FormMessage_Shadcn_, Input_Shadcn_ } from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
@@ -45,9 +42,12 @@ const BillingEmail = () => {
const { name, billing_email } = selectedOrganization ?? {}
- const canUpdateOrganization = useCheckPermissions(PermissionAction.UPDATE, 'organizations')
- const { isSuccess: isPermissionsLoaded, can: canReadBillingEmail } =
+ const { can: canReadBillingEmail, isSuccess: isPermissionsLoaded } =
useAsyncCheckProjectPermissions(PermissionAction.BILLING_READ, 'stripe.subscriptions')
+ const { can: canUpdateOrganization } = useAsyncCheckProjectPermissions(
+ PermissionAction.UPDATE,
+ 'organizations'
+ )
const { data: billingCustomer, isLoading: loadingBillingCustomer } =
useOrganizationCustomerProfileQuery({ slug }, { enabled: canReadBillingEmail })
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/SpendCapSidePanel.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/SpendCapSidePanel.tsx
index bbf1025d13a..63588dedf5f 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/SpendCapSidePanel.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/CostControl/SpendCapSidePanel.tsx
@@ -9,12 +9,12 @@ import { useParams } from 'common'
import Table from 'components/to-be-cleaned/Table'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
import { useOrgSubscriptionUpdateMutation } from 'data/subscriptions/org-subscription-update-mutation'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { BASE_PATH, PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
+import { ChevronRight, ExternalLink } from 'lucide-react'
import { pricing } from 'shared-data/pricing'
import { useOrgSettingsPageStateSnapshot } from 'state/organization-settings'
import { Alert, Button, Collapsible, SidePanel, cn } from 'ui'
-import { ExternalLink, ChevronRight } from 'lucide-react'
const SPEND_CAP_OPTIONS: {
name: string
@@ -43,7 +43,7 @@ const SpendCapSidePanel = () => {
const [showUsageCosts, setShowUsageCosts] = useState(false)
const [selectedOption, setSelectedOption] = useState<'on' | 'off'>()
- const canUpdateSpendCap = useCheckPermissions(
+ const { can: canUpdateSpendCap } = useAsyncCheckProjectPermissions(
PermissionAction.BILLING_WRITE,
'stripe.subscriptions'
)
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/CreditTopUp.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/CreditTopUp.tsx
index 233e7f97047..094f62f63aa 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/CreditTopUp.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/CreditTopUp.tsx
@@ -12,10 +12,12 @@ import { SubmitHandler, useForm } from 'react-hook-form'
import { toast } from 'sonner'
import { z } from 'zod'
+import { getStripeElementsAppearanceOptions } from 'components/interfaces/Billing/Payment/Payment.utils'
+import { PaymentConfirmation } from 'components/interfaces/Billing/Payment/PaymentConfirmation'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { useOrganizationCreditTopUpMutation } from 'data/organizations/organization-credit-top-up-mutation'
import { subscriptionKeys } from 'data/subscriptions/keys'
-import { useCheckPermissions, usePermissionsLoaded } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { STRIPE_PUBLIC_KEY } from 'lib/constants'
import {
Alert_Shadcn_,
@@ -36,10 +38,8 @@ import {
Input_Shadcn_,
} from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
-import PaymentMethodSelection from './Subscription/PaymentMethodSelection'
-import { PaymentConfirmation } from 'components/interfaces/Billing/Payment/PaymentConfirmation'
-import { getStripeElementsAppearanceOptions } from 'components/interfaces/Billing/Payment/Payment.utils'
import type { PaymentMethodElementRef } from '../../Billing/Payment/PaymentMethods/NewPaymentMethodElement'
+import PaymentMethodSelection from './Subscription/PaymentMethodSelection'
const stripePromise = loadStripe(STRIPE_PUBLIC_KEY)
@@ -63,11 +63,10 @@ export const CreditTopUp = ({ slug }: { slug: string | undefined }) => {
createPaymentMethod: PaymentMethodElementRef['createPaymentMethod']
}>(null)
- const canTopUpCredits = useCheckPermissions(
+ const { can: canTopUpCredits, isSuccess: isPermissionsLoaded } = useAsyncCheckProjectPermissions(
PermissionAction.BILLING_WRITE,
'stripe.subscriptions'
)
- const isPermissionsLoaded = usePermissionsLoaded()
const {
mutateAsync: topUpCredits,
diff --git a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx
index d084514da4a..002dd26dbe0 100644
--- a/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx
+++ b/apps/studio/components/interfaces/Organization/BillingSettings/Subscription/PlanUpdateSidePanel.tsx
@@ -18,7 +18,7 @@ import { useOrgPlansQuery } from 'data/subscriptions/org-plans-query'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
import type { OrgPlan } from 'data/subscriptions/types'
import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { MANAGED_BY } from 'lib/constants/infrastructure'
import { formatCurrency } from 'lib/helpers'
@@ -60,7 +60,7 @@ const PlanUpdateSidePanel = () => {
const [showDowngradeError, setShowDowngradeError] = useState(false)
const [selectedTier, setSelectedTier] = useState<'tier_free' | 'tier_pro' | 'tier_team'>()
- const canUpdateSubscription = useCheckPermissions(
+ const { can: canUpdateSubscription } = useAsyncCheckProjectPermissions(
PermissionAction.BILLING_WRITE,
'stripe.subscriptions'
)
@@ -88,8 +88,6 @@ const PlanUpdateSidePanel = () => {
const { data: plans, isLoading: isLoadingPlans } = useOrgPlansQuery({ orgSlug: slug })
const { data: membersExceededLimit } = useFreeProjectLimitCheckQuery({ slug })
- const billingPartner = subscription?.billing_partner
-
const {
data: subscriptionPreview,
error: subscriptionPreviewError,
diff --git a/apps/studio/components/interfaces/Organization/Documents/SOC2.tsx b/apps/studio/components/interfaces/Organization/Documents/SOC2.tsx
index ecf357accf2..f08ed28a53e 100644
--- a/apps/studio/components/interfaces/Organization/Documents/SOC2.tsx
+++ b/apps/studio/components/interfaces/Organization/Documents/SOC2.tsx
@@ -12,19 +12,19 @@ import {
import NoPermission from 'components/ui/NoPermission'
import { getDocument } from 'data/documents/document-query'
import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { Button } from 'ui'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
+import ShimmeringLoader from 'ui-patterns/ShimmeringLoader'
export const SOC2 = () => {
const { data: organization } = useSelectedOrganizationQuery()
const slug = organization?.slug
+
const { mutate: sendEvent } = useSendEventMutation()
- const canReadSubscriptions = useCheckPermissions(
- PermissionAction.BILLING_READ,
- 'stripe.subscriptions'
- )
+ const { can: canReadSubscriptions, isLoading: isLoadingPermissions } =
+ useAsyncCheckProjectPermissions(PermissionAction.BILLING_READ, 'stripe.subscriptions')
const currentPlan = organization?.plan
@@ -51,7 +51,11 @@ export const SOC2 = () => {
</div>
</ScaffoldSectionDetail>
<ScaffoldSectionContent>
- {!canReadSubscriptions ? (
+ {isLoadingPermissions ? (
+ <div className="flex items-center justify-center h-full">
+ <ShimmeringLoader className="w-24" />
+ </div>
+ ) : !canReadSubscriptions ? (
<NoPermission resourceText="access our SOC2 Type 2 report" />
) : (
<div className="flex items-center justify-center h-full">
diff --git a/apps/studio/components/interfaces/Organization/Documents/SecurityQuestionnaire.tsx b/apps/studio/components/interfaces/Organization/Documents/SecurityQuestionnaire.tsx
index 624cdfbc39a..2e165448d95 100644
--- a/apps/studio/components/interfaces/Organization/Documents/SecurityQuestionnaire.tsx
+++ b/apps/studio/components/interfaces/Organization/Documents/SecurityQuestionnaire.tsx
@@ -11,18 +11,18 @@ import {
import NoPermission from 'components/ui/NoPermission'
import { getDocument } from 'data/documents/document-query'
import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { Button } from 'ui'
+import ShimmeringLoader from 'ui-patterns/ShimmeringLoader'
export const SecurityQuestionnaire = () => {
const { data: organization } = useSelectedOrganizationQuery()
const slug = organization?.slug
+
const { mutate: sendEvent } = useSendEventMutation()
- const canReadSubscriptions = useCheckPermissions(
- PermissionAction.BILLING_READ,
- 'stripe.subscriptions'
- )
+ const { can: canReadSubscriptions, isLoading: isLoadingPermissions } =
+ useAsyncCheckProjectPermissions(PermissionAction.BILLING_READ, 'stripe.subscriptions')
const currentPlan = organization?.plan
@@ -51,7 +51,11 @@ export const SecurityQuestionnaire = () => {
</div>
</ScaffoldSectionDetail>
<ScaffoldSectionContent>
- {!canReadSubscriptions ? (
+ {isLoadingPermissions ? (
+ <div className="flex items-center justify-center h-full">
+ <ShimmeringLoader className="w-24" />
+ </div>
+ ) : !canReadSubscriptions ? (
<NoPermission resourceText="access our security questionnaire" />
) : (
<>
diff --git a/apps/studio/components/interfaces/Organization/GeneralSettings/DataPrivacyForm.tsx b/apps/studio/components/interfaces/Organization/GeneralSettings/DataPrivacyForm.tsx
index 54247a6d517..b90faee2011 100644
--- a/apps/studio/components/interfaces/Organization/GeneralSettings/DataPrivacyForm.tsx
+++ b/apps/studio/components/interfaces/Organization/GeneralSettings/DataPrivacyForm.tsx
@@ -3,13 +3,16 @@ import { useEffect } from 'react'
import { FormActions } from 'components/ui/Forms/FormActions'
import { useAIOptInForm } from 'hooks/forms/useAIOptInForm'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { Card, CardContent, CardFooter, Form_Shadcn_ } from 'ui'
import { AIOptInLevelSelector } from './AIOptInLevelSelector'
export const DataPrivacyForm = () => {
const { form, onSubmit, isUpdating, currentOptInLevel } = useAIOptInForm()
- const canUpdateOrganization = useCheckPermissions(PermissionAction.UPDATE, 'organizations')
+ const { can: canUpdateOrganization } = useAsyncCheckProjectPermissions(
+ PermissionAction.UPDATE,
+ 'organizations'
+ )
const permissionsHelperText = !canUpdateOrganization
? "You need additional permissions to manage this organization's settings"
diff --git a/apps/studio/components/interfaces/Organization/GeneralSettings/DeleteOrganizationButton.tsx b/apps/studio/components/interfaces/Organization/GeneralSettings/DeleteOrganizationButton.tsx
index de767135a0b..5fd8de703b8 100644
--- a/apps/studio/components/interfaces/Organization/GeneralSettings/DeleteOrganizationButton.tsx
+++ b/apps/studio/components/interfaces/Organization/GeneralSettings/DeleteOrganizationButton.tsx
@@ -4,8 +4,9 @@ import { useState } from 'react'
import { toast } from 'sonner'
import { LOCAL_STORAGE_KEYS } from 'common'
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { useOrganizationDeleteMutation } from 'data/organizations/organization-delete-mutation'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { Button, Form, Input, Modal } from 'ui'
@@ -23,7 +24,11 @@ export const DeleteOrganizationButton = () => {
''
)
- const canDeleteOrganization = useCheckPermissions(PermissionAction.UPDATE, 'organizations')
+ const { can: canDeleteOrganization } = useAsyncCheckProjectPermissions(
+ PermissionAction.UPDATE,
+ 'organizations'
+ )
+
const { mutate: deleteOrganization, isLoading: isDeleting } = useOrganizationDeleteMutation({
onSuccess: () => {
toast.success(`Successfully deleted ${orgName}`)
@@ -55,9 +60,22 @@ export const DeleteOrganizationButton = () => {
return (
<>
<div className="mt-2">
- <Button loading={!orgSlug} onClick={() => setIsOpen(true)} type="danger">
+ <ButtonTooltip
+ type="danger"
+ disabled={!canDeleteOrganization}
+ loading={!orgSlug}
+ onClick={() => setIsOpen(true)}
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text: !canDeleteOrganization
+ ? 'You need additional permissions to delete this organization'
+ : undefined,
+ },
+ }}
+ >
Delete organization
- </Button>
+ </ButtonTooltip>
</div>
<Modal
hideFooter
diff --git a/apps/studio/components/interfaces/Organization/GeneralSettings/GeneralSettings.tsx b/apps/studio/components/interfaces/Organization/GeneralSettings/GeneralSettings.tsx
index 2f28ffd5781..54194192c44 100644
--- a/apps/studio/components/interfaces/Organization/GeneralSettings/GeneralSettings.tsx
+++ b/apps/studio/components/interfaces/Organization/GeneralSettings/GeneralSettings.tsx
@@ -1,22 +1,18 @@
-import { PermissionAction } from '@supabase/shared-types/out/constants'
import { NoProjectsOnPaidOrgInfo } from 'components/interfaces/Billing/NoProjectsOnPaidOrgInfo'
import {
ScaffoldContainer,
ScaffoldSection,
ScaffoldSectionTitle,
} from 'components/layouts/Scaffold'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'
-import OrganizationDeletePanel from './OrganizationDeletePanel'
+import { OrganizationDeletePanel } from './OrganizationDeletePanel'
import { DataPrivacyForm } from './DataPrivacyForm'
import { OrganizationDetailsForm } from './OrganizationDetailsForm'
-const GeneralSettings = () => {
+export const GeneralSettings = () => {
const organizationDeletionEnabled = useIsFeatureEnabled('organizations:delete')
- const canDeleteOrganization = useCheckPermissions(PermissionAction.UPDATE, 'organizations')
-
return (
<ScaffoldContainer>
<NoProjectsOnPaidOrgInfo />
@@ -31,9 +27,7 @@ const GeneralSettings = () => {
<DataPrivacyForm />
</ScaffoldSection>
- {organizationDeletionEnabled && canDeleteOrganization && <OrganizationDeletePanel />}
+ {organizationDeletionEnabled && <OrganizationDeletePanel />}
</ScaffoldContainer>
)
}
-
-export default GeneralSettings
diff --git a/apps/studio/components/interfaces/Organization/GeneralSettings/OrganizationDeletePanel.tsx b/apps/studio/components/interfaces/Organization/GeneralSettings/OrganizationDeletePanel.tsx
index 04e6537c15c..d484b76993b 100644
--- a/apps/studio/components/interfaces/Organization/GeneralSettings/OrganizationDeletePanel.tsx
+++ b/apps/studio/components/interfaces/Organization/GeneralSettings/OrganizationDeletePanel.tsx
@@ -1,11 +1,11 @@
import { ScaffoldSection, ScaffoldSectionTitle } from 'components/layouts/Scaffold'
import PartnerManagedResource from 'components/ui/PartnerManagedResource'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
+import { MANAGED_BY } from 'lib/constants/infrastructure'
import { Admonition } from 'ui-patterns'
import { DeleteOrganizationButton } from './DeleteOrganizationButton'
-import { MANAGED_BY } from 'lib/constants/infrastructure'
-const OrganizationDeletePanel = () => {
+export const OrganizationDeletePanel = () => {
const { data: selectedOrganization } = useSelectedOrganizationQuery()
return (
@@ -33,5 +33,3 @@ const OrganizationDeletePanel = () => {
</ScaffoldSection>
)
}
-
-export default OrganizationDeletePanel
diff --git a/apps/studio/components/interfaces/Organization/GeneralSettings/OrganizationDetailsForm.tsx b/apps/studio/components/interfaces/Organization/GeneralSettings/OrganizationDetailsForm.tsx
index 72858b0761f..797f791e92e 100644
--- a/apps/studio/components/interfaces/Organization/GeneralSettings/OrganizationDetailsForm.tsx
+++ b/apps/studio/components/interfaces/Organization/GeneralSettings/OrganizationDetailsForm.tsx
@@ -11,7 +11,7 @@ import CopyButton from 'components/ui/CopyButton'
import { FormActions } from 'components/ui/Forms/FormActions'
import { useOrganizationUpdateMutation } from 'data/organizations/organization-update-mutation'
import { invalidateOrganizationsQuery } from 'data/organizations/organizations-query'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import type { ResponseError } from 'types'
import {
@@ -34,7 +34,11 @@ export const OrganizationDetailsForm = () => {
const { slug } = useParams()
const queryClient = useQueryClient()
const { data: selectedOrganization } = useSelectedOrganizationQuery()
- const canUpdateOrganization = useCheckPermissions(PermissionAction.UPDATE, 'organizations')
+
+ const { can: canUpdateOrganization } = useAsyncCheckProjectPermissions(
+ PermissionAction.UPDATE,
+ 'organizations'
+ )
const { mutate: updateOrganization, isLoading: isUpdatingDetails } =
useOrganizationUpdateMutation()
diff --git a/apps/studio/components/interfaces/Organization/IntegrationSettings/IntegrationSettings.tsx b/apps/studio/components/interfaces/Organization/IntegrationSettings/IntegrationSettings.tsx
index 88764d28498..453b0ed4f31 100644
--- a/apps/studio/components/interfaces/Organization/IntegrationSettings/IntegrationSettings.tsx
+++ b/apps/studio/components/interfaces/Organization/IntegrationSettings/IntegrationSettings.tsx
@@ -19,7 +19,7 @@ import { useGitHubAuthorizationQuery } from 'data/integrations/github-authorizat
import { useGitHubConnectionDeleteMutation } from 'data/integrations/github-connection-delete-mutation'
import { useGitHubConnectionsQuery } from 'data/integrations/github-connections-query'
import type { IntegrationProjectConnection } from 'data/integrations/integrations.types'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { BASE_PATH } from 'lib/constants'
@@ -29,6 +29,7 @@ import {
} from 'lib/github'
import { useRouter } from 'next/router'
import { useSidePanelsStateSnapshot } from 'state/side-panels'
+import { GenericSkeletonLoader } from 'ui-patterns'
import { IntegrationConnectionItem } from '../../Integrations/VercelGithub/IntegrationConnection'
import SidePanelVercelProjectLinker from './SidePanelVercelProjectLinker'
@@ -48,15 +49,13 @@ const IntegrationSettings = () => {
const showVercelIntegration = useIsFeatureEnabled('integrations:vercel')
- const canReadGithubConnection = useCheckPermissions(
- PermissionAction.READ,
- 'integrations.github_connections'
- )
- const canCreateGitHubConnection = useCheckPermissions(
+ const { can: canReadGithubConnection, isLoading: isLoadingPermissions } =
+ useAsyncCheckProjectPermissions(PermissionAction.READ, 'integrations.github_connections')
+ const { can: canCreateGitHubConnection } = useAsyncCheckProjectPermissions(
PermissionAction.CREATE,
'integrations.github_connections'
)
- const canUpdateGitHubConnection = useCheckPermissions(
+ const { can: canUpdateGitHubConnection } = useAsyncCheckProjectPermissions(
PermissionAction.UPDATE,
'integrations.github_connections'
)
@@ -121,7 +120,9 @@ The GitHub app will watch for changes in your repository such as file changes, b
<IntegrationImageHandler title="github" />
</ScaffoldSectionDetail>
<ScaffoldSectionContent>
- {!canReadGithubConnection ? (
+ {isLoadingPermissions ? (
+ <GenericSkeletonLoader />
+ ) : !canReadGithubConnection ? (
<NoPermission resourceText="view this organization's GitHub connections" />
) : (
<>
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppRow.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppRow.tsx
index ea6ce8776b3..08a9259f063 100644
--- a/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppRow.tsx
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthAppRow.tsx
@@ -4,7 +4,7 @@ import { Edit, MoreVertical, Trash } from 'lucide-react'
import Table from 'components/to-be-cleaned/Table'
import CopyButton from 'components/ui/CopyButton'
import type { OAuthApp } from 'data/oauth/oauth-apps-query'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import {
Button,
DropdownMenu,
@@ -25,8 +25,14 @@ export interface OAuthAppRowProps {
}
export const OAuthAppRow = ({ app, onSelectEdit, onSelectDelete }: OAuthAppRowProps) => {
- const canUpdateOAuthApps = useCheckPermissions(PermissionAction.UPDATE, 'approved_oauth_apps')
- const canDeleteOAuthApps = useCheckPermissions(PermissionAction.DELETE, 'approved_oauth_apps')
+ const { can: canUpdateOAuthApps } = useAsyncCheckProjectPermissions(
+ PermissionAction.UPDATE,
+ 'approved_oauth_apps'
+ )
+ const { can: canDeleteOAuthApps } = useAsyncCheckProjectPermissions(
+ PermissionAction.DELETE,
+ 'approved_oauth_apps'
+ )
return (
<Table.tr>
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/OAuthApps.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthApps.tsx
index 79b4464e083..ddeff5064ec 100644
--- a/apps/studio/components/interfaces/Organization/OAuthApps/OAuthApps.tsx
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthApps.tsx
@@ -3,7 +3,7 @@ import { Check, X } from 'lucide-react'
import { useState } from 'react'
import { useParams } from 'common'
-import { ScaffoldContainerLegacy } from 'components/layouts/Scaffold'
+import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'
import Table from 'components/to-be-cleaned/Table'
import AlertError from 'components/ui/AlertError'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
@@ -13,7 +13,7 @@ import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { AuthorizedApp, useAuthorizedAppsQuery } from 'data/oauth/authorized-apps-query'
import { OAuthAppCreateResponse } from 'data/oauth/oauth-app-create-mutation'
import { OAuthApp, useOAuthAppsQuery } from 'data/oauth/oauth-apps-query'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { Button, cn } from 'ui'
import { AuthorizedAppRow } from './AuthorizedAppRow'
import { DeleteAppModal } from './DeleteAppModal'
@@ -26,7 +26,7 @@ import { RevokeAppModal } from './RevokeAppModal'
// to prevent any confusion (case study: GitHub). Authorized apps could be in the "integrations" tab, but let's
// check in again after we wrap up Vercel integration
-const OAuthApps = () => {
+export const OAuthApps = () => {
const { slug } = useParams()
const [showPublishModal, setShowPublishModal] = useState(false)
const [createdApp, setCreatedApp] = useState<OAuthAppCreateResponse>()
@@ -34,8 +34,12 @@ const OAuthApps = () => {
const [selectedAppToDelete, setSelectedAppToDelete] = useState<OAuthApp>()
const [selectedAppToRevoke, setSelectedAppToRevoke] = useState<AuthorizedApp>()
- const canReadOAuthApps = useCheckPermissions(PermissionAction.READ, 'approved_oauth_apps')
- const canCreateOAuthApps = useCheckPermissions(PermissionAction.CREATE, 'approved_oauth_apps')
+ const { can: canReadOAuthApps, isLoading: isLoadingPermissions } =
+ useAsyncCheckProjectPermissions(PermissionAction.READ, 'approved_oauth_apps')
+ const { can: canCreateOAuthApps } = useAsyncCheckProjectPermissions(
+ PermissionAction.CREATE,
+ 'approved_oauth_apps'
+ )
const {
data: publishedApps,
@@ -60,175 +64,121 @@ const OAuthApps = () => {
return Number(new Date(a.authorized_at)) - Number(new Date(b.authorized_at))
})
- if (!canReadOAuthApps) {
- return (
- <ScaffoldContainerLegacy>
- <NoPermission resourceText="view OAuth apps" />
- </ScaffoldContainerLegacy>
- )
- }
-
return (
<>
- <ScaffoldContainerLegacy>
- <div className="space-y-4">
- <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-2">
- <div>
- <p>Published Apps</p>
- <p className="text-foreground-light text-sm">
- Build integrations that extend Supabase's functionality
- </p>
+ <ScaffoldContainer>
+ <ScaffoldSection isFullWidth className="flex flex-col gap-y-8">
+ <div className="space-y-4">
+ <div className="flex flex-col md:flex-row items-start md:items-center justify-between gap-2">
+ <div>
+ <p>Published Apps</p>
+ <p className="text-foreground-light text-sm">
+ Build integrations that extend Supabase's functionality
+ </p>
+ </div>
+ <ButtonTooltip
+ disabled={!canCreateOAuthApps}
+ type="primary"
+ onClick={() => setShowPublishModal(true)}
+ tooltip={{
+ content: {
+ side: 'bottom',
+ text: !canCreateOAuthApps
+ ? 'You need additional permissions to create apps'
+ : undefined,
+ },
+ }}
+ >
+ Add application
+ </ButtonTooltip>
</div>
- <ButtonTooltip
- disabled={!canCreateOAuthApps}
- type="primary"
- onClick={() => setShowPublishModal(true)}
- tooltip={{
- content: {
- side: 'bottom',
- text: !canCreateOAuthApps
- ? 'You need additional permissions to create apps'
- : undefined,
- },
- }}
- >
- Add application
- </ButtonTooltip>
- </div>
- {isLoadingPublishedApps && (
- <div className="space-y-2">
- <ShimmeringLoader />
- <ShimmeringLoader className="w-3/4" />
- <ShimmeringLoader className="w-1/2" />
- </div>
- )}
+ {isLoadingPublishedApps || isLoadingPermissions ? (
+ <div className="space-y-2">
+ <ShimmeringLoader />
+ <ShimmeringLoader className="w-3/4" />
+ <ShimmeringLoader className="w-1/2" />
+ </div>
+ ) : !canReadOAuthApps ? (
+ <NoPermission resourceText="view OAuth apps" />
+ ) : null}
- {isErrorPublishedApps && (
- <AlertError
- error={publishedAppsError}
- subject="Failed to retrieve published OAuth apps"
- />
- )}
+ {isErrorPublishedApps && (
+ <AlertError
+ error={publishedAppsError}
+ subject="Failed to retrieve published OAuth apps"
+ />
+ )}
- {createdApp !== undefined && (
- <div
- className={cn(
- 'flex items-center justify-between p-4 px-6 border first:rounded-t last:rounded-b',
- 'bg-background-alternative',
- 'rounded'
- )}
- >
- <div className="absolute top-4 right-4">
- <Button
- type="text"
- icon={<X size={18} />}
- className="px-1"
- onClick={() => setCreatedApp(undefined)}
- />
- </div>
- <div className="w-full space-y-4">
- <div className="flex flex-col gap-0">
- <div className="flex items-center gap-2">
- <Check size={14} className="text-brand" strokeWidth={3} />
- <p className="text-sm">You've created your new OAuth application.</p>
- </div>
- <p className="text-sm text-foreground-light">
- Ensure that you store the client secret securely - you will not be able to see
- it again.
- </p>
+ {createdApp !== undefined && (
+ <div
+ className={cn(
+ 'flex items-center justify-between p-4 px-6 border first:rounded-t last:rounded-b',
+ 'bg-background-alternative',
+ 'rounded'
+ )}
+ >
+ <div className="absolute top-4 right-4">
+ <Button
+ type="text"
+ icon={<X size={18} />}
+ className="px-1"
+ onClick={() => setCreatedApp(undefined)}
+ />
</div>
- <div className="flex flex-col gap-1">
- <div className="flex items-center gap-2">
- <p className="text-sm text-foreground-light">Client ID</p>
- <p className="font-mono text-sm">{createdApp.client_id}</p>
- <CopyButton text={createdApp.client_id} type="default" iconOnly />
+ <div className="w-full space-y-4">
+ <div className="flex flex-col gap-0">
+ <div className="flex items-center gap-2">
+ <Check size={14} className="text-brand" strokeWidth={3} />
+ <p className="text-sm">You've created your new OAuth application.</p>
+ </div>
+ <p className="text-sm text-foreground-light">
+ Ensure that you store the client secret securely - you will not be able to see
+ it again.
+ </p>
</div>
+ <div className="flex flex-col gap-1">
+ <div className="flex items-center gap-2">
+ <p className="text-sm text-foreground-light">Client ID</p>
+ <p className="font-mono text-sm">{createdApp.client_id}</p>
+ <CopyButton text={createdApp.client_id} type="default" iconOnly />
+ </div>
- <div className="flex items-center gap-2">
- <p className="text-sm text-foreground-light">Client Secret</p>
- <p className="font-mono text-sm">{createdApp.client_secret}</p>
- <CopyButton text={createdApp.client_secret} type="default" iconOnly />
+ <div className="flex items-center gap-2">
+ <p className="text-sm text-foreground-light">Client Secret</p>
+ <p className="font-mono text-sm">{createdApp.client_secret}</p>
+ <CopyButton text={createdApp.client_secret} type="default" iconOnly />
+ </div>
</div>
</div>
</div>
- </div>
- )}
-
- {isSuccessPublishedApps && (
- <>
- {(publishedApps?.length ?? 0) === 0 ? (
- <div className="bg-surface-100 border rounded p-4 flex items-center justify-between mt-4">
- <p className="prose text-sm">You do not have any published applications yet</p>
- </div>
- ) : (
- <Table
- head={[
- <Table.th key="icon" className="w-[30px]"></Table.th>,
- <Table.th key="name">Name</Table.th>,
- <Table.th key="client-id">Client ID</Table.th>,
- <Table.th key="created-at">Created at</Table.th>,
- <Table.th key="delete-action"></Table.th>,
- ]}
- body={
- sortedPublishedApps?.map((app) => (
- <OAuthAppRow
- key={app.id}
- app={app}
- onSelectEdit={() => {
- setShowPublishModal(true)
- setSelectedAppToUpdate(app)
- }}
- onSelectDelete={() => setSelectedAppToDelete(app)}
- />
- )) ?? []
- }
- />
- )}
- </>
- )}
- </div>
-
- <div>
- <p>Authorized Apps</p>
- <p className="text-foreground-light text-sm">
- Applications that have access to your organization's settings and projects
- </p>
-
- <div className="mt-4">
- {isLoadingAuthorizedApps && (
- <div className="space-y-2">
- <ShimmeringLoader />
- <ShimmeringLoader className="w-3/4" />
- <ShimmeringLoader className="w-1/2" />
- </div>
)}
- {isErrorAuthorizedApps && <AlertError subject="Failed to retrieve authorized apps" />}
-
- {isSuccessAuthorizedApps && (
+ {isSuccessPublishedApps && (
<>
- {(authorizedApps.length ?? 0) === 0 ? (
- <div className="bg-surface-100 border rounded p-4 flex items-center justify-between">
- <p className="prose text-sm">You do not have any authorized applications yet</p>
+ {(publishedApps?.length ?? 0) === 0 ? (
+ <div className="bg-surface-100 border rounded p-4 flex items-center justify-between mt-4">
+ <p className="prose text-sm">You do not have any published applications yet</p>
</div>
) : (
<Table
- className="mt-4"
head={[
<Table.th key="icon" className="w-[30px]"></Table.th>,
<Table.th key="name">Name</Table.th>,
- <Table.th key="created-by">Created by</Table.th>,
- <Table.th key="app-id">App ID</Table.th>,
- <Table.th key="authorized-at">Authorized at</Table.th>,
+ <Table.th key="client-id">Client ID</Table.th>,
+ <Table.th key="created-at">Created at</Table.th>,
<Table.th key="delete-action"></Table.th>,
]}
body={
- sortedAuthorizedApps?.map((app) => (
- <AuthorizedAppRow
+ sortedPublishedApps?.map((app) => (
+ <OAuthAppRow
key={app.id}
app={app}
- onSelectRevoke={() => setSelectedAppToRevoke(app)}
+ onSelectEdit={() => {
+ setShowPublishModal(true)
+ setSelectedAppToUpdate(app)
+ }}
+ onSelectDelete={() => setSelectedAppToDelete(app)}
/>
)) ?? []
}
@@ -237,8 +187,62 @@ const OAuthApps = () => {
</>
)}
</div>
- </div>
- </ScaffoldContainerLegacy>
+
+ <div>
+ <p>Authorized Apps</p>
+ <p className="text-foreground-light text-sm">
+ Applications that have access to your organization's settings and projects
+ </p>
+
+ <div className="mt-4">
+ {isLoadingAuthorizedApps || isLoadingPermissions ? (
+ <div className="space-y-2">
+ <ShimmeringLoader />
+ <ShimmeringLoader className="w-3/4" />
+ <ShimmeringLoader className="w-1/2" />
+ </div>
+ ) : !canReadOAuthApps ? (
+ <NoPermission resourceText="view authorized apps" />
+ ) : null}
+
+ {isErrorAuthorizedApps && <AlertError subject="Failed to retrieve authorized apps" />}
+
+ {isSuccessAuthorizedApps && (
+ <>
+ {(authorizedApps.length ?? 0) === 0 ? (
+ <div className="bg-surface-100 border rounded p-4 flex items-center justify-between">
+ <p className="prose text-sm">
+ You do not have any authorized applications yet
+ </p>
+ </div>
+ ) : (
+ <Table
+ className="mt-4"
+ head={[
+ <Table.th key="icon" className="w-[30px]"></Table.th>,
+ <Table.th key="name">Name</Table.th>,
+ <Table.th key="created-by">Created by</Table.th>,
+ <Table.th key="app-id">App ID</Table.th>,
+ <Table.th key="authorized-at">Authorized at</Table.th>,
+ <Table.th key="delete-action"></Table.th>,
+ ]}
+ body={
+ sortedAuthorizedApps?.map((app) => (
+ <AuthorizedAppRow
+ key={app.id}
+ app={app}
+ onSelectRevoke={() => setSelectedAppToRevoke(app)}
+ />
+ )) ?? []
+ }
+ />
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ </ScaffoldSection>
+ </ScaffoldContainer>
<PublishAppSidePanel
visible={showPublishModal}
@@ -260,5 +264,3 @@ const OAuthApps = () => {
</>
)
}
-
-export default OAuthApps
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/OAuthSecrets/OAuthSecrets.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthSecrets/OAuthSecrets.tsx
index 9026e2d63d1..84e003a9e83 100644
--- a/apps/studio/components/interfaces/Organization/OAuthApps/OAuthSecrets/OAuthSecrets.tsx
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthSecrets/OAuthSecrets.tsx
@@ -7,7 +7,7 @@ import { InlineLink } from 'components/ui/InlineLink'
import { useClientSecretCreateMutation } from 'data/oauth-secrets/client-secret-create-mutation'
import { CreatedSecret, useClientSecretsQuery } from 'data/oauth-secrets/client-secrets-query'
import { OAuthApp } from 'data/oauth/oauth-apps-query'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { Alert_Shadcn_, AlertTitle_Shadcn_, InfoIcon } from 'ui'
import { SecretRow } from './SecretRow'
@@ -18,7 +18,10 @@ interface Props {
export const OAuthSecrets = ({ selectedApp }: Props) => {
const { slug } = useParams()
const [createdSecret, setCreatedSecret] = useState<CreatedSecret>()
- const canManageSecrets = useCheckPermissions(PermissionAction.UPDATE, 'oauth_apps')
+ const { can: canManageSecrets } = useAsyncCheckProjectPermissions(
+ PermissionAction.UPDATE,
+ 'oauth_apps'
+ )
const { id: appId } = selectedApp ?? {}
diff --git a/apps/studio/components/interfaces/Organization/OAuthApps/OAuthSecrets/SecretRow.tsx b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthSecrets/SecretRow.tsx
index 20717de9729..92e3e3a55aa 100644
--- a/apps/studio/components/interfaces/Organization/OAuthApps/OAuthSecrets/SecretRow.tsx
+++ b/apps/studio/components/interfaces/Organization/OAuthApps/OAuthSecrets/SecretRow.tsx
@@ -10,7 +10,7 @@ import CopyButton from 'components/ui/CopyButton'
import { useClientSecretDeleteMutation } from 'data/oauth-secrets/client-secret-delete-mutation'
import { Secret, useClientSecretsQuery } from 'data/oauth-secrets/client-secrets-query'
import { useOrganizationMembersQuery } from 'data/organizations/organization-members-query'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { cn } from 'ui'
import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
@@ -22,7 +22,10 @@ export interface SecretRowProps {
export const SecretRow = ({ secret, appId }: SecretRowProps) => {
const { slug } = useParams()
const [showDeleteModal, setShowDeleteModal] = useState(false)
- const canManageSecrets = useCheckPermissions(PermissionAction.UPDATE, 'oauth_apps')
+ const { can: canManageSecrets } = useAsyncCheckProjectPermissions(
+ PermissionAction.UPDATE,
+ 'oauth_apps'
+ )
const { data } = useClientSecretsQuery({ slug, appId })
const secrets = data?.client_secrets ?? []
diff --git a/apps/studio/components/interfaces/Organization/SecuritySettings/SecuritySettings.tsx b/apps/studio/components/interfaces/Organization/SecuritySettings/SecuritySettings.tsx
index e4934a603f2..1dd91caccb0 100644
--- a/apps/studio/components/interfaces/Organization/SecuritySettings/SecuritySettings.tsx
+++ b/apps/studio/components/interfaces/Organization/SecuritySettings/SecuritySettings.tsx
@@ -7,7 +7,7 @@ import { toast } from 'sonner'
import { z } from 'zod'
import { useParams } from 'common'
-import { ScaffoldContainerLegacy } from 'components/layouts/Scaffold'
+import { ScaffoldContainer, ScaffoldSection } from 'components/layouts/Scaffold'
import AlertError from 'components/ui/AlertError'
import { InlineLink } from 'components/ui/InlineLink'
import NoPermission from 'components/ui/NoPermission'
@@ -16,7 +16,7 @@ import { useOrganizationMembersQuery } from 'data/organizations/organization-mem
import { useOrganizationMfaToggleMutation } from 'data/organizations/organization-mfa-mutation'
import { useOrganizationMfaQuery } from 'data/organizations/organization-mfa-query'
import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { useProfile } from 'lib/profile'
import {
@@ -42,13 +42,18 @@ const schema = z.object({
enforceMfa: z.boolean(),
})
-const SecuritySettings = () => {
+export const SecuritySettings = () => {
const { slug } = useParams()
const { profile } = useProfile()
const { data: selectedOrganization } = useSelectedOrganizationQuery()
const { data: members } = useOrganizationMembersQuery({ slug })
- const canReadMfaConfig = useCheckPermissions(PermissionAction.READ, 'organizations')
- const canUpdateMfaConfig = useCheckPermissions(PermissionAction.UPDATE, 'organizations')
+
+ const { can: canReadMfaConfig, isLoading: isLoadingPermissions } =
+ useAsyncCheckProjectPermissions(PermissionAction.READ, 'organizations')
+ const { can: canUpdateMfaConfig } = useAsyncCheckProjectPermissions(
+ PermissionAction.UPDATE,
+ 'organizations'
+ )
const { mutate: sendEvent } = useSendEventMutation()
const isPaidPlan = selectedOrganization?.plan.id !== 'free'
@@ -59,7 +64,7 @@ const SecuritySettings = () => {
isLoading: isLoadingMfa,
isError: isErrorMfa,
isSuccess: isSuccessMfa,
- } = useOrganizationMfaQuery({ slug }, { enabled: canReadMfaConfig })
+ } = useOrganizationMfaQuery({ slug }, { enabled: isPaidPlan && canReadMfaConfig })
const { mutate: toggleMfa, isLoading: isUpdatingMfa } = useOrganizationMfaToggleMutation({
onError: (error) => {
@@ -101,134 +106,130 @@ const SecuritySettings = () => {
toggleMfa({ slug, setEnforced: values.enforceMfa })
}
- if (!canReadMfaConfig) {
- return (
- <ScaffoldContainerLegacy>
- <NoPermission resourceText="view organization security settings" />
- </ScaffoldContainerLegacy>
- )
- }
-
return (
- <ScaffoldContainerLegacy>
- {!isPaidPlan && (
- <Alert_Shadcn_
- variant="default"
- title="Organization MFA enforcement is not available on Free plan"
- >
- <WarningIcon />
- <div className="flex flex-col md:flex-row pt-1 gap-4">
- <div className="grow">
- <AlertTitle_Shadcn_>
- Organization MFA enforcement is not available on Free plan
- </AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_ className="flex flex-row justify-between gap-3">
- <p>Upgrade to Pro or above to enforce MFA requirements for your organization.</p>
- </AlertDescription_Shadcn_>
- </div>
-
- <div className="flex items-center">
- <Button type="primary" asChild>
- <Link href={`/org/${slug}/billing?panel=subscriptionPlan&source=mfa`}>
- Upgrade subscription
- </Link>
- </Button>
- </div>
- </div>
- </Alert_Shadcn_>
- )}
-
- {(isErrorMfa || mfaError) && isPaidPlan && (
- <AlertError error={mfaError} subject="Failed to retrieve MFA enforcement status" />
- )}
-
- {isLoadingMfa && (
- <Card>
- <CardContent>
- <GenericSkeletonLoader />
- </CardContent>
- </Card>
- )}
-
- {isSuccessMfa && isPaidPlan && (
- <Form_Shadcn_ {...form}>
- <form onSubmit={form.handleSubmit(onSubmit)}>
- <Card>
- <CardContent>
- <FormField_Shadcn_
- control={form.control}
- name="enforceMfa"
- render={({ field }) => (
- <FormItemLayout
- layout="flex-row-reverse"
- label="Require MFA to access organization"
- description="Team members must have MFA enabled and a valid MFA session to access the organization and any projects."
- >
- <FormControl_Shadcn_>
- <Tooltip>
- <TooltipTrigger asChild>
- <div>
- <Switch
- checked={field.value}
- onCheckedChange={field.onChange}
- disabled={
- !isPaidPlan ||
- !canUpdateMfaConfig ||
- !hasMFAEnabled ||
- isUpdatingMfa
- }
- />
- </div>
- </TooltipTrigger>
- {(!canUpdateMfaConfig || !hasMFAEnabled) && (
- <TooltipContent side="bottom">
- {!canUpdateMfaConfig ? (
- "You don't have permission to update MFA settings"
- ) : (
- <>
- <InlineLink href="/account/security">Enable MFA</InlineLink> on
- your own account first
- </>
- )}
- </TooltipContent>
- )}
- </Tooltip>
- </FormControl_Shadcn_>
- </FormItemLayout>
- )}
- />
- </CardContent>
- <CardFooter className="justify-end space-x-2">
- {form.formState.isDirty && (
- <Button
- type="default"
- disabled={isLoadingMfa || isUpdatingMfa}
- onClick={() => form.reset({ enforceMfa: isPaidPlan ? mfaConfig : false })}
- >
- Cancel
- </Button>
- )}
- <Button
- type="primary"
- htmlType="submit"
- disabled={
- !isPaidPlan ||
- !canUpdateMfaConfig ||
- isUpdatingMfa ||
- isLoadingMfa ||
- !form.formState.isDirty
- }
- loading={isUpdatingMfa}
- >
- Save changes
+ <ScaffoldContainer>
+ <ScaffoldSection isFullWidth>
+ {!isPaidPlan ? (
+ <Alert_Shadcn_
+ variant="default"
+ title="Organization MFA enforcement is not available on Free plan"
+ >
+ <WarningIcon />
+ <div className="flex flex-col md:flex-row pt-1 gap-4">
+ <div className="grow">
+ <AlertTitle_Shadcn_>
+ Organization MFA enforcement is not available on Free plan
+ </AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_ className="flex flex-row justify-between gap-3">
+ <p>Upgrade to Pro or above to enforce MFA requirements for your organization.</p>
+ </AlertDescription_Shadcn_>
+ </div>
+
+ <div className="flex items-center">
+ <Button type="primary" asChild>
+ <Link href={`/org/${slug}/billing?panel=subscriptionPlan&source=mfa`}>
+ Upgrade subscription
+ </Link>
</Button>
- </CardFooter>
- </Card>
- </form>
- </Form_Shadcn_>
- )}
- </ScaffoldContainerLegacy>
+ </div>
+ </div>
+ </Alert_Shadcn_>
+ ) : (
+ <>
+ {isLoadingMfa || isLoadingPermissions ? (
+ <Card>
+ <CardContent>
+ <GenericSkeletonLoader />
+ </CardContent>
+ </Card>
+ ) : !canReadMfaConfig ? (
+ <NoPermission resourceText="view organization security settings" />
+ ) : null}
+
+ {(isErrorMfa || mfaError) && isPaidPlan && (
+ <AlertError error={mfaError} subject="Failed to retrieve MFA enforcement status" />
+ )}
+
+ {isSuccessMfa && isPaidPlan && (
+ <Form_Shadcn_ {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)}>
+ <Card>
+ <CardContent>
+ <FormField_Shadcn_
+ control={form.control}
+ name="enforceMfa"
+ render={({ field }) => (
+ <FormItemLayout
+ layout="flex-row-reverse"
+ label="Require MFA to access organization"
+ description="Team members must have MFA enabled and a valid MFA session to access the organization and any projects."
+ >
+ <FormControl_Shadcn_>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ disabled={
+ !isPaidPlan ||
+ !canUpdateMfaConfig ||
+ !hasMFAEnabled ||
+ isUpdatingMfa
+ }
+ />
+ </div>
+ </TooltipTrigger>
+ {(!canUpdateMfaConfig || !hasMFAEnabled) && (
+ <TooltipContent side="bottom">
+ {!canUpdateMfaConfig ? (
+ "You don't have permission to update MFA settings"
+ ) : (
+ <>
+ <InlineLink href="/account/security">Enable MFA</InlineLink>{' '}
+ on your own account first
+ </>
+ )}
+ </TooltipContent>
+ )}
+ </Tooltip>
+ </FormControl_Shadcn_>
+ </FormItemLayout>
+ )}
+ />
+ </CardContent>
+ <CardFooter className="justify-end space-x-2">
+ {form.formState.isDirty && (
+ <Button
+ type="default"
+ disabled={isLoadingMfa || isUpdatingMfa}
+ onClick={() => form.reset({ enforceMfa: isPaidPlan ? mfaConfig : false })}
+ >
+ Cancel
+ </Button>
+ )}
+ <Button
+ type="primary"
+ htmlType="submit"
+ disabled={
+ !isPaidPlan ||
+ !canUpdateMfaConfig ||
+ isUpdatingMfa ||
+ isLoadingMfa ||
+ !form.formState.isDirty
+ }
+ loading={isUpdatingMfa}
+ >
+ Save changes
+ </Button>
+ </CardFooter>
+ </Card>
+ </form>
+ </Form_Shadcn_>
+ )}
+ </>
+ )}
+ </ScaffoldSection>
+ </ScaffoldContainer>
)
}
-
-export default SecuritySettings
diff --git a/apps/studio/components/interfaces/Organization/TeamSettings/MemberActions.tsx b/apps/studio/components/interfaces/Organization/TeamSettings/MemberActions.tsx
index 9b3108a1f30..24b1a8a9fed 100644
--- a/apps/studio/components/interfaces/Organization/TeamSettings/MemberActions.tsx
+++ b/apps/studio/components/interfaces/Organization/TeamSettings/MemberActions.tsx
@@ -1,5 +1,5 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { MoreVertical, Trash } from 'lucide-react'
+import { MoreVertical, Redo2, Trash } from 'lucide-react'
import { useState } from 'react'
import { toast } from 'sonner'
@@ -16,7 +16,7 @@ import {
} from 'data/organizations/organization-members-query'
import { usePermissionsQuery } from 'data/permissions/permissions-query'
import { useProjectsQuery } from 'data/projects/projects-query'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { useProfile } from 'lib/profile'
@@ -68,14 +68,20 @@ export const MemberActions = ({ member }: MemberActionsProps) => {
const roleId = member.role_ids?.[0] ?? -1
const canRemoveMember = member.role_ids.every((id) => rolesRemovable.includes(id))
- const canResendInvite =
- useCheckPermissions(PermissionAction.CREATE, 'user_invites', {
- resource: { role_id: roleId },
- }) && hasOrgRole
- const canRevokeInvite =
- useCheckPermissions(PermissionAction.DELETE, 'user_invites', {
- resource: { role_id: roleId },
- }) && hasOrgRole
+
+ const { can: canCreateUserInvites } = useAsyncCheckProjectPermissions(
+ PermissionAction.CREATE,
+ 'user_invites',
+ { resource: { role_id: roleId } }
+ )
+ const canResendInvite = canCreateUserInvites && hasOrgRole
+
+ const { can: canDeleteUserInvites } = useAsyncCheckProjectPermissions(
+ PermissionAction.DELETE,
+ 'user_invites',
+ { resource: { role_id: roleId } }
+ )
+ const canRevokeInvite = canDeleteUserInvites && hasOrgRole
const { mutate: deleteOrganizationMember, isLoading: isDeletingMember } =
useOrganizationMemberDeleteMutation({
@@ -193,30 +199,34 @@ export const MemberActions = ({ member }: MemberActionsProps) => {
<>
<DropdownMenuItemTooltip
className="gap-x-2"
- disabled={!canRevokeInvite}
- onClick={() => handleRevokeInvitation(member)}
+ disabled={!canResendInvite}
+ onClick={() => handleResendInvite(member)}
tooltip={{
content: {
side: 'left',
- text: 'Additional permissions required to cancel invitation',
+ text: 'Additional permissions required to resend invitation',
},
}}
>
- <p>Cancel invitation</p>
+ <Redo2 size={14} />
+ <p>Resend invitation</p>
</DropdownMenuItemTooltip>
+
<DropdownMenuSeparator />
+
<DropdownMenuItemTooltip
className="gap-x-2"
- disabled={!canResendInvite}
- onClick={() => handleResendInvite(member)}
+ disabled={!canRevokeInvite}
+ onClick={() => handleRevokeInvitation(member)}
tooltip={{
content: {
side: 'left',
- text: 'Additional permissions required to resend invitation',
+ text: 'Additional permissions required to cancel invitation',
},
}}
>
- <p>Resend invitation</p>
+ <Trash size={14} />
+ <p>Cancel invitation</p>
</DropdownMenuItemTooltip>
</>
) : (
diff --git a/apps/studio/components/interfaces/Organization/Usage/Usage.tsx b/apps/studio/components/interfaces/Organization/Usage/Usage.tsx
index e1a51f97387..d26883fc670 100644
--- a/apps/studio/components/interfaces/Organization/Usage/Usage.tsx
+++ b/apps/studio/components/interfaces/Organization/Usage/Usage.tsx
@@ -11,7 +11,7 @@ import NoPermission from 'components/ui/NoPermission'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { useProjectsQuery } from 'data/projects/projects-query'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { TIME_PERIODS_BILLING, TIME_PERIODS_REPORTS } from 'lib/constants/metrics'
import {
@@ -31,7 +31,7 @@ import Egress from './Egress'
import SizeAndCounts from './SizeAndCounts'
import { TotalUsage } from './TotalUsage'
-const Usage = () => {
+export const Usage = () => {
const { slug, projectRef } = useParams()
const [dateRange, setDateRange] = useState<any>()
const [selectedProjectRefInputValue, setSelectedProjectRefInputValue] = useState<
@@ -43,10 +43,8 @@ const Usage = () => {
const selectedProjectRef =
selectedProjectRefInputValue === 'all-projects' ? undefined : selectedProjectRefInputValue
- const canReadSubscriptions = useCheckPermissions(
- PermissionAction.BILLING_READ,
- 'stripe.subscriptions'
- )
+ const { can: canReadSubscriptions, isLoading: isLoadingPermissions } =
+ useAsyncCheckProjectPermissions(PermissionAction.BILLING_READ, 'stripe.subscriptions')
const { data: organization } = useSelectedOrganizationQuery()
const { data, isSuccess } = useProjectsQuery()
@@ -62,16 +60,6 @@ const Usage = () => {
(project) => project.organization_id === organization?.id
)
- useEffect(() => {
- if (projectRef && isSuccess && orgProjects !== undefined) {
- if (orgProjects.find((project) => project.ref === projectRef)) {
- setSelectedProjectRefInputValue(projectRef)
- }
- }
- // [Joshen] Since we're already looking at isSuccess
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [projectRef, isSuccess])
-
const billingCycleStart = useMemo(() => {
return dayjs.unix(subscription?.current_period_start ?? 0).utc()
}, [subscription])
@@ -119,15 +107,15 @@ const Usage = () => {
? orgProjects?.find((it) => it.ref === selectedProjectRef)
: undefined
- if (!canReadSubscriptions) {
- return (
- <ScaffoldHeader>
- <ScaffoldContainer>
- <NoPermission resourceText="view organization usage" />
- </ScaffoldContainer>
- </ScaffoldHeader>
- )
- }
+ useEffect(() => {
+ if (projectRef && isSuccess && orgProjects !== undefined) {
+ if (orgProjects.find((project) => project.ref === projectRef)) {
+ setSelectedProjectRefInputValue(projectRef)
+ }
+ }
+ // [Joshen] Since we're already looking at isSuccess
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [projectRef, isSuccess])
return (
<>
@@ -139,7 +127,7 @@ const Usage = () => {
<div className="sticky top-0 border-b bg-sidebar z-[1] overflow-hidden">
<ScaffoldContainer>
<div className="py-4 flex items-center space-x-4">
- {isLoadingSubscription && (
+ {isLoadingSubscription || isLoadingPermissions ? (
<div className="flex lg:items-center items-start gap-3 flex-col lg:flex-row lg:justify-between w-full">
<div className="flex items-center gap-2">
<ShimmeringLoader className="w-48" />
@@ -147,7 +135,9 @@ const Usage = () => {
</div>
<ShimmeringLoader className="w-[280px]" />
</div>
- )}
+ ) : !canReadSubscriptions ? (
+ <NoPermission resourceText="view organization usage" />
+ ) : null}
{isErrorSubscription && (
<AlertError
@@ -312,5 +302,3 @@ const Usage = () => {
</>
)
}
-
-export default Usage
diff --git a/apps/studio/components/interfaces/Organization/index.ts b/apps/studio/components/interfaces/Organization/index.ts
index 31287315dc0..6d2f34a57da 100644
--- a/apps/studio/components/interfaces/Organization/index.ts
+++ b/apps/studio/components/interfaces/Organization/index.ts
@@ -1,9 +1,4 @@
-export { default as AuditLogs } from './AuditLogs/AuditLogs'
export { default as Documents } from './Documents/Documents'
-export { default as GeneralSettings } from './GeneralSettings/GeneralSettings'
-export { default as SecuritySettings } from './SecuritySettings/SecuritySettings'
export { default as IntegrationSettings } from './IntegrationSettings/IntegrationSettings'
export { default as InvoicesSettings } from './InvoicesSettings/InvoicesSettings'
export { default as NewOrgForm } from './NewOrg/NewOrgForm'
-export { default as OAuthApps } from './OAuthApps/OAuthApps'
-export { default as Usage } from './Usage/Usage'
diff --git a/apps/studio/components/layouts/ProjectLayout/OrganizationSettingsLayout.tsx b/apps/studio/components/layouts/ProjectLayout/OrganizationSettingsLayout.tsx
index eff4dd29ec7..848edfc8dac 100644
--- a/apps/studio/components/layouts/ProjectLayout/OrganizationSettingsLayout.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/OrganizationSettingsLayout.tsx
@@ -12,20 +12,6 @@ function OrganizationSettingsLayout({ children }: PropsWithChildren) {
const fullCurrentPath = useCurrentPath()
const [currentPath] = fullCurrentPath.split('#')
- // Hide these settings in the new layout on the following paths
- const isHidden = (path: string) => {
- return (
- path === `/org/${slug}/team` ||
- path === `/org/${slug}/integrations` ||
- path === `/org/${slug}/usage` ||
- path === `/org/${slug}/billing`
- )
- }
-
- if (isHidden(currentPath)) {
- return children
- }
-
const navMenuItems = [
{
label: 'General',
diff --git a/apps/studio/components/layouts/TableEditorLayout/TableEditorLayout.tsx b/apps/studio/components/layouts/TableEditorLayout/TableEditorLayout.tsx
index 656f395ae4e..2727eb42028 100644
--- a/apps/studio/components/layouts/TableEditorLayout/TableEditorLayout.tsx
+++ b/apps/studio/components/layouts/TableEditorLayout/TableEditorLayout.tsx
@@ -2,15 +2,11 @@ import { PermissionAction } from '@supabase/shared-types/out/constants'
import { PropsWithChildren } from 'react'
import NoPermission from 'components/ui/NoPermission'
-import {
- useAsyncCheckProjectPermissions,
- usePermissionsLoaded,
-} from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { ProjectLayoutWithAuth } from '../ProjectLayout/ProjectLayout'
const TableEditorLayout = ({ children }: PropsWithChildren<{}>) => {
- const isPermissionsLoaded = usePermissionsLoaded()
- const { can: canReadTables } = useAsyncCheckProjectPermissions(
+ const { can: canReadTables, isSuccess: isPermissionsLoaded } = useAsyncCheckProjectPermissions(
PermissionAction.TENANT_SQL_ADMIN_READ,
'tables'
)
diff --git a/apps/studio/components/ui/AIAssistantPanel/AIOptInModal.tsx b/apps/studio/components/ui/AIAssistantPanel/AIOptInModal.tsx
index 1b09490417d..919b847f50b 100644
--- a/apps/studio/components/ui/AIAssistantPanel/AIOptInModal.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/AIOptInModal.tsx
@@ -3,7 +3,7 @@ import { useEffect } from 'react'
import { AIOptInLevelSelector } from 'components/interfaces/Organization/GeneralSettings/AIOptInLevelSelector'
import { useAIOptInForm } from 'hooks/forms/useAIOptInForm'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import {
Button,
cn,
@@ -24,7 +24,10 @@ interface AIOptInModalProps {
export const AIOptInModal = ({ visible, onCancel }: AIOptInModalProps) => {
const { form, onSubmit, isUpdating, currentOptInLevel } = useAIOptInForm(onCancel)
- const canUpdateOrganization = useCheckPermissions(PermissionAction.UPDATE, 'organizations')
+ const { can: canUpdateOrganization } = useAsyncCheckProjectPermissions(
+ PermissionAction.UPDATE,
+ 'organizations'
+ )
const onOpenChange = (open: boolean) => {
if (!open) {
diff --git a/apps/studio/data/organizations/organization-customer-profile-query.ts b/apps/studio/data/organizations/organization-customer-profile-query.ts
index 0780ba21277..b95c9a7a15e 100644
--- a/apps/studio/data/organizations/organization-customer-profile-query.ts
+++ b/apps/studio/data/organizations/organization-customer-profile-query.ts
@@ -2,7 +2,7 @@ import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useQuery, UseQueryOptions } from '@tanstack/react-query'
import { get, handleError } from 'data/fetchers'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import type { ResponseError } from 'types'
import { organizationKeys } from './keys'
@@ -43,7 +43,7 @@ export const useOrganizationCustomerProfileQuery = <TData = OrganizationCustomer
) => {
// [Joshen] Thinking it makes sense to add this check at the RQ level - prevent
// unnecessary requests, although this behaviour still needs handling on the UI
- const canReadCustomerProfile = useCheckPermissions(
+ const { can: canReadCustomerProfile } = useAsyncCheckProjectPermissions(
PermissionAction.BILLING_READ,
'stripe.customer'
)
diff --git a/apps/studio/data/organizations/organization-payment-methods-query.ts b/apps/studio/data/organizations/organization-payment-methods-query.ts
index dc59d530506..800fd895f0f 100644
--- a/apps/studio/data/organizations/organization-payment-methods-query.ts
+++ b/apps/studio/data/organizations/organization-payment-methods-query.ts
@@ -3,7 +3,7 @@ import { useQuery, UseQueryOptions } from '@tanstack/react-query'
import { components } from 'api-types'
import { get, handleError } from 'data/fetchers'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import type { ResponseError } from 'types'
import { organizationKeys } from './keys'
@@ -44,7 +44,7 @@ export const useOrganizationPaymentMethodsQuery = <TData = OrganizationPaymentMe
...options
}: UseQueryOptions<OrganizationPaymentMethodsData, OrganizationPaymentMethodsError, TData> = {}
) => {
- const canReadSubscriptions = useCheckPermissions(
+ const { can: canReadSubscriptions } = useAsyncCheckProjectPermissions(
PermissionAction.BILLING_READ,
'stripe.payment_methods'
)
diff --git a/apps/studio/data/organizations/organization-tax-id-query.ts b/apps/studio/data/organizations/organization-tax-id-query.ts
index e672b0611aa..06e7ca65896 100644
--- a/apps/studio/data/organizations/organization-tax-id-query.ts
+++ b/apps/studio/data/organizations/organization-tax-id-query.ts
@@ -3,7 +3,7 @@ import { useQuery, UseQueryOptions } from '@tanstack/react-query'
import { components } from 'api-types'
import { get, handleError } from 'data/fetchers'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import type { ResponseError } from 'types'
import { organizationKeys } from './keys'
@@ -36,7 +36,11 @@ export const useOrganizationTaxIdQuery = <TData = OrganizationTaxIdData>(
...options
}: UseQueryOptions<OrganizationTaxIdData, OrganizationTaxIdError, TData> = {}
) => {
- const canReadSubscriptions = useCheckPermissions(PermissionAction.BILLING_READ, 'stripe.tax_ids')
+ const { can: canReadSubscriptions } = useAsyncCheckProjectPermissions(
+ PermissionAction.BILLING_READ,
+ 'stripe.tax_ids'
+ )
+
return useQuery<OrganizationTaxIdData, OrganizationTaxIdError, TData>(
organizationKeys.taxId(slug),
({ signal }) => getOrganizationTaxId({ slug }, signal),
diff --git a/apps/studio/data/storage/iceberg-wrapper-create-mutation.ts b/apps/studio/data/storage/iceberg-wrapper-create-mutation.ts
index 0601d3e87a4..ed59e90e08c 100644
--- a/apps/studio/data/storage/iceberg-wrapper-create-mutation.ts
+++ b/apps/studio/data/storage/iceberg-wrapper-create-mutation.ts
@@ -9,7 +9,7 @@ import {
import { getKeys, useAPIKeysQuery } from 'data/api-keys/api-keys-query'
import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { FDWCreateVariables, useFDWCreateMutation } from 'data/fdw/fdw-create-mutation'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { useS3AccessKeyCreateMutation } from './s3-access-key-create-mutation'
@@ -27,7 +27,10 @@ export const useIcebergWrapperCreateMutation = () => {
const wrapperMeta = WRAPPERS.find((wrapper) => wrapper.name === 'iceberg_wrapper')
- const canCreateCredentials = useCheckPermissions(PermissionAction.STORAGE_ADMIN_WRITE, '*')
+ const { can: canCreateCredentials } = useAsyncCheckProjectPermissions(
+ PermissionAction.STORAGE_ADMIN_WRITE,
+ '*'
+ )
const { mutateAsync: createS3AccessKey, isLoading: isCreatingS3AccessKey } =
useS3AccessKeyCreateMutation()
diff --git a/apps/studio/data/subscriptions/org-plans-query.ts b/apps/studio/data/subscriptions/org-plans-query.ts
index 77c98d2c630..a79e76e9527 100644
--- a/apps/studio/data/subscriptions/org-plans-query.ts
+++ b/apps/studio/data/subscriptions/org-plans-query.ts
@@ -1,8 +1,9 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useQuery, UseQueryOptions } from '@tanstack/react-query'
+
import { get, handleError } from 'data/fetchers'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { subscriptionKeys } from './keys'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { PermissionAction } from '@supabase/shared-types/out/constants'
export type OrgPlansVariables = {
orgSlug?: string
@@ -26,7 +27,7 @@ export const useOrgPlansQuery = <TData = OrgPlansData>(
{ orgSlug }: OrgPlansVariables,
{ enabled = true, ...options }: UseQueryOptions<OrgPlansData, OrgPlansError, TData> = {}
) => {
- const canReadSubscriptions = useCheckPermissions(
+ const { can: canReadSubscriptions } = useAsyncCheckProjectPermissions(
PermissionAction.BILLING_READ,
'stripe.subscriptions'
)
diff --git a/apps/studio/data/subscriptions/org-subscription-query.ts b/apps/studio/data/subscriptions/org-subscription-query.ts
index 26b68114612..a91e6f29e7f 100644
--- a/apps/studio/data/subscriptions/org-subscription-query.ts
+++ b/apps/studio/data/subscriptions/org-subscription-query.ts
@@ -2,7 +2,7 @@ import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useQuery, UseQueryOptions } from '@tanstack/react-query'
import { get, handleError } from 'data/fetchers'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import type { ResponseError } from 'types'
import { subscriptionKeys } from './keys'
@@ -37,7 +37,7 @@ export const useOrgSubscriptionQuery = <TData = OrgSubscriptionData>(
) => {
// [Joshen] Thinking it makes sense to add this check at the RQ level - prevent
// unnecessary requests, although this behaviour still needs handling on the UI
- const canReadSubscriptions = useCheckPermissions(
+ const { can: canReadSubscriptions } = useAsyncCheckProjectPermissions(
PermissionAction.BILLING_READ,
'stripe.subscriptions'
)
diff --git a/apps/studio/hooks/forms/useAIOptInForm.ts b/apps/studio/hooks/forms/useAIOptInForm.ts
index bd602497bb7..9a85468fb17 100644
--- a/apps/studio/hooks/forms/useAIOptInForm.ts
+++ b/apps/studio/hooks/forms/useAIOptInForm.ts
@@ -8,7 +8,7 @@ import * as z from 'zod'
import { LOCAL_STORAGE_KEYS } from 'common'
import { useOrganizationUpdateMutation } from 'data/organizations/organization-update-mutation'
import { invalidateOrganizationsQuery } from 'data/organizations/organizations-query'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
import { getAiOptInLevel } from 'hooks/misc/useOrgOptedIntoAi'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
@@ -31,7 +31,10 @@ export type AIOptInFormValues = z.infer<typeof AIOptInSchema>
export const useAIOptInForm = (onSuccessCallback?: () => void) => {
const queryClient = useQueryClient()
const { data: selectedOrganization } = useSelectedOrganizationQuery()
- const canUpdateOrganization = useCheckPermissions(PermissionAction.UPDATE, 'organizations')
+ const { can: canUpdateOrganization } = useAsyncCheckProjectPermissions(
+ PermissionAction.UPDATE,
+ 'organizations'
+ )
const [_, setUpdatedOptInSinceMCP] = useLocalStorageQuery(
LOCAL_STORAGE_KEYS.AI_ASSISTANT_MCP_OPT_IN,
diff --git a/apps/studio/hooks/misc/useCheckPermissions.ts b/apps/studio/hooks/misc/useCheckPermissions.ts
index 9ebf33696fb..15437b5f3c9 100644
--- a/apps/studio/hooks/misc/useCheckPermissions.ts
+++ b/apps/studio/hooks/misc/useCheckPermissions.ts
@@ -89,40 +89,42 @@ export function useGetProjectPermissions(
})
const permissions = permissionsOverride === undefined ? data : permissionsOverride
- const organizationsQueryEnabled = organizationSlugOverride === undefined && enabled
+ const getOrganizationDataFromParamsSlug = organizationSlugOverride === undefined && enabled
const {
data: organizationData,
isLoading: isLoadingOrganization,
isSuccess: isSuccessOrganization,
} = useSelectedOrganizationQuery({
- enabled: organizationsQueryEnabled,
+ enabled: getOrganizationDataFromParamsSlug,
})
const organization =
organizationSlugOverride === undefined ? organizationData : { slug: organizationSlugOverride }
const organizationSlug = organization?.slug
- const projectsQueryEnabled = projectRefOverride === undefined && enabled
+ const { ref: urlProjectRef } = useParams()
+ const getProjectDataFromParamsRef = !!urlProjectRef && projectRefOverride === undefined && enabled
const {
data: projectData,
isLoading: isLoadingProject,
isSuccess: isSuccessProject,
} = useSelectedProjectQuery({
- enabled: projectsQueryEnabled,
+ enabled: getProjectDataFromParamsRef,
})
const project =
projectRefOverride === undefined || projectData?.parent_project_ref
? projectData
: { ref: projectRefOverride, parent_project_ref: undefined }
+
const projectRef = project?.parent_project_ref ? project.parent_project_ref : project?.ref
const isLoading =
isLoadingPermissions ||
- (organizationsQueryEnabled && isLoadingOrganization) ||
- (projectsQueryEnabled && isLoadingProject)
+ (getOrganizationDataFromParamsSlug && isLoadingOrganization) ||
+ (getProjectDataFromParamsRef && isLoadingProject)
const isSuccess =
isSuccessPermissions &&
- (!organizationsQueryEnabled || isSuccessOrganization) &&
- (!projectsQueryEnabled || isSuccessProject)
+ (!getOrganizationDataFromParamsSlug || isSuccessOrganization) &&
+ (!getProjectDataFromParamsRef || isSuccessProject)
return {
permissions,
@@ -138,6 +140,7 @@ export function useGetProjectPermissions(
* check for loading states to not prematurely show "no perms" UIs. We'll also need a separate async check for org perms too
*
* Use `import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'` instead
+ * [Joshen] No longer being used, can be deprecated in follow up PR
*/
export function useCheckPermissions(
action: string,
@@ -180,6 +183,7 @@ export function useCheckProjectPermissions(
return doPermissionsCheck(allPermissions, action, resource, data, _organizationSlug, _projectRef)
}
+/** [Joshen] No longer being used, can be deprecated in follow up PR */
export function usePermissionsLoaded() {
const isLoggedIn = useIsLoggedIn()
const { isFetched: isPermissionsFetched } = usePermissionsQuery({ enabled: isLoggedIn })
@@ -200,6 +204,7 @@ export function usePermissionsLoaded() {
return isLoggedIn && isPermissionsFetched && isOrganizationsFetched
}
+/** [Joshen] To be renamed to be useAsyncCheckPermissions, more generic as it covers both org and project perms */
// Useful when you want to avoid layout changes while waiting for permissions to load
export function useAsyncCheckProjectPermissions(
action: string,
diff --git a/apps/studio/pages/new/[slug].tsx b/apps/studio/pages/new/[slug].tsx
index 297dc3d709d..beaa6dacab5 100644
--- a/apps/studio/pages/new/[slug].tsx
+++ b/apps/studio/pages/new/[slug].tsx
@@ -49,7 +49,7 @@ import {
import { useProjectsQuery } from 'data/projects/projects-query'
import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
import { useCustomContent } from 'hooks/custom-content/useCustomContent'
-import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { useAsyncCheckProjectPermissions } from 'hooks/misc/useCheckPermissions'
import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'
import { useLocalStorageQuery } from 'hooks/misc/useLocalStorage'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
@@ -260,7 +260,7 @@ const Wizard: NextPageWithLayout = () => {
? availableRegionsData?.recommendations.smartGroup.name
: _defaultRegion
- const isAdmin = useCheckPermissions(PermissionAction.CREATE, 'projects')
+ const { can: isAdmin } = useAsyncCheckProjectPermissions(PermissionAction.CREATE, 'projects')
const isInvalidSlug = isOrganizationsSuccess && currentOrg === undefined
const orgNotFound = isOrganizationsSuccess && (organizations?.length ?? 0) > 0 && isInvalidSlug
diff --git a/apps/studio/pages/org/[slug]/apps.tsx b/apps/studio/pages/org/[slug]/apps.tsx
index 616f81fca04..bbbfad68bf6 100644
--- a/apps/studio/pages/org/[slug]/apps.tsx
+++ b/apps/studio/pages/org/[slug]/apps.tsx
@@ -1,19 +1,11 @@
-import { OAuthApps } from 'components/interfaces/Organization'
+import { OAuthApps } from 'components/interfaces/Organization/OAuthApps/OAuthApps'
import DefaultLayout from 'components/layouts/DefaultLayout'
import OrganizationLayout from 'components/layouts/OrganizationLayout'
import OrganizationSettingsLayout from 'components/layouts/ProjectLayout/OrganizationSettingsLayout'
-import { Loading } from 'components/ui/Loading'
-import { usePermissionsQuery } from 'data/permissions/permissions-query'
-import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import type { NextPageWithLayout } from 'types'
const OrgOAuthApps: NextPageWithLayout = () => {
- const { data: selectedOrganization } = useSelectedOrganizationQuery()
- const { isLoading: isLoadingPermissions } = usePermissionsQuery()
-
- return (
- <>{selectedOrganization === undefined && isLoadingPermissions ? <Loading /> : <OAuthApps />}</>
- )
+ return <OAuthApps />
}
OrgOAuthApps.getLayout = (page) => (
diff --git a/apps/studio/pages/org/[slug]/audit.tsx b/apps/studio/pages/org/[slug]/audit.tsx
index 0baf587a80f..42a813754af 100644
--- a/apps/studio/pages/org/[slug]/audit.tsx
+++ b/apps/studio/pages/org/[slug]/audit.tsx
@@ -1,4 +1,4 @@
-import { AuditLogs } from 'components/interfaces/Organization'
+import { AuditLogs } from 'components/interfaces/Organization/AuditLogs/AuditLogs'
import DefaultLayout from 'components/layouts/DefaultLayout'
import OrganizationLayout from 'components/layouts/OrganizationLayout'
import OrganizationSettingsLayout from 'components/layouts/ProjectLayout/OrganizationSettingsLayout'
diff --git a/apps/studio/pages/org/[slug]/billing.tsx b/apps/studio/pages/org/[slug]/billing.tsx
index 6d692fa5fcf..90bbae48793 100644
--- a/apps/studio/pages/org/[slug]/billing.tsx
+++ b/apps/studio/pages/org/[slug]/billing.tsx
@@ -4,7 +4,6 @@ import { useParams } from 'common'
import { BillingSettings } from 'components/interfaces/Organization/BillingSettings/BillingSettings'
import DefaultLayout from 'components/layouts/DefaultLayout'
import OrganizationLayout from 'components/layouts/OrganizationLayout'
-import OrganizationSettingsLayout from 'components/layouts/ProjectLayout/OrganizationSettingsLayout'
import { UnknownInterface } from 'components/ui/UnknownInterface'
import { useIsFeatureEnabled } from 'hooks/misc/useIsFeatureEnabled'
import {
@@ -37,9 +36,7 @@ const OrgBillingSettings: NextPageWithLayout = () => {
OrgBillingSettings.getLayout = (page) => (
<DefaultLayout>
- <OrganizationLayout>
- <OrganizationSettingsLayout>{page}</OrganizationSettingsLayout>
- </OrganizationLayout>
+ <OrganizationLayout>{page}</OrganizationLayout>
</DefaultLayout>
)
export default OrgBillingSettings
diff --git a/apps/studio/pages/org/[slug]/general.tsx b/apps/studio/pages/org/[slug]/general.tsx
index 73670d676f2..1bdcce2af5b 100644
--- a/apps/studio/pages/org/[slug]/general.tsx
+++ b/apps/studio/pages/org/[slug]/general.tsx
@@ -1,4 +1,4 @@
-import { GeneralSettings as GeneralSettingsLegacy } from 'components/interfaces/Organization'
+import { GeneralSettings } from 'components/interfaces/Organization/GeneralSettings/GeneralSettings'
import DefaultLayout from 'components/layouts/DefaultLayout'
import OrganizationLayout from 'components/layouts/OrganizationLayout'
import OrganizationSettingsLayout from 'components/layouts/ProjectLayout/OrganizationSettingsLayout'
@@ -16,7 +16,7 @@ const OrgGeneralSettings: NextPageWithLayout = () => {
{selectedOrganization === undefined && isLoadingPermissions ? (
<Loading />
) : (
- <GeneralSettingsLegacy />
+ <GeneralSettings />
)}
</>
)
diff --git a/apps/studio/pages/org/[slug]/integrations.tsx b/apps/studio/pages/org/[slug]/integrations.tsx
index 39964b49f0e..69990a65094 100644
--- a/apps/studio/pages/org/[slug]/integrations.tsx
+++ b/apps/studio/pages/org/[slug]/integrations.tsx
@@ -1,8 +1,6 @@
import { IntegrationSettings } from 'components/interfaces/Organization'
-import AppLayout from 'components/layouts/AppLayout/AppLayout'
import DefaultLayout from 'components/layouts/DefaultLayout'
import OrganizationLayout from 'components/layouts/OrganizationLayout'
-import OrganizationSettingsLayout from 'components/layouts/ProjectLayout/OrganizationSettingsLayout'
import type { NextPageWithLayout } from 'types'
const OrgIntegrationSettings: NextPageWithLayout = () => {
@@ -11,9 +9,7 @@ const OrgIntegrationSettings: NextPageWithLayout = () => {
OrgIntegrationSettings.getLayout = (page) => (
<DefaultLayout>
- <OrganizationLayout>
- <OrganizationSettingsLayout>{page}</OrganizationSettingsLayout>
- </OrganizationLayout>
+ <OrganizationLayout>{page}</OrganizationLayout>
</DefaultLayout>
)
diff --git a/apps/studio/pages/org/[slug]/security.tsx b/apps/studio/pages/org/[slug]/security.tsx
index 93bf795e639..4948e3e1d34 100644
--- a/apps/studio/pages/org/[slug]/security.tsx
+++ b/apps/studio/pages/org/[slug]/security.tsx
@@ -1,25 +1,11 @@
-import { SecuritySettings } from 'components/interfaces/Organization'
+import { SecuritySettings } from 'components/interfaces/Organization/SecuritySettings/SecuritySettings'
import DefaultLayout from 'components/layouts/DefaultLayout'
import OrganizationLayout from 'components/layouts/OrganizationLayout'
import OrganizationSettingsLayout from 'components/layouts/ProjectLayout/OrganizationSettingsLayout'
-import { Loading } from 'components/ui/Loading'
-import { usePermissionsQuery } from 'data/permissions/permissions-query'
-import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import type { NextPageWithLayout } from 'types'
const OrgGeneralSettings: NextPageWithLayout = () => {
- const { isLoading: isLoadingPermissions } = usePermissionsQuery()
- const { data: selectedOrganization } = useSelectedOrganizationQuery()
-
- return (
- <>
- {selectedOrganization === undefined && isLoadingPermissions ? (
- <Loading />
- ) : (
- <SecuritySettings />
- )}
- </>
- )
+ return <SecuritySettings />
}
OrgGeneralSettings.getLayout = (page) => (
diff --git a/apps/studio/pages/org/[slug]/team.tsx b/apps/studio/pages/org/[slug]/team.tsx
index aef184ae3a8..36039aebd48 100644
--- a/apps/studio/pages/org/[slug]/team.tsx
+++ b/apps/studio/pages/org/[slug]/team.tsx
@@ -1,7 +1,6 @@
import { TeamSettings } from 'components/interfaces/Organization/TeamSettings/TeamSettings'
import DefaultLayout from 'components/layouts/DefaultLayout'
import OrganizationLayout from 'components/layouts/OrganizationLayout'
-import OrganizationSettingsLayout from 'components/layouts/ProjectLayout/OrganizationSettingsLayout'
import { Loading } from 'components/ui/Loading'
import { usePermissionsQuery } from 'data/permissions/permissions-query'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
@@ -16,9 +15,7 @@ const OrgTeamSettings: NextPageWithLayout = () => {
OrgTeamSettings.getLayout = (page) => (
<DefaultLayout>
- <OrganizationLayout>
- <OrganizationSettingsLayout>{page}</OrganizationSettingsLayout>
- </OrganizationLayout>
+ <OrganizationLayout>{page}</OrganizationLayout>
</DefaultLayout>
)
diff --git a/apps/studio/pages/org/[slug]/usage.tsx b/apps/studio/pages/org/[slug]/usage.tsx
index 9936b9e1a7a..3f803525bc5 100644
--- a/apps/studio/pages/org/[slug]/usage.tsx
+++ b/apps/studio/pages/org/[slug]/usage.tsx
@@ -1,24 +1,15 @@
-import { Usage } from 'components/interfaces/Organization'
+import { Usage } from 'components/interfaces/Organization/Usage/Usage'
import DefaultLayout from 'components/layouts/DefaultLayout'
import OrganizationLayout from 'components/layouts/OrganizationLayout'
-import OrganizationSettingsLayout from 'components/layouts/ProjectLayout/OrganizationSettingsLayout'
-import { Loading } from 'components/ui/Loading'
-import { usePermissionsQuery } from 'data/permissions/permissions-query'
-import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import type { NextPageWithLayout } from 'types'
const OrgUsage: NextPageWithLayout = () => {
- const { isLoading: isLoadingPermissions } = usePermissionsQuery()
- const { data: selectedOrganization } = useSelectedOrganizationQuery()
-
- return <>{selectedOrganization === undefined && isLoadingPermissions ? <Loading /> : <Usage />}</>
+ return <Usage />
}
OrgUsage.getLayout = (page) => (
<DefaultLayout>
- <OrganizationLayout>
- <OrganizationSettingsLayout>{page}</OrganizationSettingsLayout>
- </OrganizationLayout>
+ <OrganizationLayout>{page}</OrganizationLayout>
</DefaultLayout>
)