import { postAuth, postLogin, postLogout } from "@/api/account"; import { endSession, launchSession } from "@/session"; import { getToken, setToken, setProfile, getProfile, clearStore } from "./store"; import { parseAuthRes } from "./auth"; import { ipcEmit } from "@/composables/useEmitter"; export const accountAuth = async (): Promise => { /* attempt to get a login token from the store */ const token = getToken(); /* try to login with it, returns platform secret and new token on success */ if (token) { try { const res = await postAuth(token); const parsed = parseAuthRes(res); setToken(parsed.token) setProfile(parsed.profile); return { profile: parsed.profile, token: parsed.token }; } catch(e) { console.log('[ACCOUNT]', e); clearStore(); throw(new Error('Failed to authenticate.')); } } else { throw(new Error('Unable to authenticate.')); } }; export const accountLogin: IpcHandlerCallback = async (payload) => { const account = payload as AccountCredentials; try { // attempt login with email password const res = await postLogin(account.email, account.password); const parsed = parseAuthRes(res); // save jwt token and profile setToken(parsed.token); setProfile(parsed.profile); // launch session launchSession(parsed.token); // return profile to renderer return parsed.profile; } catch(e) { clearStore(); throw e; } } export const accountLogout = async (): Promise => { try { // post logout to backend await postLogout(); // remove key and crimataId clearStore(); // kill crimata platform session endSession(); return; } catch(e) { console.log('[ACCOUNT]', e); return (new Error('Failed to logout. Please try again.')); } } export const updateAppState = (): void => { const profile = getProfile(); ipcEmit("set-profile", profile); // ipcEmit('messages') etc }