feat: implement auth middleware, user sync, and token state persistence
- Define useAuth composable logic with syncUser, handleLoginSuccess, and logout methods - Add auth.ts and guest.ts route middlewares to guard routes based on authentication and user roles - Add auth.client.ts plugin to boot-sync logged in user details - Declare custom PageMeta type definitions to support role-based authorization rules
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
export default defineNuxtRouteMiddleware(async (to) => {
|
||||
const auth = useAuth()
|
||||
|
||||
// Se c'è un token ma l'utente non è ancora caricato e non stiamo già sincronizzando, sincronizza
|
||||
if ((auth.token.value || auth.tokenState.value) && !auth.user.value && !auth.isSyncingUser.value) {
|
||||
try {
|
||||
await auth.syncUser()
|
||||
} catch (error) {
|
||||
console.error('[Auth Middleware] Sync failed:', error)
|
||||
return navigateTo('/auth/login')
|
||||
}
|
||||
}
|
||||
|
||||
// Se non autenticato, redirige al login
|
||||
if (!auth.isAuthenticated.value) {
|
||||
return navigateTo('/auth/login')
|
||||
}
|
||||
|
||||
// Verifica ruoli se richiesto
|
||||
const requiredRole = to.meta.auth?.role
|
||||
|
||||
if (requiredRole && auth.user.value) {
|
||||
const userRole = auth.user.value.role
|
||||
|
||||
const roleLevels: Record<string, number> = {
|
||||
'CITIZEN': 1,
|
||||
'OPERATOR': 2,
|
||||
'ADMIN': 3
|
||||
}
|
||||
|
||||
const userLevel = roleLevels[userRole] || 0
|
||||
const requiredLevel = roleLevels[requiredRole] || 0
|
||||
|
||||
if (userLevel < requiredLevel) {
|
||||
console.warn(`[Auth] User role ${userRole} (level ${userLevel}) insufficient for required ${requiredRole} (level ${requiredLevel})`)
|
||||
return navigateTo('/')
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,17 @@
|
||||
export default defineNuxtRouteMiddleware(async () => {
|
||||
const auth = useAuth()
|
||||
|
||||
// Se c'è un token ma l'utente non è ancora caricato e non stiamo già sincronizzando, sincronizza
|
||||
if ((auth.token.value || auth.tokenState.value) && !auth.user.value && !auth.isSyncingUser.value) {
|
||||
try {
|
||||
await auth.syncUser()
|
||||
} catch (error) {
|
||||
console.error('[Guest Middleware] Sync failed:', error)
|
||||
}
|
||||
}
|
||||
|
||||
// Se autenticato, redirige al dashboard
|
||||
if (auth.isAuthenticated.value && auth.user.value) {
|
||||
return navigateTo('/dashboard')
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user