119 lines
2.9 KiB
TypeScript
119 lines
2.9 KiB
TypeScript
|
|
"use strict";
|
|
|
|
import { Profile } from "@/types";
|
|
import { submit, fetchProfile, logout } from "@/api/account";
|
|
import { ipcMain, IpcMainInvokeEvent } from "electron";
|
|
import { store } from "@/background/store";
|
|
import { endSession } from "@/background/session";
|
|
|
|
|
|
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('Unable to authenticate and fetch account 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);
|
|
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
|
|
endSession();
|
|
|
|
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);
|
|
|
|
}
|