import { defineStore } from "pinia"; import { ref, computed } from "vue"; import { c as useCookie } from "../server.mjs"; const useAuthStore = defineStore("auth", () => { const user = ref(null); const token = ref(null); const isLoading = ref(false); const error = ref(null); const isInitialized = ref(false); const isAuthenticated = computed(() => !!token.value && !!user.value); const isAdmin = computed(() => { const role = user.value?.role; if (!role) return false; const staffRoles = ["SUPERADMIN", "ADMIN", "MODERATOR", "SALES_REP", "SERVICE_MGR"]; return staffRoles.includes(role.toUpperCase()); }); const userName = computed(() => { if (!user.value) return ""; const { first_name, last_name } = user.value; if (first_name && last_name) return `${first_name} ${last_name}`; return first_name || last_name || user.value.email; }); const userEmail = computed(() => user.value?.email ?? ""); const userRole = computed(() => user.value?.role ?? "guest"); async function login(email, password) { isLoading.value = true; error.value = null; try { const body = new URLSearchParams(); body.append("username", email); body.append("password", password); const res = await $fetch("/api/v1/auth/login", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body }); const tokenCookie = useCookie("access_token", { maxAge: 60 * 60 * 24 * 7, // 7 days path: "/", sameSite: "lax", secure: true }); tokenCookie.value = res.access_token; token.value = res.access_token; await fetchUser(); } catch (err) { error.value = err?.data?.detail || err?.message || "Login failed"; throw err; } finally { isLoading.value = false; } } async function fetchUser() { const tokenCookie = useCookie("access_token"); const currentToken = tokenCookie.value || token.value; if (!currentToken) return; try { const res = await $fetch("/api/v1/auth/me", { headers: { Authorization: `Bearer ${currentToken}` } }); user.value = res; } catch (err) { if (err?.response?.status === 401) { logout(); } throw err; } } function logout() { token.value = null; user.value = null; error.value = null; const tokenCookie = useCookie("access_token"); tokenCookie.value = null; } async function init() { const tokenCookie = useCookie("access_token"); if (tokenCookie.value) { token.value = tokenCookie.value; try { await fetchUser(); } catch { logout(); } } isInitialized.value = true; } function clearError() { error.value = null; } return { // State user, token, isLoading, error, isInitialized, // Getters isAuthenticated, isAdmin, userName, userEmail, userRole, // Actions login, fetchUser, logout, init, clearError }; }); export { useAuthStore as u }; //# sourceMappingURL=auth-RwMj9LdV.js.map