Skip to content

Commit

Permalink
fix team handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
antonbuks committed Mar 4, 2024
1 parent 17fceea commit 96d1beb
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 64 deletions.
3 changes: 1 addition & 2 deletions src/common/communication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,11 +138,10 @@ export const TOKEN_REFRESHED = 'token-refreshed';
export const TOKEN_REQUEST = 'token-request';
export const REFRESH_TOKEN = 'refresh-token';
export const RESET_TOKEN = 'reset-token';
export const RESET_TEAMS = 'reset-teams';
export const SERVER_ADDED = 'server-added';
export const SERVER_DELETED = 'server-deleted';
export const RESET_AUTH = 'reset-auth';
export const RESET_TEAMS_HARD = 'reset-teams-hard';
export const RESET_TEAMS = 'reset-teams-hard';

// Calls
export const GET_DESKTOP_SOURCES = 'get-desktop-sources';
Expand Down
68 changes: 36 additions & 32 deletions src/main/app/initialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@

import path from 'path';

import { app, ipcMain, nativeTheme, session } from 'electron';
import {app, ipcMain, nativeTheme, session} from 'electron';
import isDev from 'electron-is-dev';
import installExtension, { REACT_DEVELOPER_TOOLS } from 'electron-extension-installer';
import { init } from '@sentry/electron/main';
import installExtension, {REACT_DEVELOPER_TOOLS} from 'electron-extension-installer';
import {init} from '@sentry/electron/main';

import {ConfigServer} from 'types/config';

import {
FOCUS_BROWSERVIEW,
Expand Down Expand Up @@ -37,16 +39,16 @@ import {
GET_APP_INFO,
} from 'common/communication';
import Config from 'common/config';
import { Logger } from 'common/log';
import {Logger} from 'common/log';

import AllowProtocolDialog from 'main/allowProtocolDialog';
import AppVersionManager from 'main/AppVersionManager';
import AuthManager from 'main/authManager';
import AutoLauncher from 'main/AutoLauncher';
import updateManager from 'main/autoUpdater';
import { setupBadge } from 'main/badge';
import {setupBadge} from 'main/badge';
import CertificateManager from 'main/certificateManager';
import { configPath, updatePaths } from 'main/constants';
import {configPath, updatePaths} from 'main/constants';
import CriticalErrorHandler from 'main/CriticalErrorHandler';
import downloadsManager from 'main/downloadsManager';
import i18nManager from 'main/i18nManager';
Expand All @@ -59,12 +61,16 @@ import TokenManager from 'main/tokenManager';
import ViewManager from 'main/views/viewManager';
import MainWindow from 'main/windows/mainWindow';

import { protocols } from '../../../electron-builder.json';
import {protocols} from '../../../electron-builder.json';

import { IKDriveAllowedUrls, IKLoginAllowedUrls, IKWelcomeAllowedUrls, KChatTokenWhitelist } from 'common/utils/constants';
import {IKDriveAllowedUrls, IKLoginAllowedUrls, IKWelcomeAllowedUrls, KChatTokenWhitelist} from 'common/utils/constants';

import ServerManager from 'common/servers/serverManager';

import buildConfig from 'common/config/buildConfig';

import {IKOrigin, devServerUrl, isLocalEnv} from 'common/config/ikConfig';

import {
handleAppBeforeQuit,
handleAppBrowserWindowCreated,
Expand Down Expand Up @@ -110,9 +116,6 @@ import {
handleMinimize,
handleRestore,
} from './windows';
import { ConfigServer } from 'types/config';
import buildConfig from 'common/config/buildConfig';
import { IKOrigin, devServerUrl, isLocalEnv } from 'common/config/ikConfig';

export const mainProtocol = protocols?.[0]?.schemes?.[0];

Expand Down Expand Up @@ -290,7 +293,7 @@ function initializeInterCommunicationEventListeners() {
ipcMain.handle(GET_CONFIGURATION, handleGetConfiguration);
ipcMain.handle(GET_LOCAL_CONFIGURATION, handleGetLocalConfiguration);
ipcMain.on(UPDATE_CONFIGURATION, updateConfiguration);
ipcMain.handle(UPDATE_TEAMS, updateTeamsHandler);
ipcMain.on(UPDATE_TEAMS, updateTeamsHandler);
ipcMain.handle(GET_DARK_MODE, handleGetDarkMode);
ipcMain.on(WINDOW_CLOSE, handleClose);
ipcMain.on(WINDOW_MAXIMIZE, handleMaximize);
Expand All @@ -302,7 +305,6 @@ function initializeInterCommunicationEventListeners() {
}

function updateTeamsHandler(_: any, servers: ConfigServer[]) {

const [defaultServer] = buildConfig.defaultServers!;
const [firstServer] = servers;

Expand All @@ -325,10 +327,12 @@ function initIKserver() {

function initReceivedServer(servers: ConfigServer[]) {
ServerManager.removePredefinedServersHandler(true);
servers.forEach(server => {
if (ServerManager.serverNameExist(server)) return
servers.forEach((server) => {
if (ServerManager.serverNameExist(server)) {
return;
}
ServerManager.addServer(server);
})
});
}

async function initializeAfterAppReady() {
Expand All @@ -342,7 +346,7 @@ async function initializeAfterAppReady() {

app.setAppUserModelId('Kchat.Desktop'); // Use explicit AppUserModelID
const defaultSession = session.defaultSession;
defaultSession.webRequest.onHeadersReceived({ urls: IKLoginAllowedUrls },
defaultSession.webRequest.onHeadersReceived({urls: IKLoginAllowedUrls},
(d, c) => {
if (d.url.includes('/token') && d.responseHeaders) {
if (!d.responseHeaders['access-control-allow-origin']) {
Expand All @@ -369,25 +373,25 @@ async function initializeAfterAppReady() {
/*
Inject token, for kdrive, images and websocket, rest is handled by the web client.
*/
defaultSession.webRequest.onBeforeSendHeaders({ urls: [
defaultSession.webRequest.onBeforeSendHeaders({urls: [
...KChatTokenWhitelist,
...IKDriveAllowedUrls,
...IKWelcomeAllowedUrls,
] },
(d, c) => {
const authHeader = d.requestHeaders.Authorization ? d.requestHeaders.Authorization : null;
const ikToken = TokenManager.getToken();

// No Authorization header or bearer is empty
if ((!authHeader || !authHeader?.split(' ')[1]) && ikToken.token) {
d.requestHeaders.Authorization = `Bearer ${ikToken.token}`;
}
]},
(d, c) => {
const authHeader = d.requestHeaders.Authorization ? d.requestHeaders.Authorization : null;
const ikToken = TokenManager.getToken();

// No Authorization header or bearer is empty
if ((!authHeader || !authHeader?.split(' ')[1]) && ikToken.token) {
d.requestHeaders.Authorization = `Bearer ${ikToken.token}`;
}

c({
cancel: false,
requestHeaders: d.requestHeaders,
});
},
c({
cancel: false,
requestHeaders: d.requestHeaders,
});
},
);
if (process.platform !== 'darwin') {
defaultSession.on('spellcheck-dictionary-download-failure', (event, lang) => {
Expand Down
5 changes: 2 additions & 3 deletions src/main/preload/externalAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ import {
SERVER_ADDED,
SERVER_DELETED,
RESET_AUTH,
RESET_TEAMS_HARD,
SWITCH_SERVER,
} from 'common/communication';
import {IKOrigin} from 'common/config/ikConfig';
Expand Down Expand Up @@ -148,7 +147,7 @@ contextBridge.exposeInMainWorld('authManager', {
deleteTeam: () => ipcRenderer.invoke(SERVER_DELETED),
logout: async () => {
await ipcRenderer.invoke(RESET_AUTH);
ipcRenderer.invoke(RESET_TEAMS_HARD);
ipcRenderer.invoke(RESET_TEAMS);
},
});

Expand Down Expand Up @@ -364,7 +363,7 @@ window.addEventListener('message', ({origin, data = {}}: {origin?: string; data?
ipcRenderer.send('call-focus', message);
break;
}
case RESET_TEAMS: {
case 'reset-teams': {
ipcRenderer.send(UPDATE_TEAMS, [{
name: '.',
url: IKOrigin,
Expand Down
39 changes: 20 additions & 19 deletions src/main/tokenManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,17 @@ import log from 'electron-log';

import {UPDATE_PATHS} from 'common/communication';

import {tokenApiEndpoint} from '../common/config/ikConfig';

import {tokensStorePath} from './constants';
import {tokenApiEndpoint} from '../common/config/ikConfig'

// import * as Validator from '../common/Validator';

type Token = {
token: string;
refreshToken?: string;
encrypted?: boolean;

// expiresAt: number;
}

Expand All @@ -39,17 +41,17 @@ export class TokenManager {
this.data = {};
this.requestPromise = undefined;
this.revokePromise = undefined;
this.safeStorageAvailable = safeStorage.isEncryptionAvailable()
this.safeStorageAvailable = safeStorage.isEncryptionAvailable();
}

load = (): Promise<Token | Error | Record<string, never>> => {
return new Promise((resolve, reject) => {
let storeStr;
try {
storeStr = fs.readFileSync(tokensStorePath, 'utf-8');
let jsonData = (typeof storeStr === 'object'
? storeStr
: JSON.parse(storeStr));
const jsonData = (typeof storeStr === 'object' ?
storeStr :
JSON.parse(storeStr));

// jsonData = Validator.validateTokensStore(jsonData);

Expand Down Expand Up @@ -102,7 +104,7 @@ export class TokenManager {
handleStoreToken = (_: IpcMainEvent, message: Token) => {
this.data = {
token: message.token,
encrypted: true
encrypted: true,
};

log.silly('tokenManager.handleStoreToken');
Expand Down Expand Up @@ -155,7 +157,7 @@ export class TokenManager {
try {
const data = JSON.parse(raw) as Record<string, string>;
// eslint-disable-next-line @typescript-eslint/naming-convention
const { access_token, expires_in, refresh_token } = data;
const {access_token, expires_in, refresh_token} = data;
this.data = {
token: access_token,
refreshToken: refresh_token,
Expand Down Expand Up @@ -280,25 +282,25 @@ export class TokenManager {
if (tokenObj.encrypted) {
delete tokenObj.encrypted;
}
this.save(tokenObj)
this.save(tokenObj);
return tokenObj;

};
}

try {
const encryptedString = safeStorage.encryptString(tokenObj.token);
const token = {
token: encryptedString.toString('base64'),
encrypted: true
encrypted: true,
};
this.save(token);

// return decrypted version for operations.
return {
token: tokenObj.token,
encrypted: true
encrypted: true,
};
} catch (error) {
log.error('Token encryption did not work', error)
log.error('Token encryption did not work', error);
if (tokenObj.encrypted) {
delete tokenObj.encrypted;
}
Expand All @@ -317,16 +319,15 @@ export class TokenManager {
}

try {
const buffer = Buffer.from(tokenObj.token, 'base64')
const buffer = Buffer.from(tokenObj.token, 'base64');
return {
...tokenObj,
token: safeStorage.decryptString(buffer)
}
token: safeStorage.decryptString(buffer),
};
} catch (error) {
log.error('Token decryption did not work', error)
return tokenObj
log.error('Token decryption did not work', error);
return tokenObj;
}

}
}

Expand Down
9 changes: 1 addition & 8 deletions src/main/views/viewManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,14 +198,7 @@ export class ViewManager {
}

resetTeams = () => {
// TokenManager.reset();
Config.setServers([{
name: '.',
url: IKOrigin,
order: 0,
tabs: [{ name: 'TAB_MESSAGING', order: 0, isOpen: true }],
}]);
this.reload();
ServerManager.reloadFromConfig();
}

handleCallJoined = (_: IpcMainEvent, message: any) => {
Expand Down

0 comments on commit 96d1beb

Please sign in to comment.