import { defineStore } from 'pinia' export const useAuthStore = defineStore('auth', { state: () => ({ isLoggedIn: false, user: null, roles: [], role: null // Rückwärtskompatibilität: erste Rolle }), getters: { isAdmin: (state) => { return state.roles.includes('admin') || state.roles.includes('vorstand') }, isNewsletter: (state) => { return state.roles.includes('newsletter') }, hasRole: (state) => { return (role) => state.roles.includes(role) }, hasAnyRole: (state) => { return (...roles) => roles.some(role => state.roles.includes(role)) } }, actions: { async checkAuth() { try { const response = await $fetch('/api/auth/status') this.isLoggedIn = response.isLoggedIn this.user = response.user this.roles = response.roles || (response.role ? [response.role] : []) this.role = response.role || (this.roles.length > 0 ? this.roles[0] : null) // Rückwärtskompatibilität return response } catch (error) { this.isLoggedIn = false this.user = null this.roles = [] this.role = null return { isLoggedIn: false } } }, async login(email, password) { const response = await $fetch('/api/auth/login', { method: 'POST', body: { email, password } }) if (response.success) { await this.checkAuth() } return response }, async logout() { try { await $fetch('/api/auth/logout', { method: 'POST' }) this.isLoggedIn = false this.user = null this.roles = [] this.role = null } catch (error) { console.error('Logout fehlgeschlagen:', error) throw error } } } })