Skip to content

Commit

Permalink
feat(react): Convert third party auth 'Set password' page to React
Browse files Browse the repository at this point in the history
Because:
* There are data-sharing problems with this page currently being on Backbone while other pages in the flow are in React, causing a double sign-in for all 'Set password' flows, plus the inability to sign into Sync and maintain CWTS choices for desktop oauth
* We want to move completely over from Backbone to React

This commit:
* Creates 'post_verify/third_party_auth/set_password' page in React with container component
* Sends web channel messages up to Sync after password create success
* Shares form logic with Signup, includes useSyncEngine hook for DRYness
* Changes InlineRecoveryKeySetup to check local storage instead of location state, which prevents needing to prop drill as users should always be signed in and these values available in local storage on this page
* Returns authPW and unwrapBKey from create password in auth-client

closes FXA-6651
  • Loading branch information
LZoog committed Nov 21, 2024
1 parent 1df6761 commit 13a73ee
Show file tree
Hide file tree
Showing 25 changed files with 879 additions and 272 deletions.
1 change: 1 addition & 0 deletions libs/shared/l10n/src/lib/branding.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
-product-firefox-cloud = Firefox Cloud
-product-mozilla-monitor = Mozilla Monitor
-product-firefox-relay = Firefox Relay
-product-firefox-sync = Firefox Sync
-product-pocket = Pocket
-brand-apple = Apple
Expand Down
18 changes: 15 additions & 3 deletions packages/fxa-auth-client/lib/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1538,14 +1538,26 @@ export default class AuthClient {
email: string,
newPassword: string,
headers?: Headers
): Promise<number> {
): Promise<{ passwordCreated: number; authPW: string; unwrapBKey: string }> {
const newCredentials = await crypto.getCredentials(email, newPassword);
const authPW = newCredentials.authPW;

const payload = {
authPW: newCredentials.authPW,
authPW,
};

return this.sessionPost('/password/create', sessionToken, payload, headers);
const passwordCreated = await this.sessionPost(
'/password/create',
sessionToken,
payload,
headers
);

return {
passwordCreated,
authPW,
unwrapBKey: newCredentials.unwrapBKey,
};
}

async getRandomBytes(headers?: Headers) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ const getReactRouteGroups = (showReactApp, reactRoute) => {
'post_verify/third_party_auth/callback',
'post_verify/third_party_auth/set_password',
]),
fullProdRollout: false,
fullProdRollout: true,
},

webChannelExampleRoutes: {
Expand Down
6 changes: 6 additions & 0 deletions packages/fxa-settings/src/components/App/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ import SignupConfirmed from '../../pages/Signup/SignupConfirmed';
import WebChannelExample from '../../pages/WebChannelExample';
import SignoutSync from '../Settings/SignoutSync';
import InlineRecoveryKeySetupContainer from '../../pages/InlineRecoveryKeySetup/container';
import SetPassword from '../../pages/PostVerify/SetPassword';
import SetPasswordContainer from '../../pages/PostVerify/SetPassword/container';

const Settings = lazy(() => import('../Settings'));

Expand Down Expand Up @@ -318,6 +320,10 @@ const AuthAndAccountSetupRoutes = ({
path="/post_verify/third_party_auth/callback/*"
{...{ flowQueryParams }}
/>
<SetPasswordContainer
path="/post_verify/finish_account_setup/set_password/*"
{...{ flowQueryParams, integration }}
/>

{/* Reset password */}
<ResetPasswordContainer
Expand Down
Empty file.
138 changes: 138 additions & 0 deletions packages/fxa-settings/src/components/FormSetupAccount/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import React from 'react';
import { FtlMsg } from 'fxa-react/lib/utils';
import FormPasswordWithBalloons from '../FormPasswordWithBalloons';
import InputText from '../InputText';
import LinkExternal from 'fxa-react/components/LinkExternal';
import GleanMetrics from '../../lib/glean';
import ChooseNewsletters from '../ChooseNewsletters';
import ChooseWhatToSync from '../ChooseWhatToSync';
import LoadingSpinner from 'fxa-react/components/LoadingSpinner';
import { FormSetupAccountProps } from './interfaces';
import { newsletters } from '../ChooseNewsletters/newsletters';

export const FormSetupAccount = ({
formState,
errors,
trigger,
register,
getValues,
onFocus,
email,
onFocusMetricsEvent,
onSubmit,
loading,
isSync,
offeredSyncEngineConfigs,
setDeclinedSyncEngines,
isDesktopRelay,
setSelectedNewsletterSlugs,
ageCheckErrorText,
setAgeCheckErrorText,
onFocusAgeInput,
onBlurAgeInput,
}: FormSetupAccountProps) => {
const showCWTS = () => {
if (isSync) {
if (offeredSyncEngineConfigs) {
return (
<ChooseWhatToSync
{...{
offeredSyncEngineConfigs,
setDeclinedSyncEngines,
}}
/>
);
} else {
// Waiting to receive webchannel message from browser
return <LoadingSpinner className="flex justify-center mb-4" />;
}
} else {
// Display nothing if Sync flow that does not support webchannels
// or if CWTS is disabled
return <></>;
}
};

return (
<FormPasswordWithBalloons
{...{
formState,
errors,
trigger,
register,
getValues,
onFocus,
email,
onFocusMetricsEvent,
disableButtonUntilValid: true,
onSubmit,
loading,
}}
passwordFormType="signup"
>
{setAgeCheckErrorText &&
setAgeCheckErrorText &&
onFocusAgeInput &&
onBlurAgeInput && (
<>
{/* TODO: original component had a SR-only label that is not straightforward to implement with existing InputText component
SR-only text: "How old are you? To learn why we ask for your age, follow the “why do we ask” link below. */}
<FtlMsg id="signup-age-check-label" attrs={{ label: true }}>
<InputText
name="age"
label="How old are you?"
inputMode="numeric"
className="mb-4"
pattern="[0-9]*"
maxLength={3}
onChange={() => {
// clear error tooltip if user types in the field
if (ageCheckErrorText) {
setAgeCheckErrorText('');
}
}}
inputRef={register({
pattern: /^[0-9]*$/,
maxLength: 3,
required: true,
})}
onFocusCb={onFocusAgeInput}
onBlurCb={onBlurAgeInput}
errorText={ageCheckErrorText}
tooltipPosition="bottom"
anchorPosition="end"
prefixDataTestId="age"
/>
</FtlMsg>
<FtlMsg id="signup-coppa-check-explanation-link">
<LinkExternal
href="https://www.ftc.gov/business-guidance/resources/childrens-online-privacy-protection-rule-not-just-kids-sites"
className={`link-blue text-sm py-1 -mt-2 self-start ${
isDesktopRelay ? 'mb-8' : 'mb-4'
}`}
onClick={() => GleanMetrics.registration.whyWeAsk()}
>
Why do we ask?
</LinkExternal>
</FtlMsg>
</>
)}

{isSync
? showCWTS()
: !isDesktopRelay &&
setSelectedNewsletterSlugs && (
<ChooseNewsletters
{...{
newsletters,
setSelectedNewsletterSlugs,
}}
/>
)}
</FormPasswordWithBalloons>
);
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import { UseFormMethods } from 'react-hook-form';
import { SetPasswordFormData } from '../../pages/PostVerify/SetPassword/interfaces';
import { SignupFormData } from '../../pages/Signup/interfaces';
import { syncEngineConfigs } from '../ChooseWhatToSync/sync-engines';

export type FormSetupAccountData = SignupFormData | SetPasswordFormData;

export type FormSetupAccountProps = {
formState: UseFormMethods['formState'];
errors: UseFormMethods['errors'];
trigger: UseFormMethods['trigger'];
register: UseFormMethods['register'];
getValues: UseFormMethods['getValues'];
onFocus: () => void;
email: string;
onFocusMetricsEvent: () => void;
onSubmit: (e?: React.BaseSyntheticEvent) => Promise<void>;
loading: boolean;
isSync: boolean;
offeredSyncEngineConfigs?: typeof syncEngineConfigs;
setDeclinedSyncEngines: React.Dispatch<React.SetStateAction<string[]>>;
isDesktopRelay: boolean;
setSelectedNewsletterSlugs?: React.Dispatch<React.SetStateAction<string[]>>;
// Age check props, if not provided it will not be rendered
ageCheckErrorText?: string;
setAgeCheckErrorText?: React.Dispatch<React.SetStateAction<string>>;
onFocusAgeInput?: () => void;
onBlurAgeInput?: () => void;
};
118 changes: 118 additions & 0 deletions packages/fxa-settings/src/lib/hooks/useSyncEngines/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import { useEffect, useMemo, useState } from 'react';
import {
Integration,
isOAuthIntegration,
isSyncDesktopV3Integration,
} from '../../../models';
import {
defaultDesktopV3SyncEngineConfigs,
getSyncEngineIds,
syncEngineConfigs,
webChannelDesktopV3EngineConfigs,
} from '../../../components/ChooseWhatToSync/sync-engines';
import firefox from '../../channels/firefox';
import { Constants } from '../../constants';

type SyncEnginesIntegration = Pick<Integration, 'type' | 'isSync'>;

const useSyncEngines = (integration: SyncEnginesIntegration) => {
const isSyncOAuth = isOAuthIntegration(integration) && integration.isSync();
const isSyncDesktopV3 = isSyncDesktopV3Integration(integration);
const isSync = integration.isSync();

const [webChannelEngines, setWebChannelEngines] = useState<
string[] | undefined
>();
const [offeredSyncEngineConfigs, setOfferedSyncEngineConfigs] = useState<
typeof syncEngineConfigs | undefined
>();
const [declinedSyncEngines, setDeclinedSyncEngines] = useState<string[]>([]);

useEffect(() => {
// This sends a web channel message to the browser to prompt a response
// that we listen for.
// TODO: In content-server, we send this on app-start for all integration types.
// Do we want to move this somewhere else once the index page is Reactified?
if (isSync) {
(async () => {
const status = await firefox.fxaStatus({
// TODO: Improve getting 'context', probably set this on the integration
context: isSyncDesktopV3
? Constants.FX_DESKTOP_V3_CONTEXT
: Constants.OAUTH_CONTEXT,
isPairing: false,
service: Constants.SYNC_SERVICE,
});
if (!webChannelEngines && status.capabilities.engines) {
// choose_what_to_sync may be disabled for mobile sync, see:
// https://github.com/mozilla/application-services/issues/1761
// Desktop OAuth Sync will always provide this capability too
// for consistency.
if (
isSyncDesktopV3 ||
(isSyncOAuth && status.capabilities.choose_what_to_sync)
) {
setWebChannelEngines(status.capabilities.engines);
}
}
})();
}
}, [isSync, isSyncDesktopV3, isSyncOAuth, webChannelEngines]);

useEffect(() => {
if (webChannelEngines) {
if (isSyncDesktopV3) {
// Desktop v3 web channel message sends additional engines
setOfferedSyncEngineConfigs([
...defaultDesktopV3SyncEngineConfigs,
...webChannelDesktopV3EngineConfigs.filter((engine) =>
webChannelEngines.includes(engine.id)
),
]);
} else if (isSyncOAuth) {
// OAuth Webchannel context sends all engines
setOfferedSyncEngineConfigs(
syncEngineConfigs.filter((engine) =>
webChannelEngines.includes(engine.id)
)
);
}
}
}, [isSyncDesktopV3, isSyncOAuth, webChannelEngines]);

useEffect(() => {
if (offeredSyncEngineConfigs) {
const defaultDeclinedSyncEngines = offeredSyncEngineConfigs
.filter((engineConfig) => !engineConfig.defaultChecked)
.map((engineConfig) => engineConfig.id);
setDeclinedSyncEngines(defaultDeclinedSyncEngines);
}
}, [offeredSyncEngineConfigs, setDeclinedSyncEngines]);

const offeredSyncEngines = getSyncEngineIds(offeredSyncEngineConfigs || []);

const selectedEngines = useMemo(() => {
if (isSync) {
return offeredSyncEngines.reduce((acc, syncEngId) => {
acc[syncEngId] = !declinedSyncEngines.includes(syncEngId);
return acc;
}, {} as Record<string, boolean>);
}
return {};
}, [isSync, declinedSyncEngines, offeredSyncEngines]);

return {
offeredSyncEngines,
offeredSyncEngineConfigs,
declinedSyncEngines,
setDeclinedSyncEngines,
// for metrics
selectedEngines,
};
};

export default useSyncEngines;
27 changes: 27 additions & 0 deletions packages/fxa-settings/src/lib/hooks/useSyncEngines/mocks.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import { useState } from 'react';
import {
getSyncEngineIds,
syncEngineConfigs,
} from '../../../components/ChooseWhatToSync/sync-engines';

export const useMockSyncEngines = () => {
const [declinedSyncEngines, setDeclinedSyncEngines] = useState<string[]>([]);
const offeredSyncEngines = getSyncEngineIds(syncEngineConfigs);

const selectedEngines = offeredSyncEngines.reduce((acc, syncEngId) => {
acc[syncEngId] = !declinedSyncEngines.includes(syncEngId);
return acc;
}, {} as Record<string, boolean>);

return {
offeredSyncEngines,
offeredSyncEngineConfigs: syncEngineConfigs,
declinedSyncEngines,
setDeclinedSyncEngines,
selectedEngines,
};
};
Loading

0 comments on commit 13a73ee

Please sign in to comment.