import { appApi } from 'src/boot/axios'; import { useUserStore } from './userStore'; import { useNotify } from '../general/useNotify'; import type { Settings } from '../models/settings'; import { appName, logo } from '../models/settings'; import { clearLocalStorage, setLocalSettings } from 'src/localstorage/localStorage'; import { routerInstance } from 'src/router'; const refreshTime = 10000; let intervalId: ReturnType | null = null; export function useLogin() { const userStore = useUserStore(); const { NotifyResponse } = useNotify(); async function login(user: string, password: string) { try { await appApi.post('/login', { user, password }).then((resp) => { const sets = resp.data.settings as Settings; if (sets.icon) { logo.value = sets.icon; } if (sets.appName) { appName.value = sets.appName; } document.documentElement.style.setProperty('--q-primary', sets.primaryColor); document.documentElement.style.setProperty('--q-primary-text', sets.primaryColorText); document.documentElement.style.setProperty('--q-secondary', sets.secondaryColor); document.documentElement.style.setProperty('--q-secondary-text', sets.secondaryColorText); setLocalSettings(sets); }); const resp = await appApi.get('/login/me'); await userStore .setUser({ id: resp.data.id, user: resp.data.user, role: { role: resp.data.role, permissions: [] }, }) .catch((err) => NotifyResponse(err, 'error')); startRefreshInterval(); return true; } catch (err) { console.error('Login error:', err); throw err; } } async function logout() { await appApi.get('/logout').catch((err) => { NotifyResponse(err, 'error'); }); userStore.clearUser(); clearLocalStorage(); stopRefreshInterval(); await routerInstance.push('/login'); } async function refresh() { await appApi .post('login/refresh', {}, { withCredentials: true }) .then(() => { appApi .get('/login/me') .then((resp) => { userStore .setUser({ id: resp.data.id, user: resp.data.user, role: { role: resp.data.role, permissions: [] }, }) .catch((err) => NotifyResponse(err, 'error')); if (!intervalId) { startRefreshInterval(); } return true; }) .catch(() => {}); }) .catch(() => { userStore.clearUser(); }); stopRefreshInterval(); return false; } function startRefreshInterval() { intervalId = setInterval(() => { refresh().catch((err) => NotifyResponse(err, 'error')); }, refreshTime); } function stopRefreshInterval() { if (intervalId) { clearInterval(intervalId); intervalId = null; } } return { login, logout, refresh }; }