39 lines
1.0 KiB
TypeScript
39 lines
1.0 KiB
TypeScript
export default defineNuxtRouteMiddleware((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 token = useCookie('token')
|
|
const authMessage = useCookie('authMessage')
|
|
|
|
// Routes that don't need a toast message (user knows they need to login)
|
|
const silentRoutes = ['/']
|
|
|
|
// Check token cookie (works on both server and client)
|
|
if (!token.value) {
|
|
if (!silentRoutes.includes(to.path)) {
|
|
authMessage.value = 'Please login to access this page'
|
|
}
|
|
return navigateTo('/login')
|
|
}
|
|
|
|
// On client side, also verify localStorage is in sync
|
|
if (import.meta.client) {
|
|
const { isLoggedIn } = useAuth()
|
|
if (!isLoggedIn()) {
|
|
if (!silentRoutes.includes(to.path)) {
|
|
authMessage.value = 'Please login to access this page'
|
|
}
|
|
return navigateTo('/login')
|
|
}
|
|
}
|
|
})
|