Skip to content

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

Chore/add perms check in projects api query (#30025)

Joshen Limcb5ae761f343
diff --git a/apps/studio/components/interfaces/App/CommandMenu/ApiKeys.tsx b/apps/studio/components/interfaces/App/CommandMenu/ApiKeys.tsx
index a3c3f2909a8..c86051bba3f 100644
--- a/apps/studio/components/interfaces/App/CommandMenu/ApiKeys.tsx
+++ b/apps/studio/components/interfaces/App/CommandMenu/ApiKeys.tsx
@@ -1,7 +1,7 @@
import { Key } from 'lucide-react'
import { useMemo } from 'react'
-import { useProjectApiQuery } from 'data/config/project-api-query'
+import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { copyToClipboard } from 'lib/helpers'
import { Badge } from 'ui'
@@ -23,14 +23,13 @@ export function useApiKeysCommands() {
const setPage = useSetPage()
const project = useSelectedProject()
- const { data: settings } = useProjectApiQuery(
+ const ref = project?.ref || '_'
+
+ const { data: settings } = useProjectSettingsV2Query(
{ projectRef: project?.ref },
{ enabled: !!project }
)
- const ref = project?.ref || '_'
-
- const anonKey = settings?.autoApiService?.defaultApiKey ?? undefined
- const serviceKey = settings?.autoApiService?.serviceApiKey ?? undefined
+ const { anonKey, serviceKey } = getAPIKeys(settings)
const commands = useMemo(
() =>
@@ -40,7 +39,7 @@ export function useApiKeysCommands() {
id: 'anon-key',
name: `Copy anonymous API key`,
action: () => {
- copyToClipboard(anonKey ?? '')
+ copyToClipboard(anonKey.api_key ?? '')
setIsOpen(false)
},
badge: () => (
@@ -56,7 +55,7 @@ export function useApiKeysCommands() {
id: 'service-key',
name: `Copy service API key`,
action: () => {
- copyToClipboard(serviceKey ?? '')
+ copyToClipboard(serviceKey.api_key ?? '')
setIsOpen(false)
},
badge: () => (
diff --git a/apps/studio/components/interfaces/App/CommandMenu/ApiUrl.tsx b/apps/studio/components/interfaces/App/CommandMenu/ApiUrl.tsx
index 28b36682981..1205a8f3333 100644
--- a/apps/studio/components/interfaces/App/CommandMenu/ApiUrl.tsx
+++ b/apps/studio/components/interfaces/App/CommandMenu/ApiUrl.tsx
@@ -1,10 +1,10 @@
import { Link } from 'lucide-react'
-import { useProjectApiQuery } from 'data/config/project-api-query'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
+import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { copyToClipboard } from 'lib/helpers'
import { Badge } from 'ui'
import { useRegisterCommands, useSetCommandMenuOpen } from 'ui-patterns/CommandMenu'
-import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { COMMAND_MENU_SECTIONS } from './CommandMenu.utils'
import { orderCommandSectionsByPriority } from './ordering'
@@ -12,13 +12,13 @@ export function useApiUrlCommand() {
const setIsOpen = useSetCommandMenuOpen()
const project = useSelectedProject()
- const { data: settings } = useProjectApiQuery(
+ const { data: settings } = useProjectSettingsV2Query(
{ projectRef: project?.ref },
{ enabled: !!project }
)
- const apiUrl = settings?.autoApiService.endpoint
- ? `${settings.autoApiService.protocol ?? 'https'}://${settings.autoApiService.endpoint}`
+ const apiUrl = settings?.app_config?.endpoint
+ ? `https://${settings.app_config.endpoint}`
: undefined
useRegisterCommands(
diff --git a/apps/studio/components/interfaces/Auth/Users/BanUserModal.tsx b/apps/studio/components/interfaces/Auth/Users/BanUserModal.tsx
index 1ae878d8855..d246cd04cd5 100644
--- a/apps/studio/components/interfaces/Auth/Users/BanUserModal.tsx
+++ b/apps/studio/components/interfaces/Auth/Users/BanUserModal.tsx
@@ -1,10 +1,14 @@
import { zodResolver } from '@hookform/resolvers/zod'
import dayjs from 'dayjs'
+import { useEffect } from 'react'
import { useForm } from 'react-hook-form'
-import * as z from 'zod'
import { toast } from 'sonner'
-import { useEffect } from 'react'
+import * as z from 'zod'
+import { useParams } from 'common'
+import { useUserUpdateMutation } from 'data/auth/user-update-mutation'
+import { User } from 'data/auth/users-query'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import {
Button,
cn,
@@ -20,10 +24,6 @@ import {
Separator,
} from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
-import { useUserUpdateMutation } from 'data/auth/user-update-mutation'
-import { User } from 'data/auth/users-query'
-import { useProjectApiQuery } from 'data/config/project-api-query'
-import { useParams } from 'common'
interface BanUserModalProps {
visible: boolean
@@ -34,7 +34,7 @@ interface BanUserModalProps {
export const BanUserModal = ({ visible, user, onClose }: BanUserModalProps) => {
const { ref: projectRef } = useParams()
- const { data: apiData } = useProjectApiQuery({ projectRef })
+ const { data: settings } = useProjectSettingsV2Query({ projectRef })
const { mutate: updateUser, isLoading: isBanningUser } = useUserUpdateMutation({
onSuccess: (_, vars) => {
const bannedUntil = dayjs()
@@ -62,17 +62,24 @@ export const BanUserModal = ({ visible, user, onClose }: BanUserModalProps) => {
const bannedUntil = dayjs().add(Number(value), unit).format('DD MMM YYYY HH:mm (ZZ)')
const onSubmit = (data: FormType) => {
- if (!apiData) {
+ if (!settings) {
return toast.error(`Failed to ban user: Error loading project config`)
} else if (user.id === undefined) {
return toast.error(`Failed to ban user: User ID not found`)
}
const durationHours = data.unit === 'hours' ? Number(data.value) : Number(data.value) * 24
- const { protocol, endpoint, serviceApiKey } = apiData.autoApiService
+ const endpoint = settings.app_config?.endpoint
+ const serviceApiKey = (settings?.service_api_keys ?? []).find(
+ (x) => x.tags === 'service_role'
+ )?.api_key
+
+ if (!endpoint) return toast.error(`Failed to ban user: Unable to retrieve API endpoint`)
+ if (!serviceApiKey) return toast.error(`Failed to ban user: Unable to retrieve API key`)
+
updateUser({
projectRef,
- protocol,
+ protocol: 'https',
endpoint,
serviceApiKey,
userId: user.id,
diff --git a/apps/studio/components/interfaces/Auth/Users/CreateUserModal.tsx b/apps/studio/components/interfaces/Auth/Users/CreateUserModal.tsx
index 90d0e02b97e..3f5cdb41567 100644
--- a/apps/studio/components/interfaces/Auth/Users/CreateUserModal.tsx
+++ b/apps/studio/components/interfaces/Auth/Users/CreateUserModal.tsx
@@ -1,13 +1,13 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { useParams } from 'common'
import { Lock, Mail } from 'lucide-react'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import * as z from 'zod'
+import { useParams } from 'common'
import { useUserCreateMutation } from 'data/auth/user-create-mutation'
-import { useProjectApiQuery } from 'data/config/project-api-query'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import {
Button,
@@ -40,7 +40,11 @@ const CreateUserFormSchema = z.object({
const CreateUserModal = ({ visible, setVisible }: CreateUserModalProps) => {
const { ref: projectRef } = useParams()
- const { data, isLoading, isSuccess } = useProjectApiQuery({ projectRef }, { enabled: visible })
+ const {
+ data: settings,
+ isLoading,
+ isSuccess,
+ } = useProjectSettingsV2Query({ projectRef }, { enabled: visible })
const canCreateUsers = useCheckPermissions(PermissionAction.AUTH_EXECUTE, 'create_user')
@@ -56,8 +60,15 @@ const CreateUserModal = ({ visible, setVisible }: CreateUserModalProps) => {
if (!isSuccess) {
return toast.error(`Failed to create user: Error loading project config`)
}
- const { protocol, endpoint, serviceApiKey } = data.autoApiService
- createUser({ projectRef, endpoint, protocol, serviceApiKey, user: values })
+ const endpoint = settings?.app_config?.endpoint
+ const serviceApiKey = (settings?.service_api_keys ?? []).find(
+ (key) => key.tags === 'service_role'
+ )?.api_key
+
+ if (!endpoint) return toast.error(`Failed to create user: Unable to retrieve API endpoint`)
+ if (!serviceApiKey) return toast.error(`Failed to create user: Unable to retrieve API key`)
+
+ createUser({ projectRef, endpoint, protocol: 'https', serviceApiKey, user: values })
}
const form = useForm<z.infer<typeof CreateUserFormSchema>>({
diff --git a/apps/studio/components/interfaces/Docs/Authentication.tsx b/apps/studio/components/interfaces/Docs/Authentication.tsx
index d3a44692039..37d6840a7b0 100644
--- a/apps/studio/components/interfaces/Docs/Authentication.tsx
+++ b/apps/studio/components/interfaces/Docs/Authentication.tsx
@@ -1,24 +1,30 @@
import Link from 'next/link'
-import type { AutoApiService } from 'data/config/project-api-query'
+import { useParams } from 'common'
+import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import CodeSnippet from './CodeSnippet'
import Snippets from './Snippets'
interface AuthenticationProps {
- autoApiService: AutoApiService
selectedLang: 'bash' | 'js'
showApiKey: string
}
-const Authentication = ({ autoApiService, selectedLang, showApiKey }: AuthenticationProps) => {
+const Authentication = ({ selectedLang, showApiKey }: AuthenticationProps) => {
+ const { ref: projectRef } = useParams()
+ const { data: settings } = useProjectSettingsV2Query({ projectRef })
+
+ const { anonKey, serviceKey } = getAPIKeys(settings)
+ const endpoint = settings?.app_config?.endpoint ?? ''
+
// [Joshen] ShowApiKey should really be a boolean, its confusing
const defaultApiKey =
showApiKey !== 'SUPABASE_KEY'
- ? autoApiService?.defaultApiKey ?? 'SUPABASE_CLIENT_API_KEY'
+ ? anonKey?.api_key ?? 'SUPABASE_CLIENT_API_KEY'
: 'SUPABASE_CLIENT_API_KEY'
const serviceApiKey =
showApiKey !== 'SUPABASE_KEY'
- ? autoApiService?.serviceApiKey ?? 'SUPABASE_SERVICE_KEY'
+ ? serviceKey?.api_key ?? 'SUPABASE_SERVICE_KEY'
: 'SUPABASE_SERVICE_KEY'
return (
@@ -53,8 +59,7 @@ const Authentication = ({ autoApiService, selectedLang, showApiKey }: Authentica
<p>
We have provided you a Client Key to get started. You will soon be able to add as many
keys as you like. You can find the <code>anon</code> key in the{' '}
- <Link href={`/project/${autoApiService.project.ref}/settings/api`}>API Settings</Link>{' '}
- page.
+ <Link href={`/project/${projectRef}/settings/api`}>API Settings</Link> page.
</p>
</article>
<article className="code">
@@ -64,7 +69,7 @@ const Authentication = ({ autoApiService, selectedLang, showApiKey }: Authentica
/>
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.authKeyExample(defaultApiKey, autoApiService.endpoint, {
+ snippet={Snippets.authKeyExample(defaultApiKey, endpoint, {
showBearer: false,
})}
/>
@@ -85,8 +90,7 @@ const Authentication = ({ autoApiService, selectedLang, showApiKey }: Authentica
<p>
We have provided you with a Service Key to get started. Soon you will be able to add as
many keys as you like. You can find the <code>service_role</code> in the{' '}
- <Link href={`/project/${autoApiService.project.ref}/settings/api`}>API Settings</Link>{' '}
- page.
+ <Link href={`/project/${projectRef}/settings/api`}>API Settings</Link> page.
</p>
</article>
<article className="code">
@@ -96,9 +100,7 @@ const Authentication = ({ autoApiService, selectedLang, showApiKey }: Authentica
/>
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.authKeyExample(serviceApiKey, autoApiService.endpoint, {
- keyName: 'SERVICE_KEY',
- })}
+ snippet={Snippets.authKeyExample(serviceApiKey, endpoint, { keyName: 'SERVICE_KEY' })}
/>
</article>
</div>
diff --git a/apps/studio/components/interfaces/Docs/GeneralContent.tsx b/apps/studio/components/interfaces/Docs/GeneralContent.tsx
index cb336120919..4be9860fdcb 100644
--- a/apps/studio/components/interfaces/Docs/GeneralContent.tsx
+++ b/apps/studio/components/interfaces/Docs/GeneralContent.tsx
@@ -4,26 +4,19 @@ import TablesIntroduction from 'components/interfaces/Docs/Pages/Tables/Introduc
import UserManagement from 'components/interfaces/Docs/Pages/UserManagement'
import RpcIntroduction from 'components/interfaces/Docs/Pages/Rpc/Introduction'
-const GeneralContent = ({ autoApiService, selectedLang, page, showApiKey }: any) => {
+interface GeneralContentProps {
+ page?: string
+ selectedLang: 'bash' | 'js'
+ showApiKey: string
+}
+
+const GeneralContent = ({ selectedLang, page, showApiKey }: GeneralContentProps) => {
let selected = page?.toLowerCase()
- if (selected == 'intro' || selected == null)
- return <Introduction autoApiService={autoApiService} selectedLang={selectedLang} />
+ if (selected == 'intro' || selected == null) return <Introduction selectedLang={selectedLang} />
if (selected == 'auth')
- return (
- <Authentication
- autoApiService={autoApiService}
- selectedLang={selectedLang}
- showApiKey={showApiKey}
- />
- )
+ return <Authentication selectedLang={selectedLang} showApiKey={showApiKey} />
if (selected == 'users')
- return (
- <UserManagement
- autoApiService={autoApiService}
- selectedLang={selectedLang}
- showApiKey={showApiKey}
- />
- )
+ return <UserManagement selectedLang={selectedLang} showApiKey={showApiKey} />
if (selected == 'tables-intro') return <TablesIntroduction selectedLang={selectedLang} />
if (selected == 'rpc-intro') return <RpcIntroduction />
else
diff --git a/apps/studio/components/interfaces/Docs/Introduction.tsx b/apps/studio/components/interfaces/Docs/Introduction.tsx
index 6c4c68c167e..b274bc6f388 100644
--- a/apps/studio/components/interfaces/Docs/Introduction.tsx
+++ b/apps/studio/components/interfaces/Docs/Introduction.tsx
@@ -5,17 +5,20 @@ import { useProjectPostgrestConfigQuery } from 'data/config/project-postgrest-co
import CodeSnippet from './CodeSnippet'
import PublicSchemaNotEnabledAlert from './PublicSchemaNotEnabledAlert'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
interface Props {
- autoApiService: AutoApiService
selectedLang: 'bash' | 'js'
}
-export default function Introduction({ autoApiService, selectedLang }: Props) {
+export default function Introduction({ selectedLang }: Props) {
const { ref: projectRef } = useParams()
+ const { data: settings } = useProjectSettingsV2Query({ projectRef })
const { data: config } = useProjectPostgrestConfigQuery({ projectRef })
+ const endpoint = settings?.app_config?.endpoint ?? ''
+
const isPublicSchemaEnabled = config?.db_schema
.split(',')
.map((name) => name.trim())
@@ -24,7 +27,7 @@ export default function Introduction({ autoApiService, selectedLang }: Props) {
return (
<div className="doc-section doc-section--client-libraries">
<article className="code">
- <CodeSnippet selectedLang={selectedLang} snippet={Snippets.init(autoApiService.endpoint)} />
+ <CodeSnippet selectedLang={selectedLang} snippet={Snippets.init(endpoint)} />
{!isPublicSchemaEnabled && <PublicSchemaNotEnabledAlert />}
</article>
diff --git a/apps/studio/components/interfaces/Docs/LangSelector.tsx b/apps/studio/components/interfaces/Docs/LangSelector.tsx
index 53376c063c9..b523ded9d53 100644
--- a/apps/studio/components/interfaces/Docs/LangSelector.tsx
+++ b/apps/studio/components/interfaces/Docs/LangSelector.tsx
@@ -1,8 +1,10 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { Key } from 'lucide-react'
+import { useParams } from 'common'
import type { showApiKey } from 'components/interfaces/Docs/Docs.types'
+import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { Key } from 'lucide-react'
import {
Button,
DropdownMenu,
@@ -15,26 +17,26 @@ const DEFAULT_KEY = { name: 'hide', key: 'SUPABASE_KEY' }
interface LangSelectorProps {
selectedLang: string
- setSelectedLang: (selectedLang: string) => void
showApiKey: showApiKey
+ setSelectedLang: (selectedLang: string) => void
setShowApiKey: (showApiKey: showApiKey) => void
- apiKey: string | undefined
- autoApiService: any
}
const LangSelector = ({
selectedLang,
- setSelectedLang,
showApiKey,
+ setSelectedLang,
setShowApiKey,
- apiKey,
- autoApiService,
}: LangSelectorProps) => {
+ const { ref: projectRef } = useParams()
const canReadServiceKey = useCheckPermissions(
PermissionAction.READ,
'service_api_keys.service_role_key'
)
+ const { data: settings } = useProjectSettingsV2Query({ projectRef })
+ const { anonKey: anonApiKey, serviceKey: serviceApiKey } = getAPIKeys(settings)
+
return (
<div className="p-1 w-1/2 ml-auto">
<div className="z-0 flex justify-end">
@@ -75,12 +77,12 @@ const LangSelector = ({
<DropdownMenuItem key="hide" onClick={() => setShowApiKey(DEFAULT_KEY)}>
hide
</DropdownMenuItem>
- {apiKey && (
+ {anonApiKey && (
<DropdownMenuItem
key="anon"
onClick={() =>
setShowApiKey({
- key: apiKey,
+ key: anonApiKey.api_key ?? '-',
name: 'anon (public)',
})
}
@@ -93,7 +95,7 @@ const LangSelector = ({
key="service"
onClick={() =>
setShowApiKey({
- key: autoApiService.serviceApiKey,
+ key: serviceApiKey?.api_key ?? '-',
name: 'service_role (secret)',
})
}
diff --git a/apps/studio/components/interfaces/Docs/Pages/UserManagement.tsx b/apps/studio/components/interfaces/Docs/Pages/UserManagement.tsx
index 9cbf5f4ac2d..c0296107f1b 100644
--- a/apps/studio/components/interfaces/Docs/Pages/UserManagement.tsx
+++ b/apps/studio/components/interfaces/Docs/Pages/UserManagement.tsx
@@ -1,7 +1,8 @@
import Link from 'next/link'
import { useRouter } from 'next/router'
-import type { AutoApiService } from 'data/config/project-api-query'
+import { useParams } from 'common'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { makeRandomString } from 'lib/helpers'
import CodeSnippet from '../CodeSnippet'
import Snippets from '../Snippets'
@@ -9,20 +10,18 @@ import Snippets from '../Snippets'
const randomPassword = makeRandomString(20)
interface UserManagementProps {
- autoApiService: AutoApiService
selectedLang: 'bash' | 'js'
showApiKey: string
}
-export default function UserManagement({
- autoApiService,
- selectedLang,
- showApiKey,
-}: UserManagementProps) {
+export default function UserManagement({ selectedLang, showApiKey }: UserManagementProps) {
const router = useRouter()
-
+ const { ref: projectRef } = useParams()
const keyToShow = showApiKey ? showApiKey : 'SUPABASE_KEY'
+ const { data: settings } = useProjectSettingsV2Query({ projectRef })
+ const endpoint = settings?.app_config?.endpoint ?? ''
+
return (
<>
<h2 className="doc-heading">User Management</h2>
@@ -53,7 +52,7 @@ export default function UserManagement({
<article className="code">
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.authSignup(autoApiService.endpoint, keyToShow, randomPassword)}
+ snippet={Snippets.authSignup(endpoint, keyToShow, randomPassword)}
/>
</article>
</div>
@@ -70,7 +69,7 @@ export default function UserManagement({
<article className="code">
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.authLogin(autoApiService.endpoint, keyToShow, randomPassword)}
+ snippet={Snippets.authLogin(endpoint, keyToShow, randomPassword)}
/>
</article>
</div>
@@ -87,7 +86,7 @@ export default function UserManagement({
<article className="code">
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.authMagicLink(autoApiService.endpoint, keyToShow)}
+ snippet={Snippets.authMagicLink(endpoint, keyToShow)}
/>
</article>
</div>
@@ -111,7 +110,7 @@ export default function UserManagement({
<article className="code">
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.authPhoneSignUp(autoApiService.endpoint, keyToShow)}
+ snippet={Snippets.authPhoneSignUp(endpoint, keyToShow)}
/>
</article>
</div>
@@ -131,7 +130,7 @@ export default function UserManagement({
<article className="code">
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.authMobileOTPLogin(autoApiService.endpoint, keyToShow)}
+ snippet={Snippets.authMobileOTPLogin(endpoint, keyToShow)}
/>
</article>
</div>
@@ -151,7 +150,7 @@ export default function UserManagement({
<article className="code">
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.authMobileOTPVerify(autoApiService.endpoint, keyToShow)}
+ snippet={Snippets.authMobileOTPVerify(endpoint, keyToShow)}
/>
</article>
</div>
@@ -218,7 +217,7 @@ export default function UserManagement({
<article className="code">
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.authThirdPartyLogin(autoApiService.endpoint, keyToShow)}
+ snippet={Snippets.authThirdPartyLogin(endpoint, keyToShow)}
/>
</article>
</div>
@@ -231,7 +230,7 @@ export default function UserManagement({
<article className="code">
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.authUser(autoApiService.endpoint, keyToShow)}
+ snippet={Snippets.authUser(endpoint, keyToShow)}
/>
</article>
</div>
@@ -247,7 +246,7 @@ export default function UserManagement({
<article className="code">
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.authRecover(autoApiService.endpoint, keyToShow)}
+ snippet={Snippets.authRecover(endpoint, keyToShow)}
/>
</article>
</div>
@@ -263,7 +262,7 @@ export default function UserManagement({
<article className="code">
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.authUpdate(autoApiService.endpoint, keyToShow)}
+ snippet={Snippets.authUpdate(endpoint, keyToShow)}
/>
</article>
</div>
@@ -279,7 +278,7 @@ export default function UserManagement({
<article className="code">
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.authLogout(autoApiService.endpoint, keyToShow)}
+ snippet={Snippets.authLogout(endpoint, keyToShow)}
/>
</article>
</div>
@@ -300,7 +299,7 @@ export default function UserManagement({
<article className="code">
<CodeSnippet
selectedLang={selectedLang}
- snippet={Snippets.authInvite(autoApiService.endpoint, keyToShow)}
+ snippet={Snippets.authInvite(endpoint, keyToShow)}
/>
</article>
</div>
diff --git a/apps/studio/components/interfaces/Docs/RpcContent.tsx b/apps/studio/components/interfaces/Docs/RpcContent.tsx
index b7ba1558eb2..c749f6658cd 100644
--- a/apps/studio/components/interfaces/Docs/RpcContent.tsx
+++ b/apps/studio/components/interfaces/Docs/RpcContent.tsx
@@ -1,38 +1,53 @@
+import { useParams } from 'common'
import CodeSnippet from 'components/interfaces/Docs/CodeSnippet'
import Description from 'components/interfaces/Docs/Description'
import Param from 'components/interfaces/Docs/Param'
import Snippets from 'components/interfaces/Docs/Snippets'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
+import { ProjectJsonSchemaPaths } from 'data/docs/project-json-schema-query'
/**
* TODO: need to support rpc with the same name and different params type
*/
+
+interface RpcContentProps {
+ rpcId: string
+ rpcs: { [key: string]: any }
+ paths?: ProjectJsonSchemaPaths
+ selectedLang: 'bash' | 'js'
+ showApiKey: string
+ refreshDocs: () => void
+}
+
const RpcContent = ({
- autoApiService,
rpcId,
rpcs,
paths,
selectedLang,
- refreshDocs,
showApiKey,
-}: any) => {
+ refreshDocs,
+}: RpcContentProps) => {
+ const { ref: projectRef } = useParams()
+ const { data: settings } = useProjectSettingsV2Query({ projectRef })
+ const endpoint = settings?.app_config?.endpoint ?? ''
+
const meta = rpcs[rpcId]
const pathKey = `/rpc/${rpcId}`
const path = paths && pathKey in paths ? paths[pathKey] : undefined
const keyToShow = !!showApiKey ? showApiKey : 'SUPABASE_KEY'
- if (!path) return null
-
- const {
- post: { parameters, summary },
- } = path
+ const { post } = path!
+ const { parameters, summary } = post || {}
const rpcParamsObject =
- parameters && parameters[0] && parameters[0].schema && parameters[0].schema.properties
- ? parameters[0].schema.properties
+ parameters && parameters[0] && parameters[0].schema && (parameters[0].schema as any).properties
+ ? (parameters[0].schema as any).properties
: {}
const rpcParams = Object.entries(rpcParamsObject)
.map(([k, v]: any) => ({ name: k, ...v }))
.filter((x) => !!x.name)
+ if (!path) return null
+
return (
<>
<h2 className="text-foreground mt-0">
@@ -42,7 +57,7 @@ const RpcContent = ({
<div className="doc-section">
<article className="code-column text-foreground">
<label className="font-mono text-xs uppercase text-foreground-lighter">Description</label>
- <Description content={summary} metadata={{ rpc: rpcId }} onChange={refreshDocs} />
+ <Description content={summary ?? ''} metadata={{ rpc: rpcId }} onChange={refreshDocs} />
</article>
<article className="code">
<CodeSnippet
@@ -53,7 +68,7 @@ const RpcContent = ({
rpcCamelCase: meta.camelCase,
rpcParams: rpcParams,
apiKey: keyToShow,
- endpoint: autoApiService.endpoint,
+ endpoint: endpoint,
})}
/>
</article>
diff --git a/apps/studio/components/interfaces/Home/Connect/Connect.tsx b/apps/studio/components/interfaces/Home/Connect/Connect.tsx
index d00330491b2..2478ade775a 100644
--- a/apps/studio/components/interfaces/Home/Connect/Connect.tsx
+++ b/apps/studio/components/interfaces/Home/Connect/Connect.tsx
@@ -5,10 +5,9 @@ import { useState } from 'react'
import { DatabaseConnectionString } from 'components/interfaces/Settings/Database/DatabaseSettings/DatabaseConnectionString'
import { PoolingModesModal } from 'components/interfaces/Settings/Database/PoolingModesModal'
-import { useProjectApiQuery } from 'data/config/project-api-query'
-import { useProjectSettingsQuery } from 'data/config/project-settings-query'
+import Panel from 'components/ui/Panel'
+import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { DEFAULT_PROJECT_API_SERVICE_ID } from 'lib/constants'
import {
Button,
DIALOG_PADDING_X,
@@ -30,7 +29,6 @@ import { CONNECTION_TYPES, ConnectionType, FRAMEWORKS, MOBILES, ORMS } from './C
import { getContentFilePath } from './Connect.utils'
import ConnectDropdown from './ConnectDropdown'
import ConnectTabContent from './ConnectTabContent'
-import Panel from 'components/ui/Panel'
const Connect = () => {
const { ref: projectRef } = useParams()
@@ -46,6 +44,9 @@ const Connect = () => {
?.children.find((child) => child.key === selectedChild)?.children[0]?.key || ''
)
+ const { data: settings } = useProjectSettingsV2Query({ projectRef })
+ const canReadAPIKeys = useCheckPermissions(PermissionAction.READ, 'service_api_keys')
+
const handleParentChange = (value: string) => {
setSelectedParent(value)
@@ -127,32 +128,12 @@ const Connect = () => {
return []
}
- const { data: projectSettings } = useProjectSettingsQuery({ projectRef })
-
- const { data: apiSettings } = useProjectApiQuery({
- projectRef,
- })
-
- // Get the API service
- const apiService = (projectSettings?.services ?? []).find(
- (x: any) => x.app.id == DEFAULT_PROJECT_API_SERVICE_ID
- )
-
- const canReadAPIKeys = useCheckPermissions(PermissionAction.READ, 'service_api_keys')
-
- // Get the API service
- const apiHost = canReadAPIKeys
- ? `${apiSettings?.autoApiService?.protocol ?? 'https'}://${
- apiSettings?.autoApiService?.endpoint ?? '-'
- }`
- : ''
+ const endpoint = settings?.app_config?.endpoint
+ const apiHost = canReadAPIKeys ? `https://${endpoint ?? '-'}` : ''
const apiUrl = canReadAPIKeys ? apiHost : null
- const anonKey = canReadAPIKeys
- ? apiService?.service_api_keys.find((key) => key.tags === 'anon')?.api_key ?? null
- : null
-
- const projectKeys = { apiUrl, anonKey }
+ const { anonKey } = canReadAPIKeys ? getAPIKeys(settings) : { anonKey: null }
+ const projectKeys = { apiUrl, anonKey: anonKey?.api_key ?? null }
const filePath = getContentFilePath({
connectionObject,
diff --git a/apps/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx b/apps/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx
index 93af608f4e7..afccbce6923 100644
--- a/apps/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx
+++ b/apps/studio/components/interfaces/Home/NewProjectPanel/APIKeys.tsx
@@ -3,14 +3,14 @@ import { JwtSecretUpdateStatus } from '@supabase/shared-types/out/events'
import Link from 'next/link'
import { useState } from 'react'
-import { useParams } from 'common/hooks'
import { SimpleCodeBlock } from '@ui/components/SimpleCodeBlock'
+import { useParams } from 'common/hooks'
import Panel from 'components/ui/Panel'
import { useJwtSecretUpdatingStatusQuery } from 'data/config/jwt-secret-updating-status-query'
-import { useProjectApiQuery } from 'data/config/project-api-query'
+import { getAPIKeys, useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { Input } from 'ui'
import { AlertCircle, Loader } from 'lucide-react'
+import { Input } from 'ui'
const generateInitSnippet = (endpoint: string) => ({
js: `
@@ -42,7 +42,7 @@ const APIKeys = () => {
data: settings,
isError: isProjectSettingsError,
isLoading: isProjectSettingsLoading,
- } = useProjectApiQuery({
+ } = useProjectSettingsV2Query({
projectRef,
})
@@ -55,17 +55,16 @@ const APIKeys = () => {
const canReadAPIKeys = useCheckPermissions(PermissionAction.READ, 'service_api_keys')
- // Get the API service
- const apiService = settings?.autoApiService
- const apiKeys = apiService?.service_api_keys ?? []
+ const apiKeys = settings?.service_api_keys ?? []
// API keys should not be empty. However it can be populated with a delay on project creation
const isApiKeysEmpty = apiKeys.length === 0
const isNotUpdatingJwtSecret =
jwtSecretUpdateStatus === undefined || jwtSecretUpdateStatus === JwtSecretUpdateStatus.Updated
- const apiUrl = `${apiService?.protocol ?? 'https'}://${apiService?.endpoint ?? '-'}`
- const anonKey = apiKeys.find((key) => key.tags === 'anon')
+ const endpoint = settings?.app_config?.endpoint
+ const apiUrl = `https://${endpoint ?? '-'}`
+ const { anonKey } = getAPIKeys(settings)
const clientInitSnippet: any = generateInitSnippet(apiUrl)
const selectedLanguageSnippet = clientInitSnippet[selectedLanguage.key] ?? 'No snippet available'
@@ -146,7 +145,7 @@ const APIKeys = () => {
? 'JWT secret update failed, new API key may have issues'
: jwtSecretUpdateStatus === JwtSecretUpdateStatus.Updating
? 'Updating JWT secret...'
- : apiService?.defaultApiKey
+ : anonKey?.api_key
}
onChange={() => {}}
descriptionText={
diff --git a/apps/studio/components/interfaces/ProjectAPIDocs/Content/Introduction.tsx b/apps/studio/components/interfaces/ProjectAPIDocs/Content/Introduction.tsx
index 4c50ce99911..10edf7179ef 100644
--- a/apps/studio/components/interfaces/ProjectAPIDocs/Content/Introduction.tsx
+++ b/apps/studio/components/interfaces/ProjectAPIDocs/Content/Introduction.tsx
@@ -1,17 +1,17 @@
import { useParams } from 'common'
import { Button, Input } from 'ui'
-import { useProjectApiQuery } from 'data/config/project-api-query'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { copyToClipboard } from 'lib/helpers'
+import { Copy } from 'lucide-react'
import { useEffect, useState } from 'react'
import ContentSnippet from '../ContentSnippet'
import { DOCS_CONTENT } from '../ProjectAPIDocs.constants'
import type { ContentProps } from './Content.types'
-import { Copy } from 'lucide-react'
const Introduction = ({ showKeys, language, apikey, endpoint }: ContentProps) => {
const { ref } = useParams()
- const { data } = useProjectApiQuery({ projectRef: ref })
+ const { data } = useProjectSettingsV2Query({ projectRef: ref })
const [copied, setCopied] = useState<'anon' | 'service'>()
@@ -19,9 +19,10 @@ const Introduction = ({ showKeys, language, apikey, endpoint }: ContentProps) =>
if (copied !== undefined) setTimeout(() => setCopied(undefined), 2000)
}, [copied])
- const serviceKey = showKeys
- ? data?.autoApiService.serviceApiKey ?? 'SUPABASE_CLIENT_SERVICE_KEY'
- : 'SUPABASE_CLIENT_SERVICE_KEY'
+ const anonApiKey = (data?.service_api_keys ?? []).find((key) => key.tags === 'anon')?.api_key
+ const serviceApiKey =
+ (data?.service_api_keys ?? []).find((key) => key.tags === 'service_role')?.api_key ??
+ 'SUPABASE_CLIENT_SERVICE_KEY'
return (
<>
@@ -52,9 +53,7 @@ const Introduction = ({ showKeys, language, apikey, endpoint }: ContentProps) =>
icon={<Copy />}
onClick={() => {
setCopied('anon')
- copyToClipboard(
- data?.autoApiService.defaultApiKey ?? 'SUPABASE_CLIENT_ANON_KEY'
- )
+ copyToClipboard(anonApiKey ?? 'SUPABASE_CLIENT_ANON_KEY')
}}
>
{copied === 'anon' ? 'Copied' : 'Copy'}
@@ -68,7 +67,11 @@ const Introduction = ({ showKeys, language, apikey, endpoint }: ContentProps) =>
disabled
readOnly
size="small"
- value={showKeys ? serviceKey : 'Reveal API keys via dropdown in the header'}
+ value={
+ showKeys
+ ? serviceApiKey ?? 'SUPABASE_CLIENT_SERVICE_KEY'
+ : 'Reveal API keys via dropdown in the header'
+ }
className="w-full"
descriptionText={
<p>
@@ -83,9 +86,7 @@ const Introduction = ({ showKeys, language, apikey, endpoint }: ContentProps) =>
icon={<Copy />}
onClick={() => {
setCopied('service')
- copyToClipboard(
- data?.autoApiService.serviceApiKey ?? 'SUPABASE_CLIENT_SERVICE_KEY'
- )
+ copyToClipboard(serviceApiKey)
}}
>
{copied === 'service' ? 'Copied' : 'Copy'}
@@ -105,7 +106,7 @@ const Introduction = ({ showKeys, language, apikey, endpoint }: ContentProps) =>
<ContentSnippet
selectedLanguage={language}
- apikey={serviceKey}
+ apikey={showKeys ? serviceApiKey : 'SUPABASE_CLIENT_SERVICE_KEY'}
endpoint={endpoint}
snippet={DOCS_CONTENT.serviceApiKeys}
/>
diff --git a/apps/studio/components/layouts/StorageLayout/StorageLayout.tsx b/apps/studio/components/layouts/StorageLayout/StorageLayout.tsx
index aa97b8fa2b8..0df1670f64f 100644
--- a/apps/studio/components/layouts/StorageLayout/StorageLayout.tsx
+++ b/apps/studio/components/layouts/StorageLayout/StorageLayout.tsx
@@ -2,7 +2,7 @@ import { useParams } from 'common'
import { ReactNode, useEffect } from 'react'
import { toast } from 'sonner'
-import { AutoApiService, useProjectApiQuery } from 'data/config/project-api-query'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useSelectedProject } from 'hooks/misc/useSelectedProject'
import { withAuth } from 'hooks/misc/withAuth'
import { PROJECT_STATUS } from 'lib/constants'
@@ -20,25 +20,24 @@ const StorageLayout = ({ title, children }: StorageLayoutProps) => {
const project = useSelectedProject()
const storageExplorerStore = useStorageStore()
- const { data: settings, isLoading } = useProjectApiQuery({ projectRef })
- const apiService = settings?.autoApiService
+ const { data: settings, isLoading } = useProjectSettingsV2Query({ projectRef })
+ const endpoint = settings?.app_config?.endpoint
+ const serviceApiKey = (settings?.service_api_keys ?? []).find(
+ (key) => key.tags === 'service_role'
+ )?.api_key
const isPaused = project?.status === PROJECT_STATUS.INACTIVE
useEffect(() => {
- if (!isLoading && apiService) initializeStorageStore(apiService)
- }, [isLoading, projectRef])
+ if (!isLoading && endpoint && serviceApiKey) initializeStorageStore(endpoint, serviceApiKey)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [isLoading, projectRef, endpoint, serviceApiKey])
- const initializeStorageStore = async (apiService: AutoApiService) => {
+ const initializeStorageStore = async (endpoint: string, serviceApiKey: string) => {
if (isPaused) return
- if (apiService.endpoint) {
- storageExplorerStore.initStore(
- projectRef!,
- apiService.endpoint,
- apiService.serviceApiKey,
- apiService.protocol
- )
+ if (endpoint) {
+ storageExplorerStore.initStore(projectRef!, endpoint, serviceApiKey, 'https')
} else {
toast.error(
'Failed to fetch project configuration. Try refreshing your browser, or reach out to us at [email protected]'
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageSettings/S3Connection.tsx b/apps/studio/components/to-be-cleaned/Storage/StorageSettings/S3Connection.tsx
index 25a5c517e49..1e58b14c992 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageSettings/S3Connection.tsx
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageSettings/S3Connection.tsx
@@ -12,7 +12,7 @@ import Table from 'components/to-be-cleaned/Table'
import { FormHeader } from 'components/ui/Forms/FormHeader'
import NoPermission from 'components/ui/NoPermission'
import Panel from 'components/ui/Panel'
-import { useProjectApiQuery } from 'data/config/project-api-query'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useStorageCredentialsQuery } from 'data/storage/s3-access-key-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { AlertDescription_Shadcn_, Alert_Shadcn_, Button, WarningIcon } from 'ui'
@@ -35,14 +35,15 @@ export const S3Connection = () => {
const canReadS3Credentials = useCheckPermissions(PermissionAction.STORAGE_ADMIN_READ, '*')
- const { data: projectAPI } = useProjectApiQuery({ projectRef: projectRef })
+ const { data: settings } = useProjectSettingsV2Query({ projectRef })
const { data: storageCreds, ...storageCredsQuery } = useStorageCredentialsQuery(
{ projectRef },
{ enabled: canReadS3Credentials }
)
+ const endpoint = settings?.app_config?.endpoint
const hasStorageCreds = storageCreds?.data && storageCreds.data.length > 0
- const s3connectionUrl = getConnectionURL(projectRef ?? '', projectAPI)
+ const s3connectionUrl = getConnectionURL(projectRef ?? '', endpoint)
return (
<>
diff --git a/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.utils.ts b/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.utils.ts
index 44cf98726af..3dab5cc0cd4 100644
--- a/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.utils.ts
+++ b/apps/studio/components/to-be-cleaned/Storage/StorageSettings/StorageSettings.utils.ts
@@ -26,12 +26,8 @@ export const convertToBytes = (size: number, unit: StorageSizeUnits = StorageSiz
return size * Math.pow(k, i)
}
-export function getConnectionURL(projectRef: string, projectAPI?: ProjectApiResponse) {
- if (projectAPI === undefined) return ''
-
- const projUrl = projectAPI
- ? `${projectAPI.autoApiService.protocol}://${projectAPI.autoApiService.endpoint}`
- : `https://${projectRef}.supabase.co`
+export function getConnectionURL(projectRef: string, endpoint?: string) {
+ const projUrl = endpoint ? `https://${endpoint}` : `https://${projectRef}.supabase.co`
const url = new URL(projUrl)
url.pathname = '/storage/v1/s3'
diff --git a/apps/studio/data/config/keys.ts b/apps/studio/data/config/keys.ts
index 6f4b61da217..a2aab7748f1 100644
--- a/apps/studio/data/config/keys.ts
+++ b/apps/studio/data/config/keys.ts
@@ -2,6 +2,7 @@ export const configKeys = {
pgBouncerStatus: (projectRef: string | undefined) =>
['projects', projectRef, 'pgbouncer'] as const,
settings: (projectRef: string | undefined) => ['projects', projectRef, 'settings'] as const,
+ settingsV2: (projectRef: string | undefined) => ['projects', projectRef, 'settings-v2'] as const,
api: (projectRef: string | undefined) => ['projects', projectRef, 'settings', 'api'] as const,
postgrest: (projectRef: string | undefined) => ['projects', projectRef, 'postgrest'] as const,
jwtSecretUpdatingStatus: (projectRef: string | undefined) =>
diff --git a/apps/studio/data/config/project-api-query.ts b/apps/studio/data/config/project-api-query.ts
index 8baaee61d0d..3826300f630 100644
--- a/apps/studio/data/config/project-api-query.ts
+++ b/apps/studio/data/config/project-api-query.ts
@@ -6,6 +6,8 @@ import { useProjectByRef } from 'hooks/misc/useSelectedProject'
import { PROJECT_STATUS } from 'lib/constants'
import type { ResponseError } from 'types'
import { configKeys } from './keys'
+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
export type ProjectApiVariables = {
projectRef?: string
@@ -32,24 +34,25 @@ export async function getProjectApi({ projectRef }: ProjectApiVariables, signal?
export type ProjectApiData = Awaited<ReturnType<typeof getProjectApi>>
export type ProjectApiError = ResponseError
+/** @deprecated */
export const useProjectApiQuery = <TData = ProjectApiData>(
{ projectRef }: ProjectApiVariables,
{ enabled = true, ...options }: UseQueryOptions<ProjectApiData, ProjectApiError, TData> = {}
) => {
+ const canReadAPIKeys = useCheckPermissions(PermissionAction.READ, 'service_api_keys')
+
return useQuery<ProjectApiData, ProjectApiError, TData>(
configKeys.api(projectRef),
({ signal }) => getProjectApi({ projectRef }, signal),
{
enabled: enabled && typeof projectRef !== 'undefined',
refetchInterval(data) {
- if (!data) {
- return false
- }
+ if (!data) return false
const { autoApiService } = data as unknown as ProjectApiData
const apiKeys = autoApiService?.service_api_keys ?? []
- const interval = apiKeys.length === 0 ? 2000 : 0
+ const interval = canReadAPIKeys && apiKeys.length === 0 ? 2000 : 0
return interval
},
diff --git a/apps/studio/data/config/project-settings-query.ts b/apps/studio/data/config/project-settings-query.ts
index 96a3a82385d..7d9d642c132 100644
--- a/apps/studio/data/config/project-settings-query.ts
+++ b/apps/studio/data/config/project-settings-query.ts
@@ -42,6 +42,7 @@ export async function getProjectSettings(
export type ProjectSettingsData = Awaited<ReturnType<typeof getProjectSettings>>
export type ProjectSettingsError = ResponseError
+/** @deprecated */
export const useProjectSettingsQuery = <TData = ProjectSettingsData>(
{ projectRef }: ProjectSettingsVariables,
{
diff --git a/apps/studio/data/config/project-settings-v2-query.ts b/apps/studio/data/config/project-settings-v2-query.ts
new file mode 100644
index 00000000000..129d756c0bd
--- /dev/null
+++ b/apps/studio/data/config/project-settings-v2-query.ts
@@ -0,0 +1,62 @@
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useQuery, UseQueryOptions } from '@tanstack/react-query'
+
+import type { components } from 'data/api'
+import { get, handleError } from 'data/fetchers'
+import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
+import type { ResponseError } from 'types'
+import { configKeys } from './keys'
+
+export type ProjectSettingsVariables = { projectRef?: string }
+export type ProjectSettings = components['schemas']['ProjectSettingsResponse']
+
+export async function getProjectSettings(
+ { projectRef }: ProjectSettingsVariables,
+ signal?: AbortSignal
+) {
+ if (!projectRef) throw new Error('projectRef is required')
+
+ const { data, error } = await get('/platform/projects/{ref}/settings', {
+ params: { path: { ref: projectRef } },
+ signal,
+ })
+
+ if (error) handleError(error)
+ return data as unknown as ProjectSettings
+}
+
+type ProjectSettingsData = Awaited<ReturnType<typeof getProjectSettings>>
+type ProjectSettingsError = ResponseError
+
+export const useProjectSettingsV2Query = <TData = ProjectSettingsData>(
+ { projectRef }: ProjectSettingsVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseQueryOptions<ProjectSettingsData, ProjectSettingsError, TData> = {}
+) => {
+ // [Joshen] Sync with API perms checking here - shouldReturnApiKeys
+ // https://github.com/supabase/infrastructure/blob/develop/api/src/routes/platform/projects/ref/settings.controller.ts#L92
+ const canReadAPIKeys = useCheckPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, '*')
+
+ return useQuery<ProjectSettingsData, ProjectSettingsError, TData>(
+ configKeys.settingsV2(projectRef),
+ ({ signal }) => getProjectSettings({ projectRef }, signal),
+ {
+ enabled: enabled && typeof projectRef !== 'undefined',
+ refetchInterval(data) {
+ const apiKeys = (data as ProjectSettings)?.service_api_keys ?? []
+ const interval = canReadAPIKeys && apiKeys.length === 0 ? 2000 : 0
+ return interval
+ },
+ ...options,
+ }
+ )
+}
+
+export const getAPIKeys = (settings?: ProjectSettings) => {
+ const anonKey = (settings?.service_api_keys ?? []).find((x) => x.tags === 'anon')
+ const serviceKey = (settings?.service_api_keys ?? []).find((x) => x.tags === 'service_role')
+
+ return { anonKey, serviceKey }
+}
diff --git a/apps/studio/pages/project/[ref]/api/index.tsx b/apps/studio/pages/project/[ref]/api/index.tsx
index d195fd6da37..a693135da06 100644
--- a/apps/studio/pages/project/[ref]/api/index.tsx
+++ b/apps/studio/pages/project/[ref]/api/index.tsx
@@ -4,7 +4,7 @@ import { useState } from 'react'
import { GeneralContent, ResourceContent, RpcContent } from 'components/interfaces/Docs'
import LangSelector from 'components/interfaces/Docs/LangSelector'
import DocsLayout from 'components/layouts/DocsLayout/DocsLayout'
-import { useProjectApiQuery } from 'data/config/project-api-query'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useCustomDomainsQuery } from 'data/custom-domains/custom-domains-query'
import { useProjectJsonSchemaQuery } from 'data/docs/project-json-schema-query'
import { snakeToCamel } from 'lib/helpers'
@@ -26,10 +26,7 @@ const DocView = () => {
const [selectedLang, setSelectedLang] = useState<any>('js')
const [showApiKey, setShowApiKey] = useState<any>(DEFAULT_KEY)
- const { data, error } = useProjectApiQuery({ projectRef })
- const apiService = data?.autoApiService
- const anonKey = apiService?.defaultApiKey ?? undefined
-
+ const { data: settings, error: settingsError } = useProjectSettingsV2Query({ projectRef })
const {
data: jsonSchema,
error: jsonSchemaError,
@@ -43,11 +40,10 @@ const DocView = () => {
const endpoint =
customDomainData?.customDomain?.status === 'active'
? `https://${customDomainData.customDomain?.hostname}`
- : `${data?.autoApiService.protocol ?? 'https'}://${data?.autoApiService.endpoint ?? '-'}`
+ : `https://${settings?.app_config?.endpoint ?? '-'}`
const { paths } = jsonSchema || {}
const PAGE_KEY: any = resource || rpc || page || 'index'
- const autoApiService = { ...(data?.autoApiService ?? {}), endpoint }
const { resources, rpcs } = Object.entries(paths || {}).reduce(
(a, [name]) => {
@@ -84,18 +80,18 @@ const DocView = () => {
{ resources: {}, rpcs: {} }
)
- if (error || jsonSchemaError) {
+ if (settingsError || jsonSchemaError) {
return (
<div className="p-6 mx-auto text-center sm:w-full md:w-3/4">
<p className="text-foreground-light">
<p>Error connecting to API</p>
- <p>{`${error || jsonSchemaError}`}</p>
+ <p>{`${settingsError || jsonSchemaError}`}</p>
</p>
</div>
)
}
- if (isLoading || !data || !jsonSchema) {
+ if (isLoading || !settings || !jsonSchema) {
return (
<div className="p-6 mx-auto text-center sm:w-full md:w-3/4">
<h3 className="text-xl">Building docs ...</h3>
@@ -109,11 +105,9 @@ const DocView = () => {
<div className="sticky top-0 z-40 flex flex-row-reverse w-full ">
<LangSelector
selectedLang={selectedLang}
- setSelectedLang={setSelectedLang}
showApiKey={showApiKey}
+ setSelectedLang={setSelectedLang}
setShowApiKey={setShowApiKey}
- apiKey={anonKey}
- autoApiService={autoApiService}
/>
</div>
<div>
@@ -128,7 +122,6 @@ const DocView = () => {
/>
) : rpc ? (
<RpcContent
- autoApiService={autoApiService}
selectedLang={selectedLang}
rpcId={rpc}
paths={paths}
@@ -137,12 +130,7 @@ const DocView = () => {
refreshDocs={refreshDocs}
/>
) : (
- <GeneralContent
- autoApiService={autoApiService}
- selectedLang={selectedLang}
- showApiKey={showApiKey.key}
- page={page}
- />
+ <GeneralContent selectedLang={selectedLang} showApiKey={showApiKey.key} page={page} />
)}
</div>
</div>
diff --git a/apps/studio/pages/project/[ref]/integrations/graphiql.tsx b/apps/studio/pages/project/[ref]/integrations/graphiql.tsx
index 3d34d908c1b..496ba9cb95c 100644
--- a/apps/studio/pages/project/[ref]/integrations/graphiql.tsx
+++ b/apps/studio/pages/project/[ref]/integrations/graphiql.tsx
@@ -10,8 +10,8 @@ import GraphiQL from 'components/interfaces/GraphQL/GraphiQL'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { Loading } from 'components/ui/Loading'
import { useSessionAccessTokenQuery } from 'data/auth/session-access-token-query'
-import { useProjectApiQuery } from 'data/config/project-api-query'
import { useProjectPostgrestConfigQuery } from 'data/config/project-postgrest-config-query'
+import { useProjectSettingsV2Query } from 'data/config/project-settings-v2-query'
import { useDatabaseExtensionsQuery } from 'data/database-extensions/database-extensions-query'
import { API_URL, IS_PLATFORM } from 'lib/constants'
import { getRoleImpersonationJWT } from 'lib/role-impersonation'
@@ -32,12 +32,11 @@ const GraphiQLPage: NextPageWithLayout = () => {
const pgGraphqlExtension = (data ?? []).find((ext) => ext.name === 'pg_graphql')
const { data: accessToken } = useSessionAccessTokenQuery({ enabled: IS_PLATFORM })
- const { data: settings, isFetched } = useProjectApiQuery({ projectRef })
+ const { data: settings, isFetched } = useProjectSettingsV2Query({ projectRef })
- const apiService = settings?.autoApiService
- const serviceRoleKey = apiService?.service_api_keys.find((x) => x.name === 'service_role key')
- ? apiService.serviceApiKey
- : undefined
+ const serviceRoleKey = (settings?.service_api_keys ?? []).find(
+ (x) => x.name === 'service_role key'
+ )?.api_key
const { data: config } = useProjectPostgrestConfigQuery({ projectRef })
const jwtSecret = config?.jwt_secret