Add global auth state with composable for reactive login status
This commit is contained in:
48
composables/useAuth.js
Normal file
48
composables/useAuth.js
Normal file
@@ -0,0 +1,48 @@
|
||||
import { ref, computed } from 'vue'
|
||||
|
||||
// Global state (shared across all components)
|
||||
const isLoggedIn = ref(false)
|
||||
const user = ref(null)
|
||||
const userRole = ref(null)
|
||||
|
||||
export const useAuth = () => {
|
||||
const isAdmin = computed(() => {
|
||||
return userRole.value === 'admin' || userRole.value === 'vorstand'
|
||||
})
|
||||
|
||||
const checkAuth = async () => {
|
||||
try {
|
||||
const response = await $fetch('/api/auth/status')
|
||||
isLoggedIn.value = response.isLoggedIn
|
||||
user.value = response.user
|
||||
userRole.value = response.role
|
||||
return response
|
||||
} catch (error) {
|
||||
isLoggedIn.value = false
|
||||
user.value = null
|
||||
userRole.value = null
|
||||
return { isLoggedIn: false }
|
||||
}
|
||||
}
|
||||
|
||||
const logout = async () => {
|
||||
try {
|
||||
await $fetch('/api/auth/logout', { method: 'POST' })
|
||||
isLoggedIn.value = false
|
||||
user.value = null
|
||||
userRole.value = null
|
||||
} catch (error) {
|
||||
console.error('Logout fehlgeschlagen:', error)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isLoggedIn,
|
||||
user,
|
||||
userRole,
|
||||
isAdmin,
|
||||
checkAuth,
|
||||
logout
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user