From ec7ab04d098d15958482e5a2dd3f34fe52616783 Mon Sep 17 00:00:00 2001 From: William Grant Date: Tue, 27 Feb 2024 10:44:47 +1100 Subject: [PATCH] refactor: moved related function from registrationstages to createaccount --- .../overlay/OverlayRightPanelSettings2.tsx | 4 +- ts/components/dialog/EditProfileDialog.tsx | 6 +-- .../registration/RegistrationStages.tsx | 45 +----------------- .../registration/stages/CreateAccount.tsx | 47 ++++++++++++++++++- ts/session/constants.ts | 2 +- ts/session/utils/String.ts | 6 +-- ts/util/accountManager.ts | 16 +++---- 7 files changed, 64 insertions(+), 62 deletions(-) diff --git a/ts/components/conversation/right-panel/overlay/OverlayRightPanelSettings2.tsx b/ts/components/conversation/right-panel/overlay/OverlayRightPanelSettings2.tsx index 850c19182..63a6f7ae3 100644 --- a/ts/components/conversation/right-panel/overlay/OverlayRightPanelSettings2.tsx +++ b/ts/components/conversation/right-panel/overlay/OverlayRightPanelSettings2.tsx @@ -1,6 +1,6 @@ import { useEffect, useState } from 'react'; -import { MAX_NAME_LENGTH } from '../../../../session/constants'; +import { MAX_NAME_LENGTH_BYTES } from '../../../../session/constants'; import { ToastUtils } from '../../../../session/utils'; import { sanitizeSessionUsername } from '../../../../session/utils/String'; import { useSelectedConversationKey } from '../../../../state/selectors/selectedConversation'; @@ -86,7 +86,7 @@ export const OverlayRightPanelSettings2 = () => { placeholder={window.i18n('enterDisplayName')} value={inputValue} error={inputError} - maxLength={MAX_NAME_LENGTH} + maxLength={MAX_NAME_LENGTH_BYTES} onValueChanged={handleInputChanged} onEnterPressed={handleEnterPressed} ctaButton={ diff --git a/ts/components/dialog/EditProfileDialog.tsx b/ts/components/dialog/EditProfileDialog.tsx index a39fd6544..e49100696 100644 --- a/ts/components/dialog/EditProfileDialog.tsx +++ b/ts/components/dialog/EditProfileDialog.tsx @@ -10,7 +10,7 @@ import { YourSessionIDPill, YourSessionIDSelectable } from '../basic/YourSession import { useOurAvatarPath, useOurConversationUsername } from '../../hooks/useParamSelector'; import { ConversationTypeEnum } from '../../models/conversationAttributes'; -import { MAX_NAME_LENGTH } from '../../session/constants'; +import { MAX_NAME_LENGTH_BYTES } from '../../session/constants'; import { getConversationController } from '../../session/conversations'; import { sanitizeSessionUsername } from '../../session/utils/String'; import { editProfileModal, updateEditProfilePictureModel } from '../../state/ducks/modalDialog'; @@ -151,7 +151,7 @@ export const EditProfileDialog = (): ReactElement => { try { const newName = profileName ? profileName.trim() : ''; - if (newName.length === 0 || newName.length > MAX_NAME_LENGTH) { + if (newName.length === 0 || newName.length > MAX_NAME_LENGTH_BYTES) { return; } @@ -256,7 +256,7 @@ export const EditProfileDialog = (): ReactElement => { value={profileName} placeholder={window.i18n('displayName')} onChange={onNameEdited} - maxLength={MAX_NAME_LENGTH} + maxLength={MAX_NAME_LENGTH_BYTES} tabIndex={0} required={true} aria-required={true} diff --git a/ts/components/registration/RegistrationStages.tsx b/ts/components/registration/RegistrationStages.tsx index 58931c4ab..10fb06390 100644 --- a/ts/components/registration/RegistrationStages.tsx +++ b/ts/components/registration/RegistrationStages.tsx @@ -3,7 +3,6 @@ import { useDispatch } from 'react-redux'; import { useMount } from 'react-use'; import styled from 'styled-components'; import { Data } from '../../data/data'; -import { SettingsKey } from '../../data/settings-key'; import { getSwarmPollingInstance } from '../../session/apis/snode_api'; import { getConversationController } from '../../session/conversations'; import { mnDecode } from '../../session/crypto/mnemonic'; @@ -31,6 +30,7 @@ import { Flex } from '../basic/Flex'; import { SpacerLG, SpacerSM } from '../basic/Text'; import { SessionIcon, SessionIconButton } from '../icon'; import { CreateAccount, RestoreAccount, Start } from './stages'; +import { displayNameIsValid } from './stages/CreateAccount'; const StyledRegistrationContainer = styled(Flex)` width: 348px; @@ -49,49 +49,6 @@ export async function resetRegistration() { await getConversationController().load(); } -/** - * Returns undefined if an error happened, or the trim userName. - * - * Be sure to use the trimmed userName for creating the account. - */ -const displayNameIsValid = (displayName: string): undefined | string => { - const trimName = displayName.trim(); - - if (!trimName) { - window?.log?.warn('invalid trimmed name for registration'); - ToastUtils.pushToastError('invalidDisplayName', window.i18n('displayNameEmpty')); - return undefined; - } - return trimName; -}; - -export async function signUp(signUpDetails: { - displayName: string; - generatedRecoveryPhrase: string; -}) { - const { displayName, generatedRecoveryPhrase } = signUpDetails; - window?.log?.info('SIGNING UP'); - - const trimName = displayNameIsValid(displayName); - // shows toast to user about the error - if (!trimName) { - return; - } - - try { - await resetRegistration(); - await registerSingleDevice(generatedRecoveryPhrase, 'english', trimName); - await Storage.put(SettingsKey.hasSyncedInitialConfigurationItem, Date.now()); - await setSignWithRecoveryPhrase(false); - trigger('openInbox'); - } catch (e) { - await resetRegistration(); - - ToastUtils.pushToastError('registrationError', `Error: ${e.message || 'Something went wrong'}`); - window?.log?.warn('exception during registration:', e); - } -} - /** * Sign in/restore from seed. * Ask for a display name, as we will drop incoming ConfigurationMessages if any are saved on the swarm. diff --git a/ts/components/registration/stages/CreateAccount.tsx b/ts/components/registration/stages/CreateAccount.tsx index a0bb6cfc2..2640e116c 100644 --- a/ts/components/registration/stages/CreateAccount.tsx +++ b/ts/components/registration/stages/CreateAccount.tsx @@ -1,17 +1,22 @@ import { useEffect, useState } from 'react'; import styled from 'styled-components'; +import { SettingsKey } from '../../../data/settings-key'; +import { ToastUtils } from '../../../session/utils'; import { sanitizeSessionUsername } from '../../../session/utils/String'; +import { trigger } from '../../../shims/events'; import { AccountCreation } from '../../../state/onboarding/ducks/registration'; import { useOnboardAccountCreationStep, useOnboardGeneratedRecoveryPhrase, useOnboardHexGeneratedPubKey, } from '../../../state/onboarding/selectors/registration'; +import { registerSingleDevice } from '../../../util/accountManager'; +import { Storage, setSignWithRecoveryPhrase } from '../../../util/storage'; import { Flex } from '../../basic/Flex'; import { SessionButton, SessionButtonColor } from '../../basic/SessionButton'; import { SpacerLG, SpacerSM } from '../../basic/Text'; import { SessionInput } from '../../inputs'; -import { signUp } from '../RegistrationStages'; +import { resetRegistration } from '../RegistrationStages'; import { BackButtonWithininContainer } from '../components/BackButton'; const StyledContainer = styled.div` @@ -45,6 +50,46 @@ function sanitizeDisplayNameOrToast( } } +/** + * Returns undefined if an error happened, or the trim userName. + * + * Be sure to use the trimmed userName for creating the account. + */ +export const displayNameIsValid = (displayName: string): undefined | string => { + const trimName = displayName.trim(); + + if (!trimName) { + window?.log?.warn('invalid trimmed name for registration'); + ToastUtils.pushToastError('invalidDisplayName', window.i18n('displayNameEmpty')); + return undefined; + } + return trimName; +}; + +async function signUp(signUpDetails: { displayName: string; generatedRecoveryPhrase: string }) { + const { displayName, generatedRecoveryPhrase } = signUpDetails; + window?.log?.info('SIGNING UP'); + + const trimName = displayNameIsValid(displayName); + // shows toast to user about the error + if (!trimName) { + return; + } + + try { + await resetRegistration(); + await registerSingleDevice(generatedRecoveryPhrase, 'english', trimName); + await Storage.put(SettingsKey.hasSyncedInitialConfigurationItem, Date.now()); + await setSignWithRecoveryPhrase(false); + trigger('openInbox'); + } catch (e) { + await resetRegistration(); + + ToastUtils.pushToastError('registrationError', `Error: ${e.message || 'Something went wrong'}`); + window?.log?.warn('exception during registration:', e); + } +} + export const CreateAccount = () => { const step = useOnboardAccountCreationStep(); const generatedRecoveryPhrase = useOnboardGeneratedRecoveryPhrase(); diff --git a/ts/session/constants.ts b/ts/session/constants.ts index c5d1d95d7..0d7524690 100644 --- a/ts/session/constants.ts +++ b/ts/session/constants.ts @@ -69,7 +69,7 @@ export const DEFAULT_RECENT_REACTS = ['😂', '🥰', '😢', '😡', '😮', ' export const REACT_LIMIT = 6; /** character limit for a display name based on libsession MAX_NAME_LENGTH */ -export const MAX_NAME_LENGTH = 100; +export const MAX_NAME_LENGTH_BYTES = 100; export const FEATURE_RELEASE_TIMESTAMPS = { // TODO update to agreed value between platforms for `disappearing_messages` diff --git a/ts/session/utils/String.ts b/ts/session/utils/String.ts index 70fc550e1..848ab892f 100644 --- a/ts/session/utils/String.ts +++ b/ts/session/utils/String.ts @@ -1,5 +1,5 @@ import ByteBuffer from 'bytebuffer'; -import { MAX_NAME_LENGTH } from '../constants'; +import { MAX_NAME_LENGTH_BYTES } from '../constants'; export type Encoding = 'base64' | 'hex' | 'binary' | 'utf8'; export type BufferType = ByteBuffer | Buffer | ArrayBuffer | Uint8Array; @@ -57,7 +57,7 @@ const forbiddenDisplayCharRegex = /\uFFD2*/g; * This does not trim it as otherwise, a user cannot type User A as when he hits the space, it gets trimmed right away. * The trimming should hence happen after calling this and on saving the display name. * - * This functions makes sure that the MAX_NAME_LENGTH is verified for utf8 byte length. MAX_NAME_LENGTH is the agreed character limit between platforms for libsession + * This function makes sure that the MAX_NAME_LENGTH_BYTES is verified for utf8 byte length. * @param inputName the input to sanitize * @returns a sanitized string, untrimmed */ @@ -65,7 +65,7 @@ export const sanitizeSessionUsername = (inputName: string) => { const validChars = inputName.replace(forbiddenDisplayCharRegex, ''); const lengthBytes = encode(validChars, 'utf8').byteLength; - if (lengthBytes > MAX_NAME_LENGTH) { + if (lengthBytes > MAX_NAME_LENGTH_BYTES) { throw new Error('Display name is too long'); } diff --git a/ts/util/accountManager.ts b/ts/util/accountManager.ts index dcdb12e1a..7e5f934b6 100644 --- a/ts/util/accountManager.ts +++ b/ts/util/accountManager.ts @@ -4,20 +4,20 @@ import { fromArrayBufferToBase64, fromHex, toHex } from '../session/utils/String import { getOurPubKeyStrFromCache } from '../session/utils/User'; import { trigger } from '../shims/events'; -import { actions as userActions } from '../state/ducks/user'; -import { mnDecode, mnEncode } from '../session/crypto/mnemonic'; import { SettingsKey } from '../data/settings-key'; +import { ConversationTypeEnum } from '../models/conversationAttributes'; +import { SessionKeyPair } from '../receiver/keypairs'; +import { mnDecode, mnEncode } from '../session/crypto/mnemonic'; +import { LibSessionUtil } from '../session/utils/libsession/libsession_utils'; +import { actions as userActions } from '../state/ducks/user'; +import { Registration } from './registration'; import { + Storage, saveRecoveryPhrase, setLastProfileUpdateTimestamp, setLocalPubKey, setSignInByLinking, - Storage, } from './storage'; -import { Registration } from './registration'; -import { ConversationTypeEnum } from '../models/conversationAttributes'; -import { SessionKeyPair } from '../receiver/keypairs'; -import { LibSessionUtil } from '../session/utils/libsession/libsession_utils'; /** * Might throw @@ -100,7 +100,7 @@ export async function signInByLinkingDevice(mnemonic: string, mnemonicLanguage: * This is a signup. User has no recovery and does not try to link a device * @param mnemonic The mnemonic generated on first app loading and to use for this brand new user * @param mnemonicLanguage only 'english' is supported - * @param profileName the display name to register toi + * @param profileName the display name to register, character limit is MAX_NAME_LENGTH_BYTES */ export async function registerSingleDevice( generatedMnemonic: string,