import { ref, computed } from 'vue' import type { Ref, ComputedRef } from 'vue' import * as ls from '../utils/local-storage' import { LS_KEYS } from '@v2/config/constants' export interface User { id: number name: string email: string avatar: string | number is_owner: boolean is_super_admin: boolean [key: string]: unknown } export interface UseAuthReturn { currentUser: Ref isAuthenticated: ComputedRef isOwner: ComputedRef isSuperAdmin: ComputedRef setUser: (user: User) => void clearUser: () => void login: (loginFn: () => Promise) => Promise logout: (logoutFn: () => Promise) => Promise } const currentUser = ref(null) /** * Composable for managing authentication state. * Provides the current user, login/logout helpers, and role-based computed properties. */ export function useAuth(): UseAuthReturn { const isAuthenticated = computed(() => currentUser.value !== null) const isOwner = computed( () => currentUser.value?.is_owner === true ) const isSuperAdmin = computed( () => currentUser.value?.is_super_admin === true ) function setUser(user: User): void { currentUser.value = user } function clearUser(): void { currentUser.value = null } /** * Execute a login function and set the current user on success. * * @param loginFn - Async function that performs the login and returns a User * @returns The authenticated user */ async function login(loginFn: () => Promise): Promise { const user = await loginFn() currentUser.value = user return user } /** * Execute a logout function and clear auth state. * * @param logoutFn - Async function that performs the logout */ async function logout(logoutFn: () => Promise): Promise { await logoutFn() currentUser.value = null ls.remove(LS_KEYS.AUTH_TOKEN) ls.remove(LS_KEYS.SELECTED_COMPANY) } return { currentUser, isAuthenticated, isOwner, isSuperAdmin, setUser, clearUser, login, logout, } }