90 lines
2.7 KiB
TypeScript
90 lines
2.7 KiB
TypeScript
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';
|
|
|
|
const refreshTime = 10000;
|
|
let intervalId: ReturnType<typeof setInterval> | 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;
|
|
|
|
logo.value = sets.icon;
|
|
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, username: resp.data.user, role: resp.data.role })
|
|
.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();
|
|
}
|
|
|
|
async function refresh() {
|
|
await appApi
|
|
.post('login/refresh', {}, { withCredentials: true })
|
|
.then(() => {
|
|
appApi
|
|
.get('/login/me')
|
|
.then((resp) => {
|
|
userStore
|
|
.setUser({ id: resp.data.id, username: resp.data.user, role: resp.data.role })
|
|
.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 };
|
|
}
|