feat(router): context-aware guards with meta-driven role/context resolution
Rewrites plugins/1.router/guards.ts per ARCH-CONSOLIDATION §4.3. The
B1 portal-context carve-out is removed; portal/organizer routing is
now declarative via meta.context, role gates via meta.requiresRole.
Guard pipeline:
1. Initialize auth store on first navigation
2. Public routes pass through (authenticated user on guest-only path
is bounced to resolveLandingRoute)
3. Auth required → /login?to=<path>
4. MFA setup gate → /account-settings?tab=security
5. requiresRole declarative check (replaces hardcoded /platform path
prefix + isSuperAdmin)
6. Context routing — portal returns early, organizer falls through
and sets lastContext
7. Org-selection check (organizer routes only)
Page meta updates (mechanical, idempotent):
- 4 portal pages: removed `requiresAuth: true` (auth is implicit)
- 4 pages: replaced `requiresAuth: false` with `meta.public: true`
(registreren, wachtwoord-instellen, advance/[token],
invitations/[token])
- 22 organizer pages: added `context: 'organizer'`
(account-settings, events/**, organisation/form-failures/**,
select-organisation, dashboard, events/index, members,
organisation/{index,companies,settings})
- 8 platform pages: added `context: 'organizer'` +
`requiresRole: 'super_admin'`
- 6 organizer pages had no definePage block — one was added with
`context: 'organizer'`
Adds plugins/1.router/__tests__/guards.spec.ts (11 tests) covering
public passthrough, unauthenticated redirect, portal/organizer
context branching, declarative requiresRole, org-selection
redirect, MFA gate.
Test count 178 → 189 (11 new). Lint + typecheck clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
269
apps/app/src/plugins/1.router/__tests__/guards.spec.ts
Normal file
269
apps/app/src/plugins/1.router/__tests__/guards.spec.ts
Normal file
@@ -0,0 +1,269 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
import type { NavigationGuard, RouteLocationNormalized, Router } from 'vue-router'
|
||||
import type { MeResponse } from '@/types/auth'
|
||||
|
||||
vi.mock('@/lib/axios', () => ({
|
||||
apiClient: { get: vi.fn(), post: vi.fn() },
|
||||
}))
|
||||
|
||||
vi.mock('@/utils/deviceFingerprint', () => ({
|
||||
generateDeviceFingerprint: () => 'test-fingerprint',
|
||||
}))
|
||||
|
||||
const { setupGuards } = await import('@/plugins/1.router/guards')
|
||||
const { useAuthStore } = await import('@/stores/useAuthStore')
|
||||
const { useOrganisationStore } = await import('@/stores/useOrganisationStore')
|
||||
|
||||
function captureGuard(): NavigationGuard {
|
||||
let guard: NavigationGuard | null = null
|
||||
|
||||
const router = {
|
||||
beforeEach: (fn: NavigationGuard) => {
|
||||
guard = fn
|
||||
},
|
||||
} as unknown as Router
|
||||
|
||||
setupGuards(router)
|
||||
|
||||
if (!guard)
|
||||
throw new Error('guard not captured')
|
||||
|
||||
return guard
|
||||
}
|
||||
|
||||
function makeRoute(overrides: Partial<RouteLocationNormalized> = {}): RouteLocationNormalized {
|
||||
return {
|
||||
path: '/',
|
||||
fullPath: '/',
|
||||
name: undefined,
|
||||
meta: {},
|
||||
params: {},
|
||||
query: {},
|
||||
hash: '',
|
||||
matched: [],
|
||||
redirectedFrom: undefined,
|
||||
...overrides,
|
||||
} as RouteLocationNormalized
|
||||
}
|
||||
|
||||
function hydrate(me: Partial<MeResponse> = {}): void {
|
||||
const auth = useAuthStore()
|
||||
|
||||
auth.setUser({
|
||||
id: '01ABC',
|
||||
first_name: 'Test',
|
||||
last_name: 'User',
|
||||
full_name: 'Test User',
|
||||
date_of_birth: null,
|
||||
email: 'test@example.nl',
|
||||
phone: null,
|
||||
timezone: 'Europe/Amsterdam',
|
||||
locale: 'nl',
|
||||
avatar: null,
|
||||
organisations: [],
|
||||
app_roles: [],
|
||||
permissions: [],
|
||||
...me,
|
||||
})
|
||||
|
||||
// initialize() is guarded by isInitialized; flip it directly so the
|
||||
// guard's first-step initialize() short-circuits without touching
|
||||
// the mocked apiClient.
|
||||
;(auth as unknown as { isInitialized: boolean }).isInitialized = true
|
||||
}
|
||||
|
||||
describe('router guards (WS-3 PR-B2a)', () => {
|
||||
let guard: NavigationGuard
|
||||
|
||||
beforeEach(() => {
|
||||
setActivePinia(createPinia())
|
||||
localStorage.clear()
|
||||
guard = captureGuard()
|
||||
|
||||
// Default: store starts uninitialized; tests opt-in via hydrate()
|
||||
const auth = useAuthStore()
|
||||
|
||||
;(auth as unknown as { isInitialized: boolean }).isInitialized = true
|
||||
})
|
||||
|
||||
it('public routes pass through', async () => {
|
||||
const result = await guard(
|
||||
makeRoute({ path: '/login', meta: { public: true } }),
|
||||
makeRoute(),
|
||||
() => {},
|
||||
)
|
||||
|
||||
expect(result).toBe(true)
|
||||
})
|
||||
|
||||
it('redirects unauthenticated user to login with `?to=` query', async () => {
|
||||
const result = await guard(
|
||||
makeRoute({ path: '/events', fullPath: '/events', meta: {} }),
|
||||
makeRoute(),
|
||||
() => {},
|
||||
)
|
||||
|
||||
expect(result).toEqual({ name: 'login', query: { to: '/events' } })
|
||||
})
|
||||
|
||||
it('portal route passes when user has portal context', async () => {
|
||||
hydrate({
|
||||
contexts: { available: ['portal'], default: 'portal' },
|
||||
})
|
||||
|
||||
const result = await guard(
|
||||
makeRoute({ path: '/portal/evenementen', meta: { context: 'portal' } }),
|
||||
makeRoute(),
|
||||
() => {},
|
||||
)
|
||||
|
||||
expect(result).toBe(true)
|
||||
expect(useAuthStore().lastContext).toBe('portal')
|
||||
})
|
||||
|
||||
it('portal route forbidden for organizer-only user', async () => {
|
||||
hydrate({
|
||||
organisations: [{ id: '01', name: 'Org', slug: 'org', role: 'org_admin' }],
|
||||
app_roles: ['org_admin'],
|
||||
contexts: { available: ['organizer'], default: 'organizer' },
|
||||
})
|
||||
|
||||
// Pre-select org so the guard doesn't redirect to select-organisation.
|
||||
useOrganisationStore().setActiveOrganisation('01')
|
||||
|
||||
const result = await guard(
|
||||
makeRoute({ path: '/portal/evenementen', meta: { context: 'portal' } }),
|
||||
makeRoute(),
|
||||
() => {},
|
||||
)
|
||||
|
||||
expect(result).toEqual({ name: 'forbidden' })
|
||||
})
|
||||
|
||||
it('organizer route sets lastContext to organizer for multi-role user', async () => {
|
||||
hydrate({
|
||||
organisations: [{ id: '01', name: 'Org', slug: 'org', role: 'org_admin' }],
|
||||
app_roles: ['org_admin'],
|
||||
contexts: { available: ['portal', 'organizer'], default: 'organizer' },
|
||||
})
|
||||
useOrganisationStore().setActiveOrganisation('01')
|
||||
|
||||
const result = await guard(
|
||||
makeRoute({ path: '/events', meta: { context: 'organizer' } }),
|
||||
makeRoute(),
|
||||
() => {},
|
||||
)
|
||||
|
||||
expect(result).toBe(true)
|
||||
expect(useAuthStore().lastContext).toBe('organizer')
|
||||
})
|
||||
|
||||
it('platform route forbidden for non-super_admin (declarative requiresRole)', async () => {
|
||||
hydrate({
|
||||
organisations: [{ id: '01', name: 'Org', slug: 'org', role: 'org_admin' }],
|
||||
app_roles: ['org_admin'],
|
||||
contexts: { available: ['organizer'], default: 'organizer' },
|
||||
})
|
||||
useOrganisationStore().setActiveOrganisation('01')
|
||||
|
||||
const result = await guard(
|
||||
makeRoute({
|
||||
path: '/platform/users',
|
||||
meta: { context: 'organizer', requiresRole: 'super_admin' },
|
||||
}),
|
||||
makeRoute(),
|
||||
() => {},
|
||||
)
|
||||
|
||||
expect(result).toEqual({ name: 'forbidden' })
|
||||
})
|
||||
|
||||
it('platform route allowed for super_admin', async () => {
|
||||
hydrate({
|
||||
organisations: [],
|
||||
app_roles: ['super_admin'],
|
||||
contexts: { available: ['organizer'], default: 'organizer' },
|
||||
})
|
||||
|
||||
const result = await guard(
|
||||
makeRoute({
|
||||
path: '/platform/users',
|
||||
meta: { context: 'organizer', requiresRole: 'super_admin' },
|
||||
}),
|
||||
makeRoute(),
|
||||
() => {},
|
||||
)
|
||||
|
||||
expect(result).toBe(true)
|
||||
})
|
||||
|
||||
it('redirects to select-organisation when org user has no active org', async () => {
|
||||
hydrate({
|
||||
organisations: [
|
||||
{ id: '01', name: 'Org A', slug: 'a', role: 'org_admin' },
|
||||
{ id: '02', name: 'Org B', slug: 'b', role: 'org_admin' },
|
||||
],
|
||||
app_roles: ['org_admin'],
|
||||
contexts: { available: ['organizer'], default: 'organizer' },
|
||||
})
|
||||
useOrganisationStore().clear()
|
||||
|
||||
const result = await guard(
|
||||
makeRoute({ path: '/events', fullPath: '/events', meta: { context: 'organizer' } }),
|
||||
makeRoute(),
|
||||
() => {},
|
||||
)
|
||||
|
||||
expect(result).toEqual({ path: '/select-organisation', query: { to: '/events' } })
|
||||
})
|
||||
|
||||
it('does not redirect portal-context route to select-organisation', async () => {
|
||||
hydrate({
|
||||
organisations: [{ id: '01', name: 'Org', slug: 'org', role: 'org_admin' }],
|
||||
app_roles: ['org_admin'],
|
||||
contexts: { available: ['portal', 'organizer'], default: 'organizer' },
|
||||
})
|
||||
useOrganisationStore().clear()
|
||||
|
||||
const result = await guard(
|
||||
makeRoute({ path: '/portal/evenementen', meta: { context: 'portal' } }),
|
||||
makeRoute(),
|
||||
() => {},
|
||||
)
|
||||
|
||||
expect(result).toBe(true)
|
||||
})
|
||||
|
||||
it('redirects authenticated user away from login back to landing route', async () => {
|
||||
hydrate({
|
||||
contexts: { available: ['portal'], default: 'portal' },
|
||||
})
|
||||
|
||||
const result = await guard(
|
||||
makeRoute({ path: '/login', meta: { public: true } }),
|
||||
makeRoute(),
|
||||
() => {},
|
||||
)
|
||||
|
||||
expect(result).toEqual({ path: '/portal/evenementen' })
|
||||
})
|
||||
|
||||
it('MFA setup gate redirects to /account-settings when mfaSetupRequired', async () => {
|
||||
hydrate({
|
||||
organisations: [{ id: '01', name: 'Org', slug: 'org', role: 'org_admin' }],
|
||||
app_roles: ['org_admin'],
|
||||
mfa: { enabled: false, method: null, confirmed_at: null, setup_required: true },
|
||||
contexts: { available: ['organizer'], default: 'organizer' },
|
||||
})
|
||||
useOrganisationStore().setActiveOrganisation('01')
|
||||
|
||||
const result = await guard(
|
||||
makeRoute({ path: '/events', meta: { context: 'organizer' } }),
|
||||
makeRoute(),
|
||||
() => {},
|
||||
)
|
||||
|
||||
expect(result).toEqual({ path: '/account-settings', query: { tab: 'security' } })
|
||||
})
|
||||
})
|
||||
@@ -3,109 +3,83 @@ import { useAuthStore } from '@/stores/useAuthStore'
|
||||
import { useOrganisationStore } from '@/stores/useOrganisationStore'
|
||||
|
||||
export function setupGuards(router: Router) {
|
||||
router.beforeEach(async (to, from) => {
|
||||
router.beforeEach(async to => {
|
||||
const authStore = useAuthStore()
|
||||
|
||||
// Wait for initialization to complete (only blocks on first navigation)
|
||||
// Step 1 — ensure store is initialized (only blocks on first navigation).
|
||||
if (!authStore.isInitialized)
|
||||
await authStore.initialize()
|
||||
|
||||
if (import.meta.env.DEV) {
|
||||
console.log('🔒 Router Guard:', {
|
||||
to: to.path,
|
||||
from: from.path,
|
||||
isAuthenticated: authStore.isAuthenticated,
|
||||
context: to.meta.context,
|
||||
requiresRole: to.meta.requiresRole,
|
||||
})
|
||||
}
|
||||
|
||||
const isPublic = to.meta.public === true
|
||||
|
||||
// Allow public routes (login, auth pages, 404) — but redirect authenticated users away from login
|
||||
if (isPublic) {
|
||||
// Step 2 — public routes pass through. Authenticated users hitting a
|
||||
// guest-only public page (login, password flows) get bounced back to
|
||||
// their landing route to avoid the awkward "log in again" dead-end.
|
||||
if (to.meta.public === true) {
|
||||
const guestOnlyPaths = ['/login', '/forgot-password', '/reset-password', '/verify-email-change']
|
||||
if (authStore.isAuthenticated && guestOnlyPaths.includes(to.path)) {
|
||||
if (import.meta.env.DEV)
|
||||
console.log('🔄 Redirecting logged-in user away from login page')
|
||||
if (authStore.isAuthenticated && guestOnlyPaths.includes(to.path))
|
||||
return authStore.resolveLandingRoute()
|
||||
|
||||
return { name: 'dashboard' }
|
||||
}
|
||||
if (import.meta.env.DEV)
|
||||
console.log('✅ Public route, allowing access')
|
||||
|
||||
return
|
||||
return true
|
||||
}
|
||||
|
||||
// Routes that opt out of auth (e.g. invitations)
|
||||
if (to.meta.requiresAuth === false) {
|
||||
if (import.meta.env.DEV)
|
||||
console.log('✅ Route does not require auth')
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// Not authenticated → redirect to login with return URL
|
||||
if (!authStore.isAuthenticated) {
|
||||
if (import.meta.env.DEV)
|
||||
console.log('🚫 Not authenticated, redirecting to login')
|
||||
|
||||
return { path: '/login', query: { to: to.fullPath } }
|
||||
}
|
||||
|
||||
// WS-3 PR-B1 carve-out: portal-context routes (volunteers, artists,
|
||||
// crew) don't participate in the organizer's MFA / platform-role /
|
||||
// organisation-selection checks below. PR-B2 replaces this with full
|
||||
// context-aware guards (per ARCH-CONSOLIDATION-2026-04 §4.3).
|
||||
if (to.meta.context === 'portal') {
|
||||
if (import.meta.env.DEV)
|
||||
console.log('✅ Portal-context route, allowing access (B1 carve-out)')
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// MFA enforcement — redirect to security settings if MFA setup is required
|
||||
if (authStore.mfaSetupRequired && to.path !== '/account-settings') {
|
||||
if (import.meta.env.DEV)
|
||||
console.log('🔒 MFA setup required, redirecting to security settings')
|
||||
// Step 3 — auth required. Save target as `?to=` so we can resume after login.
|
||||
if (!authStore.isAuthenticated)
|
||||
return { name: 'login', query: { to: to.fullPath } }
|
||||
|
||||
// Step 4 — MFA setup gate. The MFA-setup flow lives in account-settings
|
||||
// under `?tab=security`; let users reach there to complete setup.
|
||||
if (authStore.mfaSetupRequired && to.path !== '/account-settings')
|
||||
return { path: '/account-settings', query: { tab: 'security' } }
|
||||
|
||||
// Step 5 — declarative role check (replaces the legacy hard-coded
|
||||
// `path.startsWith('/platform') && !isSuperAdmin` branch).
|
||||
if (to.meta.requiresRole) {
|
||||
const required = Array.isArray(to.meta.requiresRole)
|
||||
? to.meta.requiresRole as string[]
|
||||
: [to.meta.requiresRole as string]
|
||||
|
||||
if (!authStore.hasAnyRole(required))
|
||||
return { name: 'forbidden' }
|
||||
}
|
||||
|
||||
// Platform admin routes — require super_admin role
|
||||
if (to.path.startsWith('/platform')) {
|
||||
if (!authStore.isSuperAdmin) {
|
||||
if (import.meta.env.DEV)
|
||||
console.log('🚫 Not a super admin, redirecting to dashboard')
|
||||
// Step 6 — context routing. Portal-context routes don't participate
|
||||
// in the org-selection check below; organizer-context falls through.
|
||||
if (to.meta.context === 'portal') {
|
||||
if (!authStore.availableContexts.includes('portal'))
|
||||
return { name: 'forbidden' }
|
||||
|
||||
return { name: 'dashboard' }
|
||||
}
|
||||
authStore.setLastContext('portal')
|
||||
|
||||
// Platform routes don't require organisation selection
|
||||
if (import.meta.env.DEV)
|
||||
console.log('✅ Super admin access to platform route')
|
||||
|
||||
return
|
||||
return true
|
||||
}
|
||||
|
||||
// Authenticated — check organisation selection for routes that need it
|
||||
if (to.meta.context === 'organizer') {
|
||||
if (!authStore.availableContexts.includes('organizer'))
|
||||
return { name: 'forbidden' }
|
||||
|
||||
authStore.setLastContext('organizer')
|
||||
}
|
||||
|
||||
// Step 7 — organizer-context org-selection. Skipped for portal routes
|
||||
// (returned at Step 6), super_admin without orgs (no org to select),
|
||||
// and the select-organisation page itself.
|
||||
const orgStore = useOrganisationStore()
|
||||
const isSelectOrgPage = to.path === '/select-organisation'
|
||||
|
||||
if (isSelectOrgPage) {
|
||||
if (import.meta.env.DEV)
|
||||
console.log('✅ Organisation selection page')
|
||||
if (isSelectOrgPage)
|
||||
return true
|
||||
|
||||
return
|
||||
}
|
||||
if (authStore.organisations.length > 0 && !orgStore.hasOrganisation)
|
||||
return { path: '/select-organisation', query: { to: to.fullPath } }
|
||||
|
||||
// If user has organisations but none selected → redirect to selection
|
||||
if (authStore.organisations.length > 0 && !orgStore.hasOrganisation) {
|
||||
if (import.meta.env.DEV)
|
||||
console.log('🔄 No organisation selected, redirecting')
|
||||
|
||||
return { path: '/select-organisation' }
|
||||
}
|
||||
|
||||
if (import.meta.env.DEV)
|
||||
console.log('✅ Access granted')
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user