fix post window close auth bug

This commit is contained in:
Enrique Hernandez 2021-02-10 22:34:07 -06:00
commit 6a19a96855
7 changed files with 91 additions and 82 deletions

View file

@ -1,15 +1,10 @@
"use strict";
import WebSocket from 'ws';
import { windowEmitter } from './windowEmitter';
import { ipcMain } from "electron";
const EventEmitter = require('events');
class SocketEmitter extends EventEmitter {}
export const socketEmitter = new SocketEmitter();
interface RenderMessage {
type: 'render';
content: string;
context: string;
subContext: string;
@ -33,24 +28,21 @@ let auth = false;
const receiveMessage = (message: string): void => {
while(!auth) {
console.log('window emitter @ session.ts recieve')
windowEmitter.emit('auth-res', message);
return;
}
const parsed: RenderMessage = JSON.parse(message);
if (parsed.type === "render") {
windowEmitter.emit('ipc-renderer', {
endpoint: 'render-message',
message: parsed
});
}
}
const authUser = async (event: any, payload: string | UserCreds | null): Promise<string> => {
windowEmitter.emit('ipc-renderer', {
endpoint: 'render-message',
message: parsed
});
};
const authSession = async (_event, payload: string | UserCreds | null): Promise<string> => {
return new Promise((resolve, reject) => {
console.log('authenticating...');
console.log('window emitter @ session.ts auth')
windowEmitter.on('auth-res', (res: string) => {
if (res === 'locked') {
reject(res);
@ -69,6 +61,14 @@ const authUser = async (event: any, payload: string | UserCreds | null): Promise
});
};
export const sendMessage = (content: string | Buffer) => {
if (content instanceof Buffer) {
socket.send(content);
} else if (content){
socket.send(JSON.stringify(content));
}
}
export const initSession = () => {
if (socket) {
socket.removeAllListeners();
@ -84,7 +84,7 @@ export const initSession = () => {
// handle renderer auth-token event
ipcMain.removeHandler('auth-user'); // avoid setting duplicate handlers
ipcMain.handle('auth-user', authUser);
ipcMain.handle('auth-user', authSession);
socket.on('open', () => {
console.log('Success! Connected to Crimata.');
@ -98,7 +98,7 @@ export const initSession = () => {
});
socket.on('error', (e) => {
socket.on('error', (_e) => {
console.log('ERROR: Failed to connect.');
socket.removeAllListeners();
socket.close();
@ -109,20 +109,13 @@ export const initSession = () => {
}
}, reconnectTimeout);
})
});
socket.on('close', () => {
console.log('Connection droped. Restarting.')
initSession();
})
});
socket.on("message", receiveMessage);
}
};
export const sendMessage = (content: string | Buffer) => {
if (content instanceof Buffer) {
socket.send(content);
} else if (content){
socket.send(JSON.stringify(content));
}
}