Files
supabase/apps/studio/components/interfaces/App/RouteValidationWrapper.tsx
Joshen Lim fd0f2dd459 Scope last visited organization local storage to profile (#47071)
## Context

If a user switches account without an explicit log out via the
dashboard, landing back on `/org` will redirect users to the last
visited organization as stored in local storage, in which it can result
in the following state if the last visited organization does not exist
in the current account
<img width="2538" height="1060" alt="image"
src="https://github.com/user-attachments/assets/270e482a-3515-48ef-898b-87e76fce80d6"
/>

## Changes involved
Am opting to scope the last visited organization to the user profile
instead - this would be a bit more cleaner than trying to actively clear
the last visited org slug from local storage with implicit account
changes as there's no deterministic way to track that (afaik) from FE
side of things

## To test
Can reproduce the problem as such
- Ensure that you have 2 accounts to log in with, and one account has an
org that the other is not a part of
- For the organization that has the "extra" org, ensure that you click
into it so that the last visited org slug is saved in local storage
- Mimic changing accounts by visiting
`/auth/v1/authorize?provider=github` (using the domain for the env that
you're testing on - e.g localhost:8000 for local, or green for staging
preview)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Unified “last visited organization” handling across the Studio UI with
a shared hook, improving consistency for home/dashboard return,
cancel/back navigation, and account routing.

* **Bug Fixes**
* Updated redirects to only route to an organization when a valid
last-visited value is available; otherwise users go to the general
organizations page.
* Kept MFA enrollment and factor delete/leave flows aligned to the
unified last-visited organization value.

* **Tests**
* Updated onboarding and layout tests to match the new last-visited
organization storage key format and hook/query success behavior.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-06-18 17:42:18 +08:00

120 lines
4.0 KiB
TypeScript

import { useIsLoggedIn, useIsMFAEnabled, useParams } from 'common'
import { useRouter } from 'next/router'
import { PropsWithChildren, useEffect } from 'react'
import { toast } from 'sonner'
import { useOrganizationsQuery } from '@/data/organizations/organizations-query'
import { useProjectDetailQuery } from '@/data/projects/project-detail-query'
import { useDashboardHistory } from '@/hooks/misc/useDashboardHistory'
import { useLastVisitedOrganization } from '@/hooks/misc/useLastVisitedOrganization'
import useLatest from '@/hooks/misc/useLatest'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { IS_PLATFORM } from '@/lib/constants'
// Ideally these could all be within a _middleware when we use Next 12
export const RouteValidationWrapper = ({ children }: PropsWithChildren<{}>) => {
const router = useRouter()
const { ref, slug, id } = useParams()
const { data: organization } = useSelectedOrganizationQuery()
const isLoggedIn = useIsLoggedIn()
const isUserMFAEnabled = useIsMFAEnabled()
const { setLastVisitedSnippet, setLastVisitedTable } = useDashboardHistory()
const { lastVisitedOrganization, setLastVisitedOrganization } = useLastVisitedOrganization()
const DEFAULT_HOME = IS_PLATFORM
? !!lastVisitedOrganization
? `/org/${lastVisitedOrganization}`
: '/organizations'
: '/project/default'
/**
* Array of urls/routes that should be ignored
*/
const excemptUrls: string[] = [
// project creation route, allows the page to self determine it's own route, it will redirect to the first org
// or prompt the user to create an organaization
// this is used by database.dev, usually as /new/new-project
'/new/[slug]',
'/join',
]
/**
* Map through all the urls that are excluded
* from route validation check
*
* @returns a boolean
*/
function isExceptUrl() {
return excemptUrls.includes(router?.pathname)
}
const { isError: isErrorProject, error: projectError } = useProjectDetailQuery({ ref })
const { data: organizations, isSuccess: orgsInitialized } = useOrganizationsQuery({
enabled: isLoggedIn,
})
const organizationsRef = useLatest(organizations)
useEffect(() => {
// check if current route is excempted from route validation check
if (isExceptUrl() || !isLoggedIn) return
if (orgsInitialized && slug) {
// Check validity of organization that user is trying to access
const organizations = organizationsRef.current ?? []
const isValidOrg = organizations.some((org) => org.slug === slug)
if (!isValidOrg) {
toast.error('You do not have access to this organization')
router.push(`${DEFAULT_HOME}?error=org_not_found&org=${slug}`)
return
}
}
}, [orgsInitialized])
useEffect(() => {
// check if current route is excempted from route validation check
if (isExceptUrl() || !isLoggedIn) return
// A successful request to project details will validate access to both project and branches
if (!!ref && isErrorProject) {
// 404 means the project no longer exists (e.g. was deleted), not an access error
if (projectError?.code !== 404) {
toast.error('You do not have access to this project')
}
router.push(DEFAULT_HOME)
return
}
}, [isErrorProject])
useEffect(() => {
if (ref !== undefined && id !== undefined) {
if (router.pathname.endsWith('/sql/[id]') && id !== 'new') {
setLastVisitedSnippet(id)
} else if (router.pathname.endsWith('/editor/[id]')) {
setLastVisitedTable(id)
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ref, id])
useEffect(() => {
if (organization) {
setLastVisitedOrganization(organization.slug)
if (
organization.organization_requires_mfa &&
!isUserMFAEnabled &&
router.pathname !== '/org/[slug]'
) {
router.push(`/org/${organization.slug}`)
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [organization])
return <>{children}</>
}