Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 11 additions & 15 deletions src/platform/cloud/onboarding/onboardingCloudRoutes.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import { computed } from 'vue'
import { mapValues } from 'es-toolkit'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createMemoryHistory, createRouter } from 'vue-router'
import type { RouteLocationNormalized, RouteRecordRaw } from 'vue-router'
import { START_LOCATION, createMemoryHistory, createRouter } from 'vue-router'
import type {
RouteLocationNormalized,
RouteLocationRaw,
RouteRecordRaw
} from 'vue-router'

import { useCurrentUser } from '@/composables/auth/useCurrentUser'
import {
Expand Down Expand Up @@ -50,7 +54,7 @@ const resolvedComponents = await Promise.all(
* before guards run, so the guard observes the final destination and its
* `redirectedFrom` says where the navigation started.
*/
async function attemptNavigation(target: string) {
async function attemptNavigation(target: RouteLocationRaw) {
const router = createRouter({
history: createMemoryHistory(),
routes: cloudOnboardingRoutes
Expand Down Expand Up @@ -290,25 +294,17 @@ const guardedRoutes = ['cloud-login', 'cloud-signup'].map((name) => {
if (typeof route?.beforeEnter !== 'function') {
throw new Error(`${name} has no beforeEnter guard`)
}
return [name, route.beforeEnter, `/cloud/${route.path}`] as const
return [name, route.beforeEnter] as const
})

type GuardedRoute = (typeof guardedRoutes)[number]

async function runGuard(
[name, guard, path]: GuardedRoute,
[name, guard]: GuardedRoute,
query: Record<string, string>
) {
const next = vi.fn()
const to = { query, name, path }
await (
guard as unknown as (
to: unknown,
from: unknown,
next: unknown
) => Promise<void>
)(to, undefined, next)
return next.mock.calls[0]?.[0]
const to = await attemptNavigation({ name, query })
return guard.call(undefined, to, START_LOCATION, () => {})
}

describe.for(guardedRoutes)('%s beforeEnter', (route) => {
Expand Down
10 changes: 4 additions & 6 deletions src/platform/cloud/onboarding/onboardingCloudRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,17 +55,16 @@ export const cloudOnboardingRoutes: RouteRecordRaw[] = [
component: () =>
import('@/platform/cloud/onboarding/CloudLoginView.vue'),
meta: { showTermsNotice: true },
beforeEnter: async (to, _from, next) => {
beforeEnter: async (to) => {
if (!to.query.switchAccount) {
const { useCurrentUser } =
await import('@/composables/auth/useCurrentUser')
const { isLoggedIn } = useCurrentUser()

if (isLoggedIn.value) {
return next(await oauthConsentRedirect())
return oauthConsentRedirect()
}
}
next()
}
},
{
Expand All @@ -74,17 +73,16 @@ export const cloudOnboardingRoutes: RouteRecordRaw[] = [
component: () =>
import('@/platform/cloud/onboarding/CloudSignupView.vue'),
meta: { showTermsNotice: true },
beforeEnter: async (to, _from, next) => {
beforeEnter: async (to) => {
if (!to.query.switchAccount) {
const { useCurrentUser } =
await import('@/composables/auth/useCurrentUser')
const { isLoggedIn } = useCurrentUser()

if (isLoggedIn.value) {
return next(await oauthConsentRedirect())
return oauthConsentRedirect()
}
}
next()
}
},
{
Expand Down
3 changes: 1 addition & 2 deletions src/platform/navigation/preservedQueryTracker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,8 @@ describe('installPreservedQueryTracker', () => {
it('strips keys of multiple marked namespaces in a single redirect', async () => {
const router = createTestRouter()
let navigationAttempts = 0
router.beforeEach((_to, _from, next) => {
router.beforeEach(() => {
navigationAttempts++
next()
})
installPreservedQueryTracker(router, [
strippedDefinition,
Expand Down
9 changes: 3 additions & 6 deletions src/platform/navigation/preservedQueryTracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export const installPreservedQueryTracker = (
router: Router,
definitions: PreservedQueryDefinition[]
) => {
router.beforeEach((to, _from, next) => {
router.beforeEach((to) => {
const queryKeys = new Set(Object.keys(to.query))
const keysToStrip = new Set<string>()

Expand All @@ -82,13 +82,10 @@ export const installPreservedQueryTracker = (
}
)

if (keysToStrip.size === 0) {
next()
return
}
if (keysToStrip.size === 0) return

const cleanedQuery = { ...to.query }
keysToStrip.forEach((key) => delete cleanedQuery[key])
next({ path: to.path, query: cleanedQuery, hash: to.hash })
return { path: to.path, query: cleanedQuery, hash: to.hash }
})
}
52 changes: 23 additions & 29 deletions src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
} from 'vue-router'
import type {
LocationQueryRaw,
NavigationGuardNext,
NavigationGuardReturn,
RouteLocationNormalized
} from 'vue-router'

Expand Down Expand Up @@ -89,15 +89,11 @@ const router = createRouter({
path: '',
name: 'GraphView',
component: () => import('@/views/GraphView.vue'),
beforeEnter: async (_to, _from, next) => {
beforeEnter: async () => {
// Then check user store
const userStore = useUserStore()
await userStore.initialize()
if (userStore.needsLogin) {
next('/user-select')
} else {
next()
}
if (userStore.needsLogin) return '/user-select'
}
},
{
Expand All @@ -121,9 +117,8 @@ const router = createRouter({

installPreservedQueryTracker(router, PRESERVED_QUERY_DEFINITIONS)

router.beforeEach((to, _from, next) => {
router.beforeEach((to) => {
captureOAuthRequestId(to.query)
next()
})

router.afterEach(() => {
Expand Down Expand Up @@ -179,9 +174,8 @@ if (isCloud) {
/** A lapsed SSO session goes back through its identity provider, once per tab per window. */
function sendToSignIn(
to: RouteLocationNormalized,
query: LocationQueryRaw,
next: NavigationGuardNext
): void {
query: LocationQueryRaw
): NavigationGuardReturn {
const ssoError = flags.ssoEnabled
? readSsoError(to.query.sso_error)
: undefined
Expand All @@ -200,20 +194,20 @@ if (isCloud) {
origin: window.location.origin
})
)
return next(false)
return false
}
next({
return {
name: 'cloud-login',
query: {
...query,
...(reentry.kind !== 'login' && SSO_ENTRY_OPEN_QUERY),
...(ssoError && { sso_error: ssoError })
}
})
}
}

// Global authentication guard
router.beforeEach(async (to, _from, next) => {
router.beforeEach(async (to, from) => {
rerouteWhenSignedOutElsewhere()
const authStore = useAuthStore()

Expand All @@ -225,7 +219,7 @@ if (isCloud) {
await until(isInitialized).toBe(true, { timeout: 16_000 })
} catch (error) {
console.error('Auth initialization failed:', error)
return next({ name: 'cloud-auth-timeout' })
return { name: 'cloud-auth-timeout' }
}
}

Expand All @@ -246,21 +240,21 @@ if (isCloud) {

// Allow public routes
if (isPublicRoute(to)) {
return next()
return
}

// Special handling for user-check
// These routes need auth but handle their own routing logic
if (to.name === 'cloud-user-check') {
if (to.meta.requiresAuth && !isLoggedIn) {
return next({ name: 'cloud-login' })
return { name: 'cloud-login' }
}
return next()
return
}

// Prevent redirect loop when coming from user-check
if (_from.name === 'cloud-user-check' && to.path === '/') {
return next()
if (from.name === 'cloud-user-check' && to.path === '/') {
return
}

const query = {
Expand All @@ -272,25 +266,25 @@ if (isCloud) {

// Check if route requires authentication
if (to.meta.requiresAuth && !isLoggedIn) {
return sendToSignIn(to, query, next)
return sendToSignIn(to, query)
}

// Handle other protected routes
if (!isLoggedIn) {
// For Electron, use dialog
if (isDesktop) {
const loginSuccess = await useAuthDialogs().showSignInDialog()
return loginSuccess ? next() : next(false)
return loginSuccess
}

return sendToSignIn(to, query, next)
return sendToSignIn(to, query)
}

// User is logged in - check if they need onboarding (when enabled)
// For root path, check actual user status to handle waitlisted users
if (!isDesktop && to.path === '/') {
if (!flags.onboardingSurveyEnabled) {
return next()
return
}
// Import auth functions dynamically to avoid circular dependency
const { getSurveyCompletedStatus } =
Expand All @@ -303,17 +297,17 @@ if (isCloud) {

// Survey is required for all users (when feature flag enabled)
if (!surveyCompleted) {
return next({ name: 'cloud-survey' })
return { name: 'cloud-survey' }
}
} catch (error) {
console.error('Failed to check user status:', error)
// On error, redirect to user-check as fallback
return next({ name: 'cloud-user-check' })
return { name: 'cloud-user-check' }
}
}

// User is logged in and accessing protected route
return next()
return
})

installDesktopLoginRedemption(router)
Expand Down
Loading