refactor main and rendered ipc

This commit is contained in:
riqo 2021-05-22 15:02:49 -05:00 committed by Enrique Hernandez
commit ddb2f4df0f
28 changed files with 758 additions and 211 deletions

View file

@ -0,0 +1,117 @@
"use strict";
import { Profile } from "@/types";
import { submit, fetchProfile, logout } from "@/api/account";
import { ipcMain, IpcMainInvokeEvent } from "electron";
import { store } from "@/background/store";
const parseAuthRes = (authRes: any) => {
const token = authRes.headers['set-cookie'][0].split(";")[0].split("=")[1] as string;
const profile = authRes.data as Profile;
return {
token,
profile
}
};
const onProfile = async (
_event: IpcMainInvokeEvent,
_payload: null
): Promise<Profile | Error> => (
new Promise(async (resolve, reject) => {
console.log('[IPC]: user-profile');
// get jwt token and crimataId from store
const token = store.get('key');
const crimataId = store.get('crimataId');
// authenticate and fetch profile
try {
const res = await fetchProfile(
crimataId,
token
);
const parsed = parseAuthRes(res);
resolve(parsed.profile);
} catch(e) {
reject(new Error('Failed to fetch profile.'));
}
})
)
const onLogin = async (
_event: IpcMainInvokeEvent,
payload: string
): Promise<Profile | Error> => (
new Promise(async (resolve, reject) => {
console.log('[IPC]: user-login');
const account = JSON.parse(payload);
if ( account.password && account.email ) {
try {
const res = await submit(account.email, account.password);
const parsed = parseAuthRes(res);
// save jwt token and profile
store.set('key', parsed.token);
store.set('crimataId', parsed.profile.crimataId);
// return profile to renderer
resolve(parsed.profile);
} catch(e) {
console.log('[API]', e.response);
reject(new Error('Failed to authenticate'));
}
}
})
)
const onLogout = async (
_event: IpcMainInvokeEvent,
_payload: null
): Promise<void> => (
new Promise(async (resolve, reject) => {
console.log('[IPC]: user-logout');
try {
// post logout to backend
await logout();
// remove key and crimataId
store.delete('key');
store.delete('crimataId');
// TODO: kill crimata platform session
resolve();
} catch(e) {
reject(new Error('Failed to logout. Please try again.'));
}
})
)
export default function useAccountListeners(): void {
ipcMain.removeHandler("user-profile");
ipcMain.handle("user-profile", onProfile);
ipcMain.removeHandler("user-login");
ipcMain.handle("user-login", onLogin);
ipcMain.removeHandler("user-logout");
ipcMain.handle("user-logout", onLogout);
}