Skip to content

create hook to check validated user #59983

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/components/BookTravelButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {Str} from 'expensify-common';
import type {ReactElement} from 'react';
import React, {useCallback, useContext, useState} from 'react';
import {useOnyx} from 'react-native-onyx';
import useAccountValidation from '@hooks/useAccountValidation';
import useCurrentUserPersonalDetails from '@hooks/useCurrentUserPersonalDetails';
import useLocalize from '@hooks/useLocalize';
import usePermissions from '@hooks/usePermissions';
Expand Down Expand Up @@ -50,7 +51,8 @@ function BookTravelButton({text, shouldRenderErrorMessageBelowButton = false}: B
const StyleUtils = useStyleUtils();
const {translate} = useLocalize();
const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID);
const [isUserValidated] = useOnyx(ONYXKEYS.USER, {selector: (user) => !!user?.validated});
const isUserValidated = useAccountValidation();

const policy = usePolicy(activePolicyID);
const [errorMessage, setErrorMessage] = useState<string | ReactElement>('');
const [travelSettings] = useOnyx(ONYXKEYS.NVP_TRAVEL_SETTINGS);
Expand Down
3 changes: 2 additions & 1 deletion src/components/SettlementButton/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import ButtonWithDropdownMenu from '@components/ButtonWithDropdownMenu';
import type {PaymentType} from '@components/ButtonWithDropdownMenu/types';
import * as Expensicons from '@components/Icon/Expensicons';
import KYCWall from '@components/KYCWall';
import useAccountValidation from '@hooks/useAccountValidation';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import useThemeStyles from '@hooks/useThemeStyles';
Expand Down Expand Up @@ -75,7 +76,7 @@ function SettlementButton({
const {isOffline} = useNetwork();
// The app would crash due to subscribing to the entire report collection if chatReportID is an empty string. So we should have a fallback ID here.
const [chatReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${chatReportID || CONST.DEFAULT_NUMBER_ID}`);
const [isUserValidated] = useOnyx(ONYXKEYS.USER, {selector: (user) => !!user?.validated});
const isUserValidated = useAccountValidation();
const policyEmployeeAccountIDs = policyID ? getPolicyEmployeeAccountIDs(policyID) : [];
const reportBelongsToWorkspace = policyID ? doesReportBelongToWorkspace(chatReport, policyEmployeeAccountIDs, policyID) : false;
const policyIDKey = reportBelongsToWorkspace ? policyID : CONST.POLICY.ID_FAKE;
Expand Down
13 changes: 13 additions & 0 deletions src/hooks/useAccountValidation.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import {useOnyx} from 'react-native-onyx';
import ONYXKEYS from '@src/ONYXKEYS';

// TODO: Remove/Update this hook once we remove the user data and migrate to account data in https://github.com/Expensify/App/issues/59277
function useAccountValidation() {
const [isAccountValidated] = useOnyx(ONYXKEYS.ACCOUNT, {selector: (account) => !!account?.validated});
const [isUserValidated] = useOnyx(ONYXKEYS.USER, {selector: (user) => !!user?.validated});

// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
return isAccountValidated || isUserValidated;
}

export default useAccountValidation;
3 changes: 2 additions & 1 deletion src/pages/AddPersonalBankAccountPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import InputWrapper from '@components/Form/InputWrapper';
import HeaderWithBackButton from '@components/HeaderWithBackButton';
import ScreenWrapper from '@components/ScreenWrapper';
import ScrollView from '@components/ScrollView';
import useAccountValidation from '@hooks/useAccountValidation';
import useLocalize from '@hooks/useLocalize';
import useThemeStyles from '@hooks/useThemeStyles';
import getPlaidOAuthReceivedRedirectURI from '@libs/getPlaidOAuthReceivedRedirectURI';
Expand All @@ -26,7 +27,7 @@ function AddPersonalBankAccountPage() {
const styles = useThemeStyles();
const {translate} = useLocalize();
const [selectedPlaidAccountId, setSelectedPlaidAccountId] = useState('');
const [isUserValidated] = useOnyx(ONYXKEYS.USER, {selector: (user) => !!user?.validated});
const isUserValidated = useAccountValidation();
const [personalBankAccount] = useOnyx(ONYXKEYS.PERSONAL_BANK_ACCOUNT);
const [plaidData] = useOnyx(ONYXKEYS.PLAID_DATA);
const shouldShowSuccess = personalBankAccount?.shouldShowSuccess ?? false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import Section from '@components/Section';
import Text from '@components/Text';
import TextLink from '@components/TextLink';
import ValidateCodeActionModal from '@components/ValidateCodeActionModal';
import useAccountValidation from '@hooks/useAccountValidation';
import useLocalize from '@hooks/useLocalize';
import useTheme from '@hooks/useTheme';
import useThemeStyles from '@hooks/useThemeStyles';
Expand Down Expand Up @@ -95,6 +96,7 @@ function VerifiedBankAccountFlowEntryPoint({
const pendingAction = reimbursementAccount?.pendingAction ?? null;
const [loginList] = useOnyx(ONYXKEYS.LOGIN_LIST);
const optionPressed = useRef('');
const isAccountValidated = useAccountValidation();

const contactMethod = account?.primaryLogin ?? '';
const loginData = useMemo(() => loginList?.[contactMethod], [loginList, contactMethod]);
Expand Down Expand Up @@ -123,7 +125,7 @@ function VerifiedBankAccountFlowEntryPoint({
* note: non USD accounts only have manual option available
*/
useEffect(() => {
if (!account?.validated) {
if (!isAccountValidated) {
return;
}

Expand All @@ -139,13 +141,13 @@ function VerifiedBankAccountFlowEntryPoint({
setUSDBankAccountStep(CONST.BANK_ACCOUNT.STEP.BANK_ACCOUNT);
openPlaidView();
}
}, [account?.validated, isNonUSDWorkspace, setNonUSDBankAccountStep, setUSDBankAccountStep]);
}, [isAccountValidated, isNonUSDWorkspace, setNonUSDBankAccountStep, setUSDBankAccountStep]);

const handleConnectPlaid = () => {
if (isPlaidDisabled) {
return;
}
if (!account?.validated) {
if (!isAccountValidated) {
optionPressed.current = CONST.BANK_ACCOUNT.SETUP_TYPE.PLAID;
toggleValidateCodeActionModal?.(true);
return;
Expand All @@ -158,7 +160,7 @@ function VerifiedBankAccountFlowEntryPoint({
};

const handleConnectManually = () => {
if (!account?.validated) {
if (!isAccountValidated) {
optionPressed.current = CONST.BANK_ACCOUNT.SETUP_TYPE.MANUAL;
toggleValidateCodeActionModal?.(true);
return;
Expand Down
3 changes: 2 additions & 1 deletion src/pages/Travel/WorkspaceAddressForTravelPage.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React from 'react';
import {useOnyx} from 'react-native-onyx';
import type {FormOnyxValues} from '@components/Form/types';
import useAccountValidation from '@hooks/useAccountValidation';
import useLocalize from '@hooks/useLocalize';
import usePolicy from '@hooks/usePolicy';
import Navigation from '@libs/Navigation/Navigation';
Expand All @@ -19,7 +20,7 @@ function WorkspaceAddressForTravelPage({route}: WorkspaceAddressForTravelPagePro
const {translate} = useLocalize();
const [activePolicyID] = useOnyx(ONYXKEYS.NVP_ACTIVE_POLICY_ID);
const policy = usePolicy(activePolicyID);
const [isUserValidated] = useOnyx(ONYXKEYS.USER, {selector: (user) => !!user?.validated});
const isUserValidated = useAccountValidation();

const updatePolicyAddress = (values: FormOnyxValues<typeof ONYXKEYS.FORMS.HOME_ADDRESS_FORM>) => {
if (!policy) {
Expand Down
3 changes: 2 additions & 1 deletion src/pages/home/report/ReportActionItem.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, {useMemo} from 'react';
import type {OnyxEntry} from 'react-native-onyx';
import {useBlockedFromConcierge} from '@components/OnyxProvider';
import useAccountValidation from '@hooks/useAccountValidation';
import useOnyx from '@hooks/useOnyx';
import ModifiedExpenseMessage from '@libs/ModifiedExpenseMessage';
import {getIOUReportIDFromReportActionPreview, getOriginalMessage, isMoneyRequestAction} from '@libs/ReportActionsUtils';
Expand Down Expand Up @@ -51,7 +52,7 @@ function ReportActionItem({action, report, ...props}: PureReportActionItemProps)
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- This is needed to prevent the app from crashing when the app is using imported state.
const [reportNameValuePairs] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS}${report?.reportID || undefined}`);

const [isUserValidated] = useOnyx(ONYXKEYS.USER, {selector: (user) => !!user?.validated});
const isUserValidated = useAccountValidation();
// The app would crash due to subscribing to the entire report collection if parentReportID is an empty string. So we should have a fallback ID here.
// eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
const [parentReport] = useOnyx(`${ONYXKEYS.COLLECTION.REPORT}${report?.parentReportID || undefined}`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import ScreenWrapper from '@components/ScreenWrapper';
import Text from '@components/Text';
import TextInput from '@components/TextInput';
import ValidateCodeActionModal from '@components/ValidateCodeActionModal';
import useAccountValidation from '@hooks/useAccountValidation';
import useBeforeRemove from '@hooks/useBeforeRemove';
import useLocalize from '@hooks/useLocalize';
import useThemeStyles from '@hooks/useThemeStyles';
Expand Down Expand Up @@ -51,7 +52,7 @@ function NewContactMethodPage({route, navigation}: NewContactMethodPageProps) {
const [loginList] = useOnyx(ONYXKEYS.LOGIN_LIST);
const loginData = loginList?.[pendingContactAction?.contactMethod ?? contactMethod];
const validateLoginError = getLatestErrorField(loginData, 'addedLogin');
const [isUserValidated] = useOnyx(ONYXKEYS.USER, {selector: (user) => !!user?.validated});
const isUserValidated = useAccountValidation();

const navigateBackTo = route?.params?.backTo ?? ROUTES.SETTINGS_PROFILE.getRoute();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import ScrollView from '@components/ScrollView';
import Section from '@components/Section';
import Text from '@components/Text';
import ValidateCodeActionModal from '@components/ValidateCodeActionModal';
import useAccountValidation from '@hooks/useAccountValidation';
import useBeforeRemove from '@hooks/useBeforeRemove';
import useLocalize from '@hooks/useLocalize';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
Expand Down Expand Up @@ -45,7 +46,7 @@ function CopyCodesPage({route}: TwoFactorAuthPageProps) {
const [loginList] = useOnyx(ONYXKEYS.LOGIN_LIST);
const [validateCodeAction] = useOnyx(ONYXKEYS.VALIDATE_ACTION_CODE);

const [isUserValidated] = useOnyx(ONYXKEYS.USER, {selector: (user) => !!user?.validated});
const isUserValidated = useAccountValidation();
const contactMethod = account?.primaryLogin ?? '';

const loginData = useMemo(() => loginList?.[contactMethod], [loginList, contactMethod]);
Expand Down
3 changes: 2 additions & 1 deletion src/pages/settings/Wallet/PaymentMethodList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import * as Expensicons from '@components/Icon/Expensicons';
import MenuItem from '@components/MenuItem';
import OfflineWithFeedback from '@components/OfflineWithFeedback';
import Text from '@components/Text';
import useAccountValidation from '@hooks/useAccountValidation';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import type {FormattedSelectedPaymentMethodIcon} from '@hooks/usePaymentMethodState/types';
Expand Down Expand Up @@ -198,7 +199,7 @@ function PaymentMethodList({
const {isOffline} = useNetwork();
const illustrations = useThemeIllustrations();

const [isUserValidated] = useOnyx(ONYXKEYS.USER, {selector: (user) => !!user?.validated});
const isUserValidated = useAccountValidation();
const [bankAccountList = {}, bankAccountListResult] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST);
const [userWallet] = useOnyx(ONYXKEYS.USER_WALLET);
const isLoadingBankAccountList = isLoadingOnyxValue(bankAccountListResult);
Expand Down
17 changes: 9 additions & 8 deletions src/pages/settings/Wallet/VerifyAccountPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ import FullScreenLoadingIndicator from '@components/FullscreenLoadingIndicator';
import HeaderWithBackButton from '@components/HeaderWithBackButton';
import ScreenWrapper from '@components/ScreenWrapper';
import ValidateCodeActionModal from '@components/ValidateCodeActionModal';
import useAccountValidation from '@hooks/useAccountValidation';
import useBeforeRemove from '@hooks/useBeforeRemove';
import useLocalize from '@hooks/useLocalize';
import useThemeStyles from '@hooks/useThemeStyles';
import * as ErrorUtils from '@libs/ErrorUtils';
import {getEarliestErrorField} from '@libs/ErrorUtils';
import Navigation from '@libs/Navigation/Navigation';
import type {PlatformStackScreenProps} from '@libs/Navigation/PlatformStackNavigation/types';
import type {SettingsNavigatorParamList} from '@libs/Navigation/types';
import * as User from '@userActions/User';
import {clearContactMethodErrors, clearUnvalidatedNewContactMethodAction, requestValidateCodeAction, validateSecondaryLogin} from '@userActions/User';
import ONYXKEYS from '@src/ONYXKEYS';
import type SCREENS from '@src/SCREENS';

Expand All @@ -24,8 +25,8 @@ function VerifyAccountPage({route}: VerifyAccountPageProps) {
const contactMethod = account?.primaryLogin ?? '';
const {translate} = useLocalize();
const loginData = loginList?.[contactMethod];
const validateLoginError = ErrorUtils.getEarliestErrorField(loginData, 'validateLogin');
const [isUserValidated] = useOnyx(ONYXKEYS.USER, {selector: (user) => !!user?.validated});
const validateLoginError = getEarliestErrorField(loginData, 'validateLogin');
const isUserValidated = useAccountValidation();
const [validateCodeAction] = useOnyx(ONYXKEYS.VALIDATE_ACTION_CODE);
const [isValidateCodeActionModalVisible, setIsValidateCodeActionModalVisible] = useState(true);

Expand All @@ -34,17 +35,17 @@ function VerifyAccountPage({route}: VerifyAccountPageProps) {

useBeforeRemove(() => setIsValidateCodeActionModalVisible(false));

useEffect(() => () => User.clearUnvalidatedNewContactMethodAction(), []);
useEffect(() => () => clearUnvalidatedNewContactMethodAction(), []);

const handleSubmitForm = useCallback(
(validateCode: string) => {
User.validateSecondaryLogin(loginList, contactMethod, validateCode, true);
validateSecondaryLogin(loginList, contactMethod, validateCode, true);
},
[loginList, contactMethod],
);

const clearError = useCallback(() => {
User.clearContactMethodErrors(contactMethod, 'validateLogin');
clearContactMethodErrors(contactMethod, 'validateLogin');
}, [contactMethod]);

const closeModal = useCallback(() => {
Expand Down Expand Up @@ -87,7 +88,7 @@ function VerifyAccountPage({route}: VerifyAccountPageProps) {

return (
<ValidateCodeActionModal
sendValidateCode={() => User.requestValidateCodeAction()}
sendValidateCode={requestValidateCodeAction}
handleSubmitForm={handleSubmitForm}
validateError={validateLoginError}
hasMagicCodeBeenSent={validateCodeAction?.validateCodeSent}
Expand Down
3 changes: 2 additions & 1 deletion src/pages/settings/Wallet/WalletPage/WalletPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import ScreenWrapper from '@components/ScreenWrapper';
import ScrollView from '@components/ScrollView';
import Section from '@components/Section';
import Text from '@components/Text';
import useAccountValidation from '@hooks/useAccountValidation';
import useLocalize from '@hooks/useLocalize';
import useNetwork from '@hooks/useNetwork';
import usePaymentMethodState from '@hooks/usePaymentMethodState';
Expand Down Expand Up @@ -61,7 +62,7 @@ function WalletPage({shouldListenForResize = false}: WalletPageProps) {
const [isLoadingPaymentMethods] = useOnyx(ONYXKEYS.IS_LOADING_PAYMENT_METHODS, {initialValue: true});
const [userWallet] = useOnyx(ONYXKEYS.USER_WALLET);
const [walletTerms] = useOnyx(ONYXKEYS.WALLET_TERMS, {initialValue: {}});
const [isUserValidated] = useOnyx(ONYXKEYS.USER, {selector: (user) => !!user?.validated});
const isUserValidated = useAccountValidation();
const [isLoadingApp] = useOnyx(ONYXKEYS.IS_LOADING_APP);

const [isActingAsDelegate] = useOnyx(ONYXKEYS.ACCOUNT, {selector: (account) => !!account?.delegatedAccess?.delegate});
Expand Down
11 changes: 8 additions & 3 deletions src/pages/signin/SignInPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import CustomStatusBarAndBackground from '@components/CustomStatusBarAndBackgrou
import ScreenWrapper from '@components/ScreenWrapper';
import ThemeProvider from '@components/ThemeProvider';
import ThemeStylesProvider from '@components/ThemeStylesProvider';
import useAccountValidation from '@hooks/useAccountValidation';
import useLocalize from '@hooks/useLocalize';
import useResponsiveLayout from '@hooks/useResponsiveLayout';
import useSafeAreaInsets from '@hooks/useSafeAreaInsets';
Expand Down Expand Up @@ -68,6 +69,7 @@ type GetRenderOptionsParams = {
hasInitiatedSAMLLogin: boolean;
shouldShowAnotherLoginPageOpenedMessage: boolean;
credentials: OnyxEntry<Credentials>;
isAccountValidated?: boolean;
};

/**
Expand All @@ -89,6 +91,7 @@ function getRenderOptions({
hasInitiatedSAMLLogin,
shouldShowAnotherLoginPageOpenedMessage,
credentials,
isAccountValidated,
}: GetRenderOptionsParams): RenderOption {
const hasAccount = !isEmptyObject(account);
const isSAMLEnabled = !!account?.isSAMLEnabled;
Expand All @@ -108,11 +111,11 @@ function getRenderOptions({
}

// Show the Welcome form if a user is signing up for a new account in a domain that is not controlled
const shouldShouldSignUpWelcomeForm = !!credentials?.login && !account?.validated && !account?.accountExists && !account?.domainControlled;
const shouldShouldSignUpWelcomeForm = !!credentials?.login && !isAccountValidated && !account?.accountExists && !account?.domainControlled;
const shouldShowLoginForm = !shouldShowAnotherLoginPageOpenedMessage && !hasLogin && !hasValidateCode;
const shouldShowEmailDeliveryFailurePage = hasLogin && hasEmailDeliveryFailure && !shouldShowChooseSSOOrMagicCode && !shouldInitiateSAMLLogin;
const shouldShowSMSDeliveryFailurePage = !!(hasLogin && hasSMSDeliveryFailure && !shouldShowChooseSSOOrMagicCode && !shouldInitiateSAMLLogin && account?.accountExists);
const isUnvalidatedSecondaryLogin = hasLogin && !isPrimaryLogin && !account?.validated && !hasEmailDeliveryFailure && !hasSMSDeliveryFailure;
const isUnvalidatedSecondaryLogin = hasLogin && !isPrimaryLogin && !isAccountValidated && !hasEmailDeliveryFailure && !hasSMSDeliveryFailure;
const shouldShowValidateCodeForm =
!shouldShouldSignUpWelcomeForm &&
hasAccount &&
Expand Down Expand Up @@ -151,6 +154,7 @@ function SignInPage({shouldEnableMaxHeight = true}: SignInPageInnerProps, ref: F
const validateCodeFormRef = useRef<BaseValidateCodeFormRef>(null);

const [account] = useOnyx(ONYXKEYS.ACCOUNT);
const isAccountValidated = useAccountValidation();
const [credentials] = useOnyx(ONYXKEYS.CREDENTIALS);
/**
This variable is only added to make sure the component is re-rendered
Expand Down Expand Up @@ -222,6 +226,7 @@ function SignInPage({shouldEnableMaxHeight = true}: SignInPageInnerProps, ref: F
hasInitiatedSAMLLogin,
shouldShowAnotherLoginPageOpenedMessage,
credentials,
isAccountValidated,
});

if (shouldInitiateSAMLLogin) {
Expand Down Expand Up @@ -320,7 +325,7 @@ function SignInPage({shouldEnableMaxHeight = true}: SignInPageInnerProps, ref: F
isVisible={shouldShowLoginForm}
login={login}
onLoginChanged={setLogin}
blurOnSubmit={account?.validated === false}
blurOnSubmit={isAccountValidated === false}
// eslint-disable-next-line react-compiler/react-compiler
scrollPageToTop={signInPageLayoutRef.current?.scrollPageToTop}
/>
Expand Down
Loading