Skip to content

Commit

Permalink
chore: replace Meteor._localStorage -> Accounts.storageLocation (Rock…
Browse files Browse the repository at this point in the history
  • Loading branch information
ggazzo authored Sep 25, 2024
1 parent 47c584c commit 7dc9c41
Show file tree
Hide file tree
Showing 10 changed files with 31 additions and 43 deletions.
27 changes: 14 additions & 13 deletions apps/meteor/app/e2e/client/rocketchat.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { isE2EEMessage } from '@rocket.chat/core-typings';
import { Emitter } from '@rocket.chat/emitter';
import EJSON from 'ejson';
import _ from 'lodash';
import { Accounts } from 'meteor/accounts-base';
import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';

Expand Down Expand Up @@ -308,8 +309,8 @@ class E2E extends Emitter {

getKeysFromLocalStorage(): KeyPair {
return {
public_key: Meteor._localStorage.getItem('public_key'),
private_key: Meteor._localStorage.getItem('private_key'),
public_key: Accounts.storageLocation.getItem('public_key'),
private_key: Accounts.storageLocation.getItem('private_key'),
};
}

Expand All @@ -332,7 +333,7 @@ class E2E extends Emitter {
imperativeModal.close();
},
onConfirm: () => {
Meteor._localStorage.removeItem('e2e.randomPassword');
Accounts.storageLocation.removeItem('e2e.randomPassword');
this.setState(E2EEState.READY);
dispatchToastMessage({ type: 'success', message: t('End_To_End_Encryption_Enabled') });
this.closeAlert();
Expand Down Expand Up @@ -394,7 +395,7 @@ class E2E extends Emitter {
await this.persistKeys(this.getKeysFromLocalStorage(), await this.createRandomPassword());
}

const randomPassword = Meteor._localStorage.getItem('e2e.randomPassword');
const randomPassword = Accounts.storageLocation.getItem('e2e.randomPassword');
if (randomPassword) {
this.setState(E2EEState.SAVE_PASSWORD);
this.openAlert({
Expand All @@ -412,8 +413,8 @@ class E2E extends Emitter {
this.log('-> Stop Client');
this.closeAlert();

Meteor._localStorage.removeItem('public_key');
Meteor._localStorage.removeItem('private_key');
Accounts.storageLocation.removeItem('public_key');
Accounts.storageLocation.removeItem('private_key');
this.instancesByRoomId = {};
this.privateKey = undefined;
this.started = false;
Expand All @@ -425,8 +426,8 @@ class E2E extends Emitter {
async changePassword(newPassword: string): Promise<void> {
await this.persistKeys(this.getKeysFromLocalStorage(), newPassword, { force: true });

if (Meteor._localStorage.getItem('e2e.randomPassword')) {
Meteor._localStorage.setItem('e2e.randomPassword', newPassword);
if (Accounts.storageLocation.getItem('e2e.randomPassword')) {
Accounts.storageLocation.setItem('e2e.randomPassword', newPassword);
}
}

Expand All @@ -447,12 +448,12 @@ class E2E extends Emitter {
}

async loadKeys({ public_key, private_key }: { public_key: string; private_key: string }): Promise<void> {
Meteor._localStorage.setItem('public_key', public_key);
Accounts.storageLocation.setItem('public_key', public_key);

try {
this.privateKey = await importRSAKey(EJSON.parse(private_key), ['decrypt']);

Meteor._localStorage.setItem('private_key', private_key);
Accounts.storageLocation.setItem('private_key', private_key);
} catch (error) {
this.setState(E2EEState.ERROR);
return this.error('Error importing private key: ', error);
Expand All @@ -474,7 +475,7 @@ class E2E extends Emitter {
try {
const publicKey = await exportJWKKey(key.publicKey);

Meteor._localStorage.setItem('public_key', JSON.stringify(publicKey));
Accounts.storageLocation.setItem('public_key', JSON.stringify(publicKey));
} catch (error) {
this.setState(E2EEState.ERROR);
return this.error('Error exporting public key: ', error);
Expand All @@ -483,7 +484,7 @@ class E2E extends Emitter {
try {
const privateKey = await exportJWKKey(key.privateKey);

Meteor._localStorage.setItem('private_key', JSON.stringify(privateKey));
Accounts.storageLocation.setItem('private_key', JSON.stringify(privateKey));
} catch (error) {
this.setState(E2EEState.ERROR);
return this.error('Error exporting private key: ', error);
Expand All @@ -498,7 +499,7 @@ class E2E extends Emitter {

async createRandomPassword(): Promise<string> {
const randomPassword = await generateMnemonicPhrase(5);
Meteor._localStorage.setItem('e2e.randomPassword', randomPassword);
Accounts.storageLocation.setItem('e2e.randomPassword', randomPassword);
return randomPassword;
}

Expand Down
1 change: 1 addition & 0 deletions apps/meteor/app/ui-master/server/scripts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ window.addEventListener('load', function() {
});
window.localStorage.clear();
Meteor._localStorage = window.sessionStorage;
Accounts.config({ clientStorage: 'session' });
}
});
`
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { IMessage } from '@rocket.chat/core-typings';
import { Emitter } from '@rocket.chat/emitter';
import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';

import type { ComposerAPI } from '../../../../client/lib/chats/ChatAPI';
import { withDebouncing } from '../../../../lib/utils/highOrderFunctions';
Expand Down Expand Up @@ -31,11 +31,11 @@ export const createComposerAPI = (input: HTMLTextAreaElement, storageID: string)

const persist = withDebouncing({ wait: 300 })(() => {
if (input.value) {
Meteor._localStorage.setItem(storageID, input.value);
Accounts.storageLocation.setItem(storageID, input.value);
return;
}

Meteor._localStorage.removeItem(storageID);
Accounts.storageLocation.removeItem(storageID);
});

const notifyQuotedMessagesUpdate = (): void => {
Expand Down Expand Up @@ -262,7 +262,7 @@ export const createComposerAPI = (input: HTMLTextAreaElement, storageID: string)

const insertNewLine = (): void => insertText('\n');

setText(Meteor._localStorage.getItem(storageID) ?? '', {
setText(Accounts.storageLocation.getItem(storageID) ?? '', {
skipFocus: true,
});

Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/app/ui-utils/server/Message.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { IMessage } from '@rocket.chat/core-typings';
import { escapeHTML } from '@rocket.chat/string-helpers';
import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';

import { trim } from '../../../lib/utils/stringUtils';
import { i18n } from '../../../server/lib/i18n';
Expand All @@ -17,7 +17,7 @@ export const Message = {
}
if (messageType.message) {
if (!language) {
language = Meteor._localStorage.getItem('userLanguage') || 'en';
language = Accounts.storageLocation.getItem('userLanguage') || 'en';
}
const data = (typeof messageType.data === 'function' && messageType.data(msg)) || {};
return i18n.t(messageType.message, { ...data, lng: language });
Expand Down
6 changes: 4 additions & 2 deletions apps/meteor/app/utils/client/lib/RestApiClient.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { RestClient } from '@rocket.chat/api-client';
import { Accounts } from 'meteor/accounts-base';
import { Meteor } from 'meteor/meteor';

import { invokeTwoFactorModal } from '../../../../client/lib/2fa/process2faReturn';
import { baseURI } from '../../../../client/lib/baseURI';
Expand All @@ -12,7 +11,10 @@ class RestApiClient extends RestClient {
'X-Auth-Token': string;
}
| undefined {
const [uid, token] = [Meteor._localStorage.getItem(Accounts.USER_ID_KEY), Meteor._localStorage.getItem(Accounts.LOGIN_TOKEN_KEY)];
const [uid, token] = [
Accounts.storageLocation.getItem(Accounts.USER_ID_KEY),
Accounts.storageLocation.getItem(Accounts.LOGIN_TOKEN_KEY),
];

if (!uid || !token) {
return;
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/client/meteorOverrides/login/saml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ Meteor.logout = async function (...args) {

// Remove the userId from the client to prevent calls to the server while the logout is processed.
// If the logout fails, the userId will be reloaded on the resume call
Meteor._localStorage.removeItem(Accounts.USER_ID_KEY);
Accounts.storageLocation.removeItem(Accounts.USER_ID_KEY);

// A nasty bounce: 'result' has the SAML LogoutRequest but we need a proper 302 to redirected from the server.
window.location.replace(Meteor.absoluteUrl(`_saml/sloRedirect/${provider}/?redirect=${encodeURIComponent(result)}`));
Expand Down
6 changes: 2 additions & 4 deletions apps/meteor/client/providers/UserProvider/UserProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ import { useDeleteUser } from './hooks/useDeleteUser';
import { useEmailVerificationWarning } from './hooks/useEmailVerificationWarning';
import { useUpdateAvatar } from './hooks/useUpdateAvatar';

const getUserId = (): string | null => Meteor.userId();

const getUser = (): IUser | null => Meteor.user() as IUser | null;

const logout = (): Promise<void> =>
Expand All @@ -42,9 +40,9 @@ type UserProviderProps = {
};

const UserProvider = ({ children }: UserProviderProps): ReactElement => {
const userId = useReactiveValue(getUserId);
const previousUserId = useRef(userId);
const user = useReactiveValue(getUser);
const userId = user?._id ?? null;
const previousUserId = useRef(userId);
const [userLanguage, setUserLanguage] = useLocalStorage('userLanguage', '');
const [preferedLanguage, setPreferedLanguage] = useLocalStorage('preferedLanguage', '');

Expand Down
16 changes: 1 addition & 15 deletions apps/meteor/client/startup/accounts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Accounts } from 'meteor/accounts-base';
import { Meteor } from 'meteor/meteor';
import { Tracker } from 'meteor/tracker';

import { settings } from '../../app/settings/client';
// import { settings } from '../../app/settings/client';
import { mainReady } from '../../app/ui-utils/client';
import { sdk } from '../../app/utils/client/lib/SDKClient';
import { t } from '../../app/utils/lib/i18n';
Expand All @@ -25,17 +25,3 @@ Accounts.onEmailVerificationLink((token: string) => {
});
});
});

Meteor.startup(() => {
Tracker.autorun((computation) => {
const forgetUserSessionOnWindowClose = settings.get('Accounts_ForgetUserSessionOnWindowClose');

if (forgetUserSessionOnWindowClose === undefined) {
return;
}

computation.stop();

Accounts.config({ clientStorage: forgetUserSessionOnWindowClose ? 'session' : 'local' });
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { useUniqueId } from '@rocket.chat/fuselage-hooks';
import { Form } from '@rocket.chat/layout';
import { useLogout, useRoute } from '@rocket.chat/ui-contexts';
import { Accounts } from 'meteor/accounts-base';
import { Meteor } from 'meteor/meteor';
import React, { useEffect, useMemo, useRef } from 'react';
import { Trans, useTranslation } from 'react-i18next';

Expand All @@ -19,7 +18,7 @@ type AuthorizationFormPageProps = {
};

const AuthorizationFormPage = ({ oauthApp, redirectUri, user }: AuthorizationFormPageProps) => {
const token = useMemo(() => Meteor._localStorage.getItem(Accounts.LOGIN_TOKEN_KEY) ?? undefined, []);
const token = useMemo(() => Accounts.storageLocation.getItem(Accounts.LOGIN_TOKEN_KEY) ?? undefined, []);

const formLabelId = useUniqueId();

Expand Down
1 change: 1 addition & 0 deletions apps/meteor/definition/externals/meteor/accounts-base.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
declare module 'meteor/accounts-base' {
namespace Accounts {
const storageLocation: Window['localStorage'];
function createUser(
options: {
username?: string;
Expand Down

0 comments on commit 7dc9c41

Please sign in to comment.