32 lines
617 B
TypeScript
32 lines
617 B
TypeScript
export default defineNuxtRouteMiddleware(async (to) => {
|
|
const auth = useAuth()
|
|
|
|
if (!auth.isEnabled || to.meta.public) {
|
|
return
|
|
}
|
|
|
|
const requiresAuth = Boolean(to.meta.requiresAuth || (to.meta.roles && to.meta.roles.length > 0))
|
|
|
|
if (!requiresAuth) {
|
|
return
|
|
}
|
|
|
|
await auth.ensureInitialized()
|
|
|
|
if (!auth.isAuthenticated.value) {
|
|
await auth.login()
|
|
return
|
|
}
|
|
|
|
if (to.meta.roles?.length) {
|
|
const authStore = useAuthStore()
|
|
|
|
if (!authStore.hasAnyRole(to.meta.roles)) {
|
|
throw createError({
|
|
statusCode: 403,
|
|
statusMessage: 'Forbidden'
|
|
})
|
|
}
|
|
}
|
|
})
|