58 lines
1.7 KiB
TypeScript
58 lines
1.7 KiB
TypeScript
export default defineNuxtRouteMiddleware(async (to, from) => {
|
|
// Allow pages to opt-out of auth with definePageMeta({ auth: false })
|
|
if (to.meta.auth === false) {
|
|
return
|
|
}
|
|
|
|
// Public routes that don't require authentication
|
|
const publicRoutes = ['/login', '/register']
|
|
|
|
if (publicRoutes.includes(to.path)) {
|
|
return
|
|
}
|
|
|
|
const authMessage = useCookie('authMessage')
|
|
// Check for session cookie (HTTP-only cookie is checked server-side via API)
|
|
const tenantCookie = useCookie('routebox_tenant')
|
|
|
|
// Routes that don't need a toast message (user knows they need to login)
|
|
const silentRoutes = ['/']
|
|
|
|
// Quick check: if no tenant cookie, likely not authenticated
|
|
// The actual session cookie is HTTP-only and can't be read client-side
|
|
// For a full check, we'd call /api/auth/me, but that's expensive for every route
|
|
|
|
// On client side, check the reactive auth state
|
|
if (import.meta.client) {
|
|
const { isAuthenticated, checkAuth } = useAuth()
|
|
|
|
// If we already know we're authenticated, allow
|
|
if (isAuthenticated.value) {
|
|
return
|
|
}
|
|
|
|
// If we have a tenant cookie, try to validate the session
|
|
if (tenantCookie.value) {
|
|
const isValid = await checkAuth()
|
|
if (isValid) {
|
|
return
|
|
}
|
|
}
|
|
|
|
// Not authenticated
|
|
if (!silentRoutes.includes(to.path)) {
|
|
authMessage.value = 'Please login to access this page'
|
|
}
|
|
return navigateTo('/login')
|
|
}
|
|
|
|
// Server-side: check for tenant cookie as a quick indicator
|
|
// If no tenant cookie, redirect to login
|
|
if (!tenantCookie.value) {
|
|
if (!silentRoutes.includes(to.path)) {
|
|
authMessage.value = 'Please login to access this page'
|
|
}
|
|
return navigateTo('/login')
|
|
}
|
|
})
|