import { app } from "electron"; import { parseAuthRes } from "@/auth"; import { postAuth, postLogin, postLogout } from "@/api/account"; import { updateAppUI, launchSession, endSession } from "@/session"; import { getToken, setToken, clearToken } from "./store"; import { backgroundMitt, ipcEmit } from "@/composables/useEmitter"; /* Either null or a crimataId */ let account: string | null = null; export const accountAuth = async (): Promise => { /* attempt to get a login token from the store */ const token = getToken(); try { if (token) { // attempt to login with token const res = await postAuth(token); const parsed = parseAuthRes(res); // save jwt token and profile setToken(parsed.token); account = parsed.crimataId // launch session launchSession(parsed.token); } else throw(new Error('Failed to authenticate (no token).')); } catch (e) { console.log(e); clearToken(); } finally { // push state changes to the frontend updateAppState(); } }; export const accountLogin = async (payload: any): Promise => { const creds = payload as AccountCredentials; try { // attempt login with email password const res = await postLogin(creds.email, creds.password); const parsed = parseAuthRes(res); // save jwt token and profile setToken(parsed.token); account = parsed.crimataId; // launch session launchSession(parsed.token); // push state changes to the frontend updateAppState(); return; } catch(e) { clearToken(); throw e; } } export const accountLogout = async (): Promise => { try { // post logout to backend await postLogout(); // remove key and account clearToken(); account = null; // push account state to browser ipcEmit("set-account", account); // kill crimata platform session endSession(); return; } catch(e) { console.log('[ACCOUNT]', e); return (new Error('Failed to logout. Please try again.')); } } // logout when auth fails on platform end backgroundMitt.on("close-auth-fail", async (_payload: any) => { await accountLogout(); }); // emits state of account, version, and UI export const updateAppState = () => { ipcEmit("set-account", account); ipcEmit("set-version", app.getVersion()); updateAppUI(); }