Skip to content

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

chore: simply studio auth logic (#18655)

Alaister Youngb5e9020277f5
diff --git a/studio/components/interfaces/SignIn/SignInForm.tsx b/studio/components/interfaces/SignIn/SignInForm.tsx
index 1b3ed5a03bc..b91c9cc0937 100644
--- a/studio/components/interfaces/SignIn/SignInForm.tsx
+++ b/studio/components/interfaces/SignIn/SignInForm.tsx
@@ -2,17 +2,17 @@ import HCaptcha from '@hcaptcha/react-hcaptcha'
import * as Sentry from '@sentry/nextjs'
import { AuthError } from '@supabase/supabase-js'
import { useQueryClient } from '@tanstack/react-query'
-import { getMfaAuthenticatorAssuranceLevel } from 'data/profile/mfa-authenticator-assurance-level-query'
-import { useStore } from 'hooks'
-import { usePushNext } from 'hooks/misc/useAutoAuthRedirect'
-import { auth, buildPathWithParams } from 'lib/gotrue'
-import { incrementSignInClicks } from 'lib/local-storage'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { useRef, useState } from 'react'
-import { Button, Form, Input } from 'ui'
import { object, string } from 'yup'
+import { getMfaAuthenticatorAssuranceLevel } from 'data/profile/mfa-authenticator-assurance-level-query'
+import { useStore } from 'hooks'
+import { auth, buildPathWithParams, getReturnToPath } from 'lib/gotrue'
+import { incrementSignInClicks } from 'lib/local-storage'
+import { Button, Form, Input } from 'ui'
+
const signInSchema = object({
email: string().email('Must be a valid email').required('Email is required'),
password: string().required('Password is required'),
@@ -21,7 +21,6 @@ const signInSchema = object({
const SignInForm = () => {
const { ui } = useStore()
const router = useRouter()
- const pushNext = usePushNext()
const queryClient = useQueryClient()
const [captchaToken, setCaptchaToken] = useState<string | null>(null)
@@ -74,7 +73,7 @@ const SignInForm = () => {
await queryClient.resetQueries()
- await pushNext()
+ router.push(getReturnToPath())
} catch (error) {
ui.setNotification({
id: toastId,
diff --git a/studio/components/interfaces/SignIn/SignInMfaForm.tsx b/studio/components/interfaces/SignIn/SignInMfaForm.tsx
index 3c4cf01d639..17c986c680b 100644
--- a/studio/components/interfaces/SignIn/SignInMfaForm.tsx
+++ b/studio/components/interfaces/SignIn/SignInMfaForm.tsx
@@ -12,8 +12,8 @@ import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import { useMfaChallengeAndVerifyMutation } from 'data/profile/mfa-challenge-and-verify-mutation'
import { useMfaListFactorsQuery } from 'data/profile/mfa-list-factors-query'
import { useStore } from 'hooks'
-import { usePushNext } from 'hooks/misc/useAutoAuthRedirect'
import { useSignOut } from 'lib/auth'
+import { getReturnToPath } from 'lib/gotrue'
const signInSchema = object({
code: string().required('MFA Code is required'),
@@ -21,7 +21,6 @@ const signInSchema = object({
const SignInMfaForm = () => {
const { ui } = useStore()
- const pushNext = usePushNext()
const queryClient = useQueryClient()
const router = useRouter()
const {
@@ -48,13 +47,13 @@ const SignInMfaForm = () => {
if (isSuccessFactors) {
// if the user wanders into this page and he has no MFA setup, send the user to the next screen
if (factors.totp.length === 0) {
- queryClient.resetQueries().then(() => pushNext())
+ queryClient.resetQueries().then(() => router.push(getReturnToPath()))
}
if (factors.totp.length > 0) {
setSelectedFactor(factors.totp[0])
}
}
- }, [factors?.totp, isSuccessFactors, pushNext, queryClient])
+ }, [factors?.totp, isSuccessFactors, router, queryClient])
const onSignIn = async ({ code }: { code: string }) => {
const toastId = ui.setNotification({
@@ -74,7 +73,7 @@ const SignInMfaForm = () => {
await queryClient.resetQueries()
- await pushNext()
+ router.push(getReturnToPath())
},
onError: (error) => {
ui.setNotification({
diff --git a/studio/components/layouts/SignInLayout/SignInLayout.tsx b/studio/components/layouts/SignInLayout/SignInLayout.tsx
index 330f2f42dca..a81cbeb2b47 100644
--- a/studio/components/layouts/SignInLayout/SignInLayout.tsx
+++ b/studio/components/layouts/SignInLayout/SignInLayout.tsx
@@ -1,14 +1,13 @@
import { useQueryClient } from '@tanstack/react-query'
import { useTheme } from 'next-themes'
-import { useFlag } from 'hooks'
-import { usePushNext } from 'hooks/misc/useAutoAuthRedirect'
-import { BASE_PATH } from 'lib/constants'
-import { auth, buildPathWithParams, getAccessToken } from 'lib/gotrue'
-import { observer } from 'mobx-react-lite'
import Image from 'next/legacy/image'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { PropsWithChildren, useEffect, useState } from 'react'
+
+import { useFlag } from 'hooks'
+import { BASE_PATH } from 'lib/constants'
+import { auth, buildPathWithParams, getAccessToken, getReturnToPath } from 'lib/gotrue'
import { tweets } from 'shared-data'
import { Button, IconFileText } from 'ui'
@@ -27,7 +26,6 @@ const SignInLayout = ({
children,
}: PropsWithChildren<SignInLayoutProps>) => {
const router = useRouter()
- const pushNext = usePushNext()
const queryClient = useQueryClient()
const { resolvedTheme } = useTheme()
const ongoingIncident = useFlag('ongoingIncident')
@@ -64,7 +62,7 @@ const SignInLayout = ({
}
await queryClient.resetQueries()
- await pushNext()
+ router.push(getReturnToPath())
} else {
// if the user doesn't have a token, he needs to go back to the sign-in page
const redirectTo = buildPathWithParams('/sign-in')
@@ -194,4 +192,4 @@ const SignInLayout = ({
)
}
-export default observer(SignInLayout)
+export default SignInLayout
diff --git a/studio/hooks/misc/useAutoAuthRedirect.tsx b/studio/hooks/misc/useAutoAuthRedirect.tsx
deleted file mode 100644
index 6921bb3d6a3..00000000000
--- a/studio/hooks/misc/useAutoAuthRedirect.tsx
+++ /dev/null
@@ -1,92 +0,0 @@
-import { QueryClient } from '@tanstack/react-query'
-import { auth, getAccessToken, getReturnToPath } from 'lib/gotrue'
-import { useRouter } from 'next/router'
-import { useCallback, useEffect } from 'react'
-
-export function usePushNext() {
- const router = useRouter()
-
- return useCallback(
- async () => {
- const searchParams = new URLSearchParams(location.search)
-
- const hasNext = searchParams.has('next')
-
- // preference the next param, as it's used for integration redirects
- if (hasNext) {
- const next = searchParams.get('next')!
-
- // vercel integration
- const isVercelIntegration = next.includes('https://vercel.com')
- if (isVercelIntegration) {
- return
- }
-
- // database.new integration
- if (next === 'new-project') {
- searchParams.delete('next')
- searchParams.delete('returnTo')
- const remainingSearchParams = searchParams.toString()
-
- return await router.push(
- '/new/new-project' + (remainingSearchParams ? `?${remainingSearchParams}` : '')
- )
- }
-
- return await router.push(
- next + (searchParams.toString() ? `?${searchParams.toString()}` : '')
- )
- }
-
- return await router.push(getReturnToPath())
- },
- // watch params so router.query will get updated
- [router.query]
- )
-}
-
-function useAutoAuthRedirect(queryClient: QueryClient) {
- const pushNext = usePushNext()
-
- useEffect(() => {
- const searchParams = new URLSearchParams(location.search)
- const hasReturnTo = searchParams.has('returnTo')
- const hasNext = searchParams.has('next')
- const shouldRedirect = hasReturnTo || hasNext
-
- if (!shouldRedirect) {
- // If there's no returnTo or next, then we don't need to do anything
- return
- }
-
- auth
- .initialize()
- .then(async ({ error }) => {
- if (error) {
- // if there was a problem signing in via the url, don't redirect
- return
- }
-
- const token = await getAccessToken()
-
- if (token) {
- const { data, error } = await auth.mfa.getAuthenticatorAssuranceLevel()
- if (error) {
- // if there was a problem fetching the user AAL levels, don't redirect
- return
- }
-
- // if the user doesn't have the appropriate AAL level, don't redirect
- if (data.currentLevel !== data.nextLevel) {
- return
- }
-
- await queryClient.resetQueries()
- await pushNext()
- }
- })
- .catch(() => {}) // catch all errors thrown by auth methods
- }, [])
-}
-
-export default useAutoAuthRedirect
diff --git a/studio/hooks/misc/withAuth.tsx b/studio/hooks/misc/withAuth.tsx
index baffaec3038..4b345844e01 100644
--- a/studio/hooks/misc/withAuth.tsx
+++ b/studio/hooks/misc/withAuth.tsx
@@ -1,24 +1,12 @@
import { useRouter } from 'next/router'
-import Script from 'next/script'
import { ComponentType, useEffect } from 'react'
-import { useParams } from 'common/hooks'
import { usePermissionsQuery } from 'data/permissions/permissions-query'
import { useAuthenticatorAssuranceLevelQuery } from 'data/profile/mfa-authenticator-assurance-level-query'
import { useSelectedProject, useStore } from 'hooks'
import { useAuth } from 'lib/auth'
import { IS_PLATFORM } from 'lib/constants'
-import { STORAGE_KEY, getReturnToPath } from 'lib/gotrue'
import { NextPageWithLayout, isNextPageWithLayout } from 'types'
-import Error500 from '../../pages/500'
-
-const PLATFORM_ONLY_PAGES = [
- 'reports',
- 'settings',
- 'auth/providers',
- 'auth/templates',
- 'auth/url-configuration',
-]
export function withAuth<T>(
WrappedComponent: ComponentType<T> | NextPageWithLayout<T, T>,
@@ -34,18 +22,26 @@ export function withAuth<T>(
useHighestAAL: boolean
} = { useHighestAAL: true }
) {
+ // ignore auth in self-hosted
+ if (!IS_PLATFORM) {
+ return WrappedComponent
+ }
+
const WithAuthHOC: ComponentType<T> = (props) => {
const router = useRouter()
- const { basePath } = router
- const { ref } = useParams()
const rootStore = useStore()
- const { isLoading, session } = useAuth()
- const { isLoading: isAALLoading, data: aalData } = useAuthenticatorAssuranceLevelQuery()
-
const { ui } = rootStore
- const page = router.pathname.split('/').slice(3).join('/')
- const redirectTo = defaultRedirectTo(ref)
+ const { isLoading, session } = useAuth()
+ const { isLoading: isAALLoading, data: aalData } = useAuthenticatorAssuranceLevelQuery({
+ onError(error) {
+ ui.setNotification({
+ error,
+ category: 'error',
+ message: `Failed to fetch authenticator assurance level: ${error.message}. Try refreshing your browser, or reach out to us via a support ticket if the issue persists`,
+ })
+ },
+ })
usePermissionsQuery({
onError(error: any) {
@@ -58,32 +54,25 @@ export function withAuth<T>(
})
const isLoggedIn = Boolean(session)
- const isCorrectLevel = options.useHighestAAL
- ? aalData?.currentLevel === aalData?.nextLevel
- : true
-
- const isAccessingBlockedPage =
- !IS_PLATFORM &&
- PLATFORM_ONLY_PAGES.some((platformOnlyPage) => page.startsWith(platformOnlyPage))
- const isRedirecting =
- isAccessingBlockedPage ||
- checkRedirectTo(
- isLoading || isAALLoading,
- router.pathname,
- isLoggedIn,
- isCorrectLevel,
- redirectTo
- )
+ const isFinishedLoading = !isLoading && !isAALLoading
useEffect(() => {
- // This should run after setting store data
- if (isRedirecting) {
+ const isCorrectLevel = options.useHighestAAL
+ ? aalData?.currentLevel === aalData?.nextLevel
+ : true
+
+ if (isFinishedLoading && (!isLoggedIn || !isCorrectLevel)) {
const searchParams = new URLSearchParams(location.search)
- searchParams.set('returnTo', location.pathname)
- const url = `${redirectTo}?${searchParams.toString()}`
- router.push(url)
+ let pathname = location.pathname
+ if (process.env.NEXT_PUBLIC_BASE_PATH) {
+ pathname = pathname.replace(process.env.NEXT_PUBLIC_BASE_PATH, '')
+ }
+
+ searchParams.set('returnTo', pathname)
+
+ router.push(`/sign-in?${searchParams.toString()}`)
}
- }, [isRedirecting, redirectTo])
+ }, [session, isLoading, router, aalData, isFinishedLoading, isLoggedIn])
const selectedProject = useSelectedProject()
useEffect(() => {
@@ -92,33 +81,9 @@ export function withAuth<T>(
}
}, [selectedProject])
- if (!isLoading && !isRedirecting && !isLoggedIn) {
- return <Error500 />
- }
-
const InnerComponent = WrappedComponent as any
- return (
- <>
- {/* This script will quickly (before the main JS loads) redirect the user
- to the login page if they are guaranteed (no token at all) to not be logged in. */}
- {IS_PLATFORM && (
- <Script
- id="redirect-if-not-logged-in"
- dangerouslySetInnerHTML={{
- __html: `
- window._getReturnToPath = ${getReturnToPath.toString()};
- if (!localStorage.getItem('${STORAGE_KEY}') && !location.hash) {
- const searchParams = new URLSearchParams(location.search);
- searchParams.set('returnTo', location.pathname);
- location.replace('${basePath ?? ''}/sign-in' + '?' + searchParams.toString())
- }`,
- }}
- />
- )}
- <InnerComponent {...props} />
- </>
- )
+ return <InnerComponent {...props} />
}
WithAuthHOC.displayName = `withAuth(${WrappedComponent.displayName})`
@@ -129,23 +94,3 @@ export function withAuth<T>(
return WithAuthHOC
}
-
-function defaultRedirectTo(ref: string | string[] | undefined) {
- return IS_PLATFORM ? `/sign-in` : ref !== undefined ? `/project/${ref}` : '/projects'
-}
-
-function checkRedirectTo(
- loading: boolean,
- pathname: string,
- isLoggedIn: boolean,
- isCorrectLevel: boolean,
- redirectTo: string
-) {
- if (loading) return false
- if (pathname === redirectTo) return false
-
- // If redirectTo is set, redirect if the user is not logged in or logged in with MFA.
- if (redirectTo && (!isLoggedIn || !isCorrectLevel)) return true
-
- return false
-}
diff --git a/studio/lib/gotrue.ts b/studio/lib/gotrue.ts
index ad02f5c857f..71400a43f0d 100644
--- a/studio/lib/gotrue.ts
+++ b/studio/lib/gotrue.ts
@@ -75,15 +75,14 @@ export const buildPathWithParams = (pathname: string) => {
return `${pathname}?${searchParams.toString()}`
}
-// NOTE: do not use any imports in this function as it is used standalone in the documents head
-// [Joshen] Potentially can remove after full move over to /dashboard
export const getReturnToPath = (fallback = '/projects') => {
const searchParams = new URLSearchParams(location.search)
- // [Joshen] Remove base path value ("/dashboard") from returnTo
- // because we're having this in the document's head, we won't have access
- // to process.env, hardcoding the value as a workaround
- const returnTo = (searchParams.get('returnTo') ?? fallback).replace('/dashboard', '')
+ let returnTo = searchParams.get('returnTo') ?? fallback
+
+ if (process.env.NEXT_PUBLIC_BASE_PATH) {
+ returnTo = returnTo.replace(process.env.NEXT_PUBLIC_BASE_PATH, '')
+ }
searchParams.delete('returnTo')
@@ -91,7 +90,7 @@ export const getReturnToPath = (fallback = '/projects') => {
let validReturnTo
- // only allow returning to internal pages. e.g. /dashboard
+ // only allow returning to internal pages. e.g. /projects
try {
// if returnTo is a relative path, this will throw an error
new URL(returnTo)
diff --git a/studio/next.config.js b/studio/next.config.js
index 71d9256f78d..b407efe2ff1 100644
--- a/studio/next.config.js
+++ b/studio/next.config.js
@@ -31,7 +31,19 @@ const nextConfig = {
return [
{
source: '/',
- destination: '/sign-in',
+ has: [
+ {
+ type: 'query',
+ key: 'next',
+ value: 'new-project',
+ },
+ ],
+ destination: '/new/new-project',
+ permanent: false,
+ },
+ {
+ source: '/',
+ destination: '/projects',
permanent: false,
},
{
diff --git a/studio/pages/_app.tsx b/studio/pages/_app.tsx
index 809b18b8490..46ef0021370 100644
--- a/studio/pages/_app.tsx
+++ b/studio/pages/_app.tsx
@@ -49,7 +49,6 @@ import FlagProvider from 'components/ui/Flag/FlagProvider'
import PageTelemetry from 'components/ui/PageTelemetry'
import { useRootQueryClient } from 'data/query-client'
import { StoreProvider } from 'hooks'
-import useAutoAuthRedirect from 'hooks/misc/useAutoAuthRedirect'
import { AuthProvider } from 'lib/auth'
import { BASE_PATH, IS_PLATFORM, LOCAL_STORAGE_KEYS } from 'lib/constants'
import { dart } from 'lib/constants/prism'
@@ -100,8 +99,6 @@ function CustomApp({ Component, pageProps }: AppPropsWithLayout) {
: undefined
)
- useAutoAuthRedirect(queryClient)
-
const getLayout = Component.getLayout ?? ((page) => page)
const AuthContainer = useMemo(
diff --git a/studio/pages/new/[slug].tsx b/studio/pages/new/[slug].tsx
index a9becae5169..59fb7988061 100644
--- a/studio/pages/new/[slug].tsx
+++ b/studio/pages/new/[slug].tsx
@@ -1,8 +1,7 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useParams } from 'common'
import generator from 'generate-password'
-import { debounce, isUndefined } from 'lodash'
-import { observer } from 'mobx-react-lite'
+import { debounce } from 'lodash'
import Link from 'next/link'
import { useRouter } from 'next/router'
import { PropsWithChildren, useEffect, useRef, useState } from 'react'
@@ -84,7 +83,7 @@ const Wizard: NextPageWithLayout = () => {
)
const isAdmin = useCheckPermissions(PermissionAction.CREATE, 'projects')
- const isInvalidSlug = isUndefined(currentOrg)
+ const isInvalidSlug = currentOrg !== undefined
const isEmptyOrganizations = (organizations?.length ?? 0) <= 0 && isOrganizationsSuccess
const hasMembersExceedingFreeTierLimit = (membersExceededLimit || []).length > 0
@@ -104,28 +103,32 @@ const Wizard: NextPageWithLayout = () => {
debounce((value) => checkPasswordStrength(value), 300)
).current
- /*
- * Handle no org
- * redirect to new org route
- */
- if (isEmptyOrganizations) {
- router.push(`/new`)
- }
+ useEffect(() => {
+ /*
+ * Handle no org
+ * redirect to new org route
+ */
+ if (isEmptyOrganizations) {
+ router.push(`/new`)
+ }
+ }, [isEmptyOrganizations, router])
- /*
- * Redirect to first org if the slug doesn't match an org slug
- * this is mainly to capture the /project/new url, which is redirected from database.new
- */
- if (isInvalidSlug && (organizations?.length ?? 0) > 0) {
- router.push(`/new/${organizations?.[0].slug}`)
- }
+ useEffect(() => {
+ /*
+ * Redirect to first org if the slug doesn't match an org slug
+ * this is mainly to capture the /project/new url, which is redirected from database.new
+ */
+ if (isInvalidSlug && (organizations?.length ?? 0) > 0) {
+ router.push(`/new/${organizations?.[0].slug}`)
+ }
+ }, [isInvalidSlug, organizations, router])
useEffect(() => {
// User added a new payment method
if (router.query.setup_intent && router.query.redirect_status) {
ui.setNotification({ category: 'success', message: 'Successfully added new payment method' })
}
- }, [])
+ }, [router.query.redirect_status, router.query.setup_intent, ui])
function onProjectNameChange(e: any) {
e.target.value = e.target.value.replace(/\./g, '')
@@ -507,7 +510,7 @@ const PageLayout = withAuth(({ children }: PropsWithChildren) => {
const { slug } = useParams()
const { data: organizations } = useOrganizationsQuery()
- const currentOrg = organizations?.find((o: any) => o.slug === slug)
+ const currentOrg = organizations?.find((o) => o.slug === slug)
return (
<WizardLayoutWithoutAuth organization={currentOrg} project={null}>
@@ -518,4 +521,4 @@ const PageLayout = withAuth(({ children }: PropsWithChildren) => {
Wizard.getLayout = (page) => <PageLayout>{page}</PageLayout>
-export default observer(Wizard)
+export default Wizard
diff --git a/studio/pages/sign-in-mfa.tsx b/studio/pages/sign-in-mfa.tsx
index fbc47d7dd03..eaee6c12a22 100644
--- a/studio/pages/sign-in-mfa.tsx
+++ b/studio/pages/sign-in-mfa.tsx
@@ -2,8 +2,7 @@ import { useQueryClient } from '@tanstack/react-query'
import SignInMfaForm from 'components/interfaces/SignIn/SignInMfaForm'
import { SignInLayout } from 'components/layouts'
import Loading from 'components/ui/Loading'
-import { usePushNext } from 'hooks/misc/useAutoAuthRedirect'
-import { auth, buildPathWithParams, getAccessToken } from 'lib/gotrue'
+import { auth, buildPathWithParams, getAccessToken, getReturnToPath } from 'lib/gotrue'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import toast from 'react-hot-toast'
@@ -12,7 +11,6 @@ import { NextPageWithLayout } from 'types'
const SignInMfaPage: NextPageWithLayout = () => {
const router = useRouter()
const [loading, setLoading] = useState(true)
- const pushNext = usePushNext()
const queryClient = useQueryClient()
// This useEffect redirects the user to MFA if they're already halfway signed in
@@ -36,13 +34,14 @@ const SignInMfaPage: NextPageWithLayout = () => {
`Failed to retrieve assurance level: ${error.message}. Please try signing in again`
)
setLoading(false)
- return router.push('/sign-in')
+ return router.push({ pathname: '/sign-in', query: router.query })
}
if (data) {
if (data.currentLevel === data.nextLevel) {
await queryClient.resetQueries()
- await pushNext()
+ router.push(getReturnToPath())
+
return
}
if (data.currentLevel !== data.nextLevel) {