import { reactive, toRefs } from 'vue'; import { useIpc } from './ipc'; interface AuthState { accessToken: string | null; error?: Error; } const state = reactive({ accessToken: null, error: undefined, }); const AUTH_KEY = 'crimata_token'; let token: string | null; token = window.localStorage.getItem(AUTH_KEY); if (token) { state.accessToken = token; window.localStorage.setItem(AUTH_KEY, token); } const authToken = async () => { const { invoke } = useIpc(); try { token = window.localStorage.getItem(AUTH_KEY); if (!token) { token = "no-token" } console.log(`Token ${token}`) const res = await invoke('auth-session', token); window.localStorage.setItem(AUTH_KEY, res); state.accessToken = res; } catch(e) { state.error = e; console.log('ERROR: failed authentication'); window.localStorage.removeItem(AUTH_KEY); state.accessToken = null; } } // authenticate on auth event window.ipcRenderer.on("auth", async (_event, _arg) => { await authToken(); }); export const useAuth = () => { const setToken = (token: string) => { window.localStorage.setItem(AUTH_KEY, token); state.accessToken = token; state.error = undefined; } const logout = (): Promise => { window.localStorage.removeItem(AUTH_KEY); return Promise.resolve(state.accessToken = null); } return { setToken, logout, ...toRefs(state), // accessToken, error } }