Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

feat(app): let accounts add an email or password to finish setup

Hampus637b5380e19c
diff --git a/fluxer_app/src/features/auth/components/modals/BackupCodesViewModal.tsx b/fluxer_app/src/features/auth/components/modals/BackupCodesViewModal.tsx
index a4c97cc74..ab199667d 100644
--- a/fluxer_app/src/features/auth/components/modals/BackupCodesViewModal.tsx
+++ b/fluxer_app/src/features/auth/components/modals/BackupCodesViewModal.tsx
@@ -11,6 +11,7 @@ import {modal} from '@app/features/ui/commands/ModalCommands';
import {Input} from '@app/features/ui/components/form/FormInput';
import type {User} from '@app/features/user/models/User';
import * as FormUtils from '@app/lib/forms';
+import {EmailCodeAvailability} from '@fluxer/constants/src/AccountConfigConstants';
import type {I18n} from '@lingui/core';
import {msg} from '@lingui/core/macro';
import {Trans, useLingui} from '@lingui/react/macro';
@@ -84,7 +85,9 @@ export const BackupCodesViewModal = observer(({user}: BackupCodesViewModalProps)
setResendAt(null);
setStage('intro');
}, []);
- const usesSudo = RuntimeConfig.usesUsernameSignIn;
+ const usesSudo =
+ RuntimeConfig.emailCodeAvailabilityFor({hasEmail: user.email != null, emailVerified: user.verified === true}) !==
+ EmailCodeAvailability.AVAILABLE;
const showWithSudo = useCallback(async () => {
setSubmitting(true);
try {
diff --git a/fluxer_app/src/features/auth/components/modals/ClaimAccountModal.module.css b/fluxer_app/src/features/auth/components/modals/ClaimAccountModal.module.css
new file mode 100644
index 000000000..6ae237aa0
--- /dev/null
+++ b/fluxer_app/src/features/auth/components/modals/ClaimAccountModal.module.css
@@ -0,0 +1,12 @@
+.resendRow {
+ display: flex;
+ justify-content: flex-start;
+ margin-top: -0.25rem;
+}
+
+.status {
+ margin: 0;
+ font-size: 0.875rem;
+ line-height: 1.25rem;
+ color: var(--text-tertiary);
+}
diff --git a/fluxer_app/src/features/auth/components/modals/ClaimAccountModal.tsx b/fluxer_app/src/features/auth/components/modals/ClaimAccountModal.tsx
index 7e33fa8bd..72ec6d5ea 100644
--- a/fluxer_app/src/features/auth/components/modals/ClaimAccountModal.tsx
+++ b/fluxer_app/src/features/auth/components/modals/ClaimAccountModal.tsx
@@ -4,12 +4,21 @@ import * as Modal from '@app/features/app/components/dialogs/Modal';
import {EXAMPLE_PERSONAL_EMAIL} from '@app/features/app/config/I18nDisplayConstants';
import {useFormSubmit} from '@app/features/app/hooks/useFormSubmit';
import RuntimeConfig from '@app/features/app/state/RuntimeConfig';
+import {NEW_CODE_SENT_DESCRIPTOR} from '@app/features/auth/AuthMessageDescriptors';
+import {offerAuthenticatorCalmly} from '@app/features/auth/components/modals/AuthenticatorOfferModal';
+import styles from '@app/features/auth/components/modals/ClaimAccountModal.module.css';
+import {EmailCodeField} from '@app/features/auth/flow/EmailCodeField';
+import {isCompleteEmailCode, parseIsoTimestamp} from '@app/features/auth/flow/identifier_first/IdentifierFirstState';
+import {QuietButton} from '@app/features/auth/flow/QuietButton';
+import {useResendCooldown} from '@app/features/auth/hooks/useResendCooldown';
import {
+ ADD_EMAIL_DESCRIPTOR,
CLAIM_ACCOUNT_DESCRIPTOR,
EMAIL_DESCRIPTOR,
PASSWORD_DESCRIPTOR,
USERNAME_DESCRIPTOR,
VERIFICATION_CODE_DESCRIPTOR,
+ VERIFY_DESCRIPTOR,
} from '@app/features/i18n/utils/CommonMessageDescriptors';
import type {HttpError} from '@app/features/platform/types/EndpointError';
import {Button} from '@app/features/ui/button/Button';
@@ -20,14 +29,18 @@ import {Form} from '@app/features/ui/components/form/Form';
import {Input} from '@app/features/ui/components/form/FormInput';
import ModalState from '@app/features/ui/state/Modal';
import {SteppedCarousel} from '@app/features/ui/stepped_carousel/SteppedCarousel';
+import * as AccountTierCommands from '@app/features/user/commands/AccountTierCommands';
import {createRecoveryKitWithPasswordAndOpen} from '@app/features/user/commands/RecoveryKitCommands';
import * as UserCommands from '@app/features/user/commands/UserCommands';
import Users from '@app/features/user/state/Users';
import * as FormUtils from '@app/lib/forms';
+import {ClaimAccountNextSteps, VerificationBases} from '@fluxer/constants/src/AccountConfigConstants';
+import {AccountTiers, AccountVerificationNeeds, LocalCredentialKinds} from '@fluxer/constants/src/AccountTierConstants';
+import type {MessageDescriptor} from '@lingui/core';
import {msg} from '@lingui/core/macro';
import {Trans, useLingui} from '@lingui/react/macro';
import {observer} from 'mobx-react-lite';
-import {useEffect, useMemo, useState} from 'react';
+import {useEffect, useMemo, useRef, useState} from 'react';
import {useForm} from 'react-hook-form';
const VERIFICATION_CODE_SENT_DESCRIPTOR = msg({
@@ -74,19 +87,35 @@ interface UsernameClaimInputs {
const USERNAME_CLAIM_PATH_MAP = {new_password: 'newPassword'} as const;
-const UsernameClaimAccountModal = observer(() => {
+interface ClaimFlowOptions {
+ readonly onComplete?: () => void;
+ readonly onDismiss?: () => void;
+ readonly reason?: string | null;
+}
+
+const UsernameClaimAccountModal = observer(({onComplete, onDismiss, reason}: ClaimFlowOptions) => {
const {i18n} = useLingui();
+ const dismiss = () => {
+ ModalCommands.popWithKey(CLAIM_ACCOUNT_MODAL_KEY);
+ onDismiss?.();
+ };
const form = useForm<UsernameClaimInputs>({
defaultValues: {username: Users.currentUser?.username ?? '', newPassword: '', confirmPassword: ''},
});
+ const hasPasskey = hasRegisteredPasskey();
const handleClaim = async (data: UsernameClaimInputs) => {
if (data.newPassword !== data.confirmPassword) {
form.setError('confirmPassword', {type: 'validate', message: i18n._(PASSWORDS_DO_NOT_MATCH_DESCRIPTOR)});
return;
}
- const updated = await UserCommands.update({username: data.username.trim(), new_password: data.newPassword});
+ const username = data.username.trim();
+ const updated = await UserCommands.update(
+ data.newPassword === '' ? {username} : {username, new_password: data.newPassword},
+ );
ModalCommands.popWithKey(CLAIM_ACCOUNT_MODAL_KEY);
ToastCommands.createToast({type: 'success', children: i18n._(ACCOUNT_CLAIMED_SUCCESSFULLY_DESCRIPTOR)});
+ onComplete?.();
+ if (data.newPassword === '') return;
void createRecoveryKitWithPasswordAndOpen({
userId: updated.id,
password: data.newPassword,
@@ -101,7 +130,7 @@ const UsernameClaimAccountModal = observer(() => {
pathMap: USERNAME_CLAIM_PATH_MAP,
});
return (
- <Modal.Root size="small" centered data-flx="auth.claim-account-modal.username.modal-root">
+ <Modal.Root size="small" centered onClose={dismiss} data-flx="auth.claim-account-modal.username.modal-root">
<Modal.Header
title={i18n._(CLAIM_YOUR_ACCOUNT_DESCRIPTOR)}
data-flx="auth.claim-account-modal.username.modal-header"
@@ -109,6 +138,11 @@ const UsernameClaimAccountModal = observer(() => {
<Form form={form} onSubmit={handleSubmit} data-flx="auth.claim-account-modal.username.form.submit">
<Modal.Content data-flx="auth.claim-account-modal.username.modal-content">
<Modal.ContentLayout data-flx="auth.claim-account-modal.username.modal-content-layout">
+ {reason == null ? null : (
+ <Modal.Description dir="auto" data-flx="auth.claim-account-modal.username.reason">
+ {reason}
+ </Modal.Description>
+ )}
<Modal.Description data-flx="auth.claim-account-modal.username.modal-description">
<Trans>
Claim your account by choosing a username and password. You sign in with them, so pick ones you will
@@ -139,7 +173,7 @@ const UsernameClaimAccountModal = observer(() => {
maxLength={128}
minLength={8}
placeholder={'•'.repeat(32)}
- required={true}
+ required={!hasPasskey}
type="password"
/>
<Input
@@ -151,7 +185,7 @@ const UsernameClaimAccountModal = observer(() => {
maxLength={128}
minLength={8}
placeholder={'•'.repeat(32)}
- required={true}
+ required={!hasPasskey}
type="password"
/>
</Modal.InputGroup>
@@ -159,7 +193,7 @@ const UsernameClaimAccountModal = observer(() => {
</Modal.Content>
<Modal.Footer data-flx="auth.claim-account-modal.username.footer">
<Button
- onClick={ModalCommands.pop}
+ onClick={dismiss}
variant="secondary"
type="button"
data-flx="auth.claim-account-modal.username.button.pop"
@@ -302,7 +336,7 @@ const EmailClaimAccountModal = observer(() => {
<>
<Modal.Description data-flx="auth.claim-account-modal.modal-description--2">
<Trans>
- Enter the code we sent to your email to verify it. Your password will be set once the code is confirmed.
+ Enter the code we sent to your email to confirm it. Your password will be set once the code is confirmed.
</Trans>
</Modal.Description>
<Modal.InputGroup data-flx="auth.claim-account-modal.modal-input-group--2">
@@ -388,26 +422,376 @@ const EmailClaimAccountModal = observer(() => {
</Modal.Root>
);
});
-const ClaimAccountModal = observer(() =>
- RuntimeConfig.usesUsernameSignIn ? (
- <UsernameClaimAccountModal data-flx="auth.claim-account-modal.username-claim-account-modal" />
- ) : (
- <EmailClaimAccountModal data-flx="auth.claim-account-modal.email-claim-account-modal" />
- ),
-);
+const EMAIL_CONFIRMED_DESCRIPTOR = msg({
+ message: 'Email confirmed',
+ comment: 'Toast after someone confirms their email address with the emailed code.',
+});
+const EMAIL_ADDED_DESCRIPTOR = msg({
+ message: 'Email added',
+ comment: 'Toast after someone adds an email and password on an instance that cannot send email codes.',
+});
+const ADD_EMAIL_TITLE_DESCRIPTOR = msg({
+ message: 'Add an email',
+ comment: 'Heading of the dialog where someone with an unclaimed account adds an email.',
+});
+const ADD_EMAIL_TEXT_DESCRIPTOR = msg({
+ message: "Add an email to sign in on other devices. We'll send you a code to confirm it.",
+ comment:
+ 'Text in the dialog where someone with an unclaimed account adds an email, on an instance that sends email codes.',
+});
+const ADD_EMAIL_NO_DELIVERY_TEXT_DESCRIPTOR = msg({
+ message: 'Add an email and a password to sign in on other devices.',
+ comment: 'Text in the add email dialog on an instance that cannot send email codes.',
+});
+const SET_PASSWORD_TITLE_DESCRIPTOR = msg({
+ message: 'Set a password',
+ comment: 'Heading of the dialog where someone whose account has an email but no password sets one.',
+});
+const SET_PASSWORD_TEXT_DESCRIPTOR = msg({
+ message: 'Set a password to sign in on other devices with this email.',
+ comment:
+ 'Text in the dialog where someone whose account has an email but no password sets one, on an instance that cannot send email codes.',
+});
+const SET_PASSWORD_BUTTON_DESCRIPTOR = msg({
+ message: 'Set password',
+ comment: 'Button that saves the password in the dialog for an account that has an email but no password.',
+});
+const PASSWORD_SET_DESCRIPTOR = msg({
+ message: 'Password set',
+ comment: 'Toast after someone whose account has an email but no password sets one.',
+});
+const CONFIRM_EMAIL_TITLE_DESCRIPTOR = msg({
+ message: 'Confirm your email',
+ comment: 'Heading of the dialog where someone types the code we emailed them to confirm their address.',
+});
+const CONFIRM_LATER_DESCRIPTOR = msg({
+ message: 'Confirm later',
+ comment: 'Secondary button that closes the email code dialog without confirming the address yet.',
+});
+const SEND_CODE_DESCRIPTOR = msg({
+ message: 'Send code',
+ comment: 'Button that emails a confirmation code to the address the person typed.',
+});
+const RESEND_CODE_DESCRIPTOR = msg({
+ message: 'Send a new code',
+ comment: 'Quiet text link under the code field that emails a fresh confirmation code.',
+});
+const RESEND_IN_DESCRIPTOR = msg({
+ message: 'Send a new code in {seconds}s',
+ comment: 'Disabled quiet text link while a new confirmation code cannot be sent yet. seconds counts down.',
+});
-let hasShownClaimAccountModalThisSession = false;
+interface AccountEmailFlowProps extends ClaimFlowOptions {
+ readonly startWithCode: boolean;
+}
-export const openClaimAccountModal = ({force = false}: {force?: boolean} = {}): void => {
- if (ModalState.hasModal(CLAIM_ACCOUNT_MODAL_KEY)) {
- return;
+interface AccountEmailInputs {
+ email: string;
+ password: string;
+}
+
+function hasRegisteredPasskey(): boolean {
+ const credential = Users.currentUser?.localCredential;
+ return credential === LocalCredentialKinds.PASSKEY || credential === LocalCredentialKinds.PASSWORD_AND_PASSKEY;
+}
+
+function useCodeDelivery() {
+ const [resendAt, setResendAt] = useState<number | null>(null);
+ const seconds = useResendCooldown(resendAt);
+ const applyDelivery = (delivery: {resend_available_at: string}) =>
+ setResendAt(parseIsoTimestamp(delivery.resend_available_at, Date.now() + 30_000));
+ return {seconds, applyDelivery};
+}
+
+const AccountEmailFlowModal = observer(function AccountEmailFlowModal({
+ startWithCode,
+ onComplete,
+ onDismiss,
+ reason,
+}: AccountEmailFlowProps) {
+ const {i18n} = useLingui();
+ const user = Users.currentUser;
+ const existingEmail = user?.verificationNeed === AccountVerificationNeeds.SET_PASSWORD ? (user.email ?? null) : null;
+ const form = useForm<AccountEmailInputs>({defaultValues: {email: existingEmail ?? '', password: ''}});
+ const [stage, setStage] = useState<Stage>(startWithCode ? 'verify' : 'collect');
+ const [code, setCode] = useState('');
+ const [codeError, setCodeError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [resent, setResent] = useState(false);
+ const {seconds, applyDelivery} = useCodeDelivery();
+ const codeInputRef = useRef<HTMLInputElement | null>(null);
+ const sentRef = useRef(false);
+ const emailsEnabled = RuntimeConfig.emailsEnabled;
+ const asksPassword = existingEmail !== null || RuntimeConfig.verificationBasis === VerificationBases.LOCAL_CREDENTIAL;
+ const passwordRequired = asksPassword && !hasRegisteredPasskey();
+ const sentTo = user?.email ?? form.getValues('email');
+ const close = () => {
+ ModalCommands.popWithKey(CLAIM_ACCOUNT_MODAL_KEY);
+ };
+ const finishLater = () => {
+ close();
+ onDismiss?.();
+ };
+ const finish = () => {
+ close();
+ if (onComplete === undefined) {
+ void offerAuthenticatorCalmly();
+ } else {
+ onComplete();
+ }
+ };
+ const sendVerificationCode = async (): Promise<boolean> => {
+ setBusy(true);
+ setCodeError(null);
+ setResent(false);
+ try {
+ applyDelivery(await AccountTierCommands.sendEmailVerificationCode());
+ return true;
+ } catch (error) {
+ setCodeError(FormUtils.extractErrorMessage(i18n, error));
+ return false;
+ } finally {
+ setBusy(false);
+ }
+ };
+ useEffect(() => {
+ if (!startWithCode || sentRef.current) return;
+ sentRef.current = true;
+ void sendVerificationCode();
+ }, [startWithCode]);
+ const handleCollect = async (data: AccountEmailInputs) => {
+ const delivery = await AccountTierCommands.claimAccount(
+ existingEmail ?? data.email.trim(),
+ asksPassword ? data.password : null,
+ );
+ if (delivery.next_step === ClaimAccountNextSteps.NONE) {
+ ToastCommands.createToast({
+ type: 'success',
+ children: i18n._(existingEmail === null ? EMAIL_ADDED_DESCRIPTOR : PASSWORD_SET_DESCRIPTOR),
+ });
+ finish();
+ return;
+ }
+ applyDelivery(delivery);
+ setCode('');
+ setStage('verify');
+ };
+ const {handleSubmit, isSubmitting} = useFormSubmit({form, onSubmit: handleCollect, defaultErrorField: 'email'});
+ const confirm = async (value: string) => {
+ if (!isCompleteEmailCode(value) || busy) return;
+ setBusy(true);
+ setCodeError(null);
+ try {
+ await AccountTierCommands.confirmEmailVerification(value);
+ ToastCommands.createToast({type: 'success', children: i18n._(EMAIL_CONFIRMED_DESCRIPTOR)});
+ finish();
+ } catch (error) {
+ setCodeError(FormUtils.extractErrorMessage(i18n, error));
+ } finally {
+ setBusy(false);
+ }
+ };
+ const handleResend = async () => {
+ if (seconds > 0 || busy) return;
+ setResent(await sendVerificationCode());
+ };
+ let collectText: MessageDescriptor;
+ if (existingEmail !== null) {
+ collectText = SET_PASSWORD_TEXT_DESCRIPTOR;
+ } else if (emailsEnabled) {
+ collectText = ADD_EMAIL_TEXT_DESCRIPTOR;
+ } else {
+ collectText = ADD_EMAIL_NO_DELIVERY_TEXT_DESCRIPTOR;
+ }
+ let collectButton: MessageDescriptor;
+ if (existingEmail !== null) {
+ collectButton = SET_PASSWORD_BUTTON_DESCRIPTOR;
+ } else if (emailsEnabled) {
+ collectButton = SEND_CODE_DESCRIPTOR;
+ } else {
+ collectButton = ADD_EMAIL_DESCRIPTOR;
+ }
+ if (stage === 'verify') {
+ return (
+ <Modal.Root
+ size="small"
+ centered
+ initialFocusRef={codeInputRef}
+ onClose={finishLater}
+ data-flx="auth.claim-account-modal.verify.modal-root"
+ >
+ <Modal.Header
+ title={i18n._(CONFIRM_EMAIL_TITLE_DESCRIPTOR)}
+ data-flx="auth.claim-account-modal.verify.header"
+ />
+ <Form form={form} onSubmit={() => void confirm(code)} data-flx="auth.claim-account-modal.verify.form">
+ <Modal.Content data-flx="auth.claim-account-modal.verify.content">
+ <Modal.ContentLayout data-flx="auth.claim-account-modal.verify.content-layout">
+ {reason == null ? null : (
+ <Modal.Description dir="auto" data-flx="auth.claim-account-modal.verify.reason">
+ {reason}
+ </Modal.Description>
+ )}
+ <Modal.Description dir="auto" data-flx="auth.claim-account-modal.verify.description">
+ <Trans comment="Code step in the claim account dialog. The tag wraps the email address the code was sent to.">
+ Enter the code we sent to{' '}
+ <bdi data-flx="auth.claim-account-modal.account-email-flow-modal.bdi">{sentTo}</bdi>.
+ </Trans>
+ </Modal.Description>
+ <EmailCodeField
+ value={code}
+ error={codeError}
+ disabled={busy}
+ onChange={setCode}
+ onComplete={(value) => void confirm(value)}
+ inputRef={codeInputRef}
+ data-flx="auth.claim-account-modal.verify.code"
+ />
+ {resent ? (
+ <p className={styles.status} role="status" data-flx="auth.claim-account-modal.verify.status">
+ {i18n._(NEW_CODE_SENT_DESCRIPTOR)}
+ </p>
+ ) : null}
+ <div className={styles.resendRow} data-flx="auth.claim-account-modal.verify.resend-row">
+ <QuietButton
+ disabled={seconds > 0 || busy}
+ onClick={() => void handleResend()}
+ data-flx="auth.claim-account-modal.verify.button.resend"
+ >
+ {seconds > 0 ? i18n._(RESEND_IN_DESCRIPTOR, {seconds}) : i18n._(RESEND_CODE_DESCRIPTOR)}
+ </QuietButton>
+ </div>
+ </Modal.ContentLayout>
+ </Modal.Content>
+ <Modal.Footer data-flx="auth.claim-account-modal.verify.footer">
+ <Button
+ variant="secondary"
+ type="button"
+ onClick={finishLater}
+ data-flx="auth.claim-account-modal.verify.button.later"
+ >
+ {i18n._(CONFIRM_LATER_DESCRIPTOR)}
+ </Button>
+ <Button
+ type="submit"
+ submitting={busy}
+ disabled={!isCompleteEmailCode(code)}
+ data-flx="auth.claim-account-modal.verify.button.submit"
+ >
+ {i18n._(VERIFY_DESCRIPTOR)}
+ </Button>
+ </Modal.Footer>
+ </Form>
+ </Modal.Root>
+ );
+ }
+ return (
+ <Modal.Root size="small" centered onClose={finishLater} data-flx="auth.claim-account-modal.collect.modal-root">
+ <Modal.Header
+ title={i18n._(existingEmail === null ? ADD_EMAIL_TITLE_DESCRIPTOR : SET_PASSWORD_TITLE_DESCRIPTOR)}
+ data-flx="auth.claim-account-modal.collect.header"
+ />
+ <Form form={form} onSubmit={handleSubmit} data-flx="auth.claim-account-modal.collect.form.submit">
+ <Modal.Content data-flx="auth.claim-account-modal.collect.content">
+ <Modal.ContentLayout data-flx="auth.claim-account-modal.collect.content-layout">
+ <Modal.Description dir="auto" data-flx="auth.claim-account-modal.collect.description">
+ {reason ?? i18n._(collectText)}
+ </Modal.Description>
+ <Modal.InputGroup data-flx="auth.claim-account-modal.collect.input-group">
+ <Input
+ data-flx="auth.claim-account-modal.collect.input.email"
+ {...form.register('email')}
+ autoComplete="email"
+ autoFocus={existingEmail === null}
+ error={form.formState.errors.email?.message}
+ label={i18n._(EMAIL_DESCRIPTOR)}
+ maxLength={256}
+ minLength={1}
+ placeholder={EXAMPLE_PERSONAL_EMAIL}
+ readOnly={existingEmail !== null}
+ required={true}
+ type="email"
+ />
+ {asksPassword ? (
+ <Input
+ data-flx="auth.claim-account-modal.collect.input.password"
+ {...form.register('password')}
+ autoComplete="new-password"
+ error={form.formState.errors.password?.message}
+ autoFocus={existingEmail !== null}
+ label={i18n._(PASSWORD_DESCRIPTOR)}
+ maxLength={128}
+ minLength={8}
+ required={passwordRequired}
+ type="password"
+ />
+ ) : null}
+ </Modal.InputGroup>
+ </Modal.ContentLayout>
+ </Modal.Content>
+ <Modal.Footer data-flx="auth.claim-account-modal.collect.footer">
+ <Button
+ onClick={finishLater}
+ variant="secondary"
+ type="button"
+ data-flx="auth.claim-account-modal.collect.button.cancel"
+ >
+ <Trans>Cancel</Trans>
+ </Button>
+ <Button type="submit" submitting={isSubmitting} data-flx="auth.claim-account-modal.collect.button.submit">
+ {i18n._(collectButton)}
+ </Button>
+ </Modal.Footer>
+ </Form>
+ </Modal.Root>
+ );
+});
+
+interface ClaimAccountModalProps extends ClaimFlowOptions {
+ readonly startWithCode: boolean;
+}
+
+const ClaimAccountModal = observer(({onComplete, onDismiss, reason, startWithCode}: ClaimAccountModalProps) => {
+ const user = Users.currentUser;
+ if (RuntimeConfig.usesUsernameSignIn) {
+ return (
+ <UsernameClaimAccountModal
+ onComplete={onComplete}
+ onDismiss={onDismiss}
+ reason={reason}
+ data-flx="auth.claim-account-modal.username-claim-account-modal"
+ />
+ );
+ }
+ if (user?.reportsAccountTier !== true) {
+ return <EmailClaimAccountModal data-flx="auth.claim-account-modal.email-claim-account-modal" />;
}
- if (!force && hasShownClaimAccountModalThisSession) {
+ return (
+ <AccountEmailFlowModal
+ startWithCode={startWithCode}
+ onComplete={onComplete}
+ onDismiss={onDismiss}
+ reason={reason}
+ data-flx="auth.claim-account-modal.account-email-flow-modal"
+ />
+ );
+});
+
+export const openClaimAccountModal = (options: ClaimFlowOptions = {}): void => {
+ if (ModalState.hasModal(CLAIM_ACCOUNT_MODAL_KEY)) {
return;
}
- hasShownClaimAccountModalThisSession = true;
+ const startWithCode = Users.currentUser?.accountTier === AccountTiers.UNVERIFIED;
ModalCommands.pushWithKey(
- modal(() => <ClaimAccountModal data-flx="auth.claim-account-modal.open-claim-account-modal.claim-account-modal" />),
+ modal(() => (
+ <ClaimAccountModal
+ onComplete={options.onComplete}
+ onDismiss={options.onDismiss}
+ reason={options.reason}
+ startWithCode={startWithCode}
+ data-flx="auth.claim-account-modal.open-claim-account-modal.claim-account-modal"
+ />
+ )),
CLAIM_ACCOUNT_MODAL_KEY,
);
};
diff --git a/fluxer_app/src/features/auth/hooks/useVerifyEmailAction.tsx b/fluxer_app/src/features/auth/hooks/useVerifyEmailAction.tsx
index 08a81265c..0424a5aa7 100644
--- a/fluxer_app/src/features/auth/hooks/useVerifyEmailAction.tsx
+++ b/fluxer_app/src/features/auth/hooks/useVerifyEmailAction.tsx
@@ -2,18 +2,22 @@
import i18n from '@app/app/I18n';
import {GenericErrorModal} from '@app/features/app/components/alerts/GenericErrorModal';
+import {
+ EmailVerificationModes,
+ verificationMode,
+} from '@app/features/app/components/dialogs/components/EmailVerificationAlert';
import {UserSettingsModal} from '@app/features/app/components/dialogs/LoadableSettingsModals';
-import RuntimeConfig from '@app/features/app/state/RuntimeConfig';
import * as AuthenticationCommands from '@app/features/auth/commands/AuthenticationCommands';
import {VerificationResult} from '@app/features/auth/commands/AuthenticationCommands';
+import {openClaimAccountModal} from '@app/features/auth/components/modals/ClaimAccountModal';
import {VERIFY_EMAIL_DESCRIPTOR} from '@app/features/i18n/utils/CommonMessageDescriptors';
import {currentInstanceTarget} from '@app/features/platform/transport/InstanceHTTP';
import * as ModalCommands from '@app/features/ui/commands/ModalCommands';
import {modal} from '@app/features/ui/commands/ModalCommands';
import * as ToastCommands from '@app/features/ui/commands/ToastCommands';
import {BouncedEmailChangeModal} from '@app/features/user/components/modals/BouncedEmailChangeModal';
-import type {User} from '@app/features/user/models/User';
import Users from '@app/features/user/state/Users';
+import {needsEmailConfirmation} from '@app/features/user/utils/AccountGates';
import {msg} from '@lingui/core/macro';
import {useLingui} from '@lingui/react/macro';
import {useState} from 'react';
@@ -38,10 +42,14 @@ const SEND_FAILED_MESSAGE_DESCRIPTOR = msg({
message: 'Something went wrong while sending your verification email. Please try again in a moment.',
comment: 'Body of the error modal shown when sending the verification email fails unexpectedly.',
});
-const RESEND_VERIFICATION_EMAIL_DESCRIPTOR = msg({
- message: 'Resend verification email',
+const ENTER_CODE_DESCRIPTOR = msg({
+ message: 'Enter code',
+ comment: 'Button that opens the dialog where people type the code we emailed them to confirm their address.',
+});
+const RESEND_EMAIL_DESCRIPTOR = msg({
+ message: 'Resend email',
comment:
- 'Button label on prompts that ask the user to verify their email, such as the add friend form. A verification email was already sent when the account was created, so this sends another one. Keep it concise.',
+ 'Button label on prompts that ask the user to confirm their email, such as the add friend form and the email nagbar. A verification email was already sent when the account was created, so this sends another one. Keep it concise.',
});
function showVerificationEmailErrorModal(result: VerificationResult): void {
@@ -57,16 +65,6 @@ function showVerificationEmailErrorModal(result: VerificationResult): void {
);
}
-export function canResendVerificationEmail(user: User | null | undefined): boolean {
- return Boolean(
- RuntimeConfig.emailsEnabled &&
- user?.isClaimed() &&
- !RuntimeConfig.usesUsernameSignIn &&
- user.email &&
- !user.verified,
- );
-}
-
export function useResendVerificationEmail() {
const {i18n} = useLingui();
const [isSending, setIsSending] = useState(false);
@@ -99,7 +97,7 @@ function openAccountSecuritySettings(): void {
);
}
-function openBouncedEmailChange(): void {
+export function openBouncedEmailChange(): void {
ModalCommands.push(
modal(() => <BouncedEmailChangeModal data-flx="auth.verify-email-action.bounced-email-change-modal" />),
);
@@ -112,11 +110,14 @@ export function useVerifyEmailAction() {
if (user?.emailBounced === true) {
return {text: i18n._(VERIFY_EMAIL_DESCRIPTOR), onClick: openBouncedEmailChange, submitting: false};
}
- if (!canResendVerificationEmail(user)) {
+ if (verificationMode(user) === EmailVerificationModes.ENTER_CODE) {
+ return {text: i18n._(ENTER_CODE_DESCRIPTOR), onClick: () => openClaimAccountModal(), submitting: false};
+ }
+ if (!needsEmailConfirmation(user)) {
return {text: i18n._(VERIFY_EMAIL_DESCRIPTOR), onClick: openAccountSecuritySettings, submitting: false};
}
return {
- text: i18n._(RESEND_VERIFICATION_EMAIL_DESCRIPTOR),
+ text: i18n._(RESEND_EMAIL_DESCRIPTOR),
onClick: () => void resend(),
submitting: isSending,
};
diff --git a/fluxer_app/src/features/user/commands/RecoveryKitCommands.ts b/fluxer_app/src/features/user/commands/RecoveryKitCommands.ts
index 02f2f8d70..55aeea293 100644
--- a/fluxer_app/src/features/user/commands/RecoveryKitCommands.ts
+++ b/fluxer_app/src/features/user/commands/RecoveryKitCommands.ts
@@ -67,7 +67,7 @@ async function currentUserHasRecoveryKit(userId: string | null): Promise<boolean
}
}
-export async function createAndShowRecoveryKit(): Promise<void> {
+export async function createAndShowRecoveryKit(onDone?: () => void): Promise<void> {
const userId = Users.currentUserId;
const replacing = await currentUserHasRecoveryKit(userId);
const kit = await createRecoveryKit(userId, {});
@@ -75,6 +75,7 @@ export async function createAndShowRecoveryKit(): Promise<void> {
recoveryKey: kit.recovery_key,
createdAt: kit.created_at,
reason: replacing ? 'replaced' : 'created',
+ onDone,
});
}
@@ -83,15 +84,17 @@ export async function createRecoveryKitWithPasswordAndOpen({
password,
username,
discriminator,
+ onDone,
}: {
userId: string;
password: string;
username?: string;
discriminator?: string;
+ onDone?: () => void;
}): Promise<boolean> {
try {
const kit = await createRecoveryKit(userId, {password});
- openRecoveryKitModal({recoveryKey: kit.recovery_key, createdAt: kit.created_at, username, discriminator});
+ openRecoveryKitModal({recoveryKey: kit.recovery_key, createdAt: kit.created_at, username, discriminator, onDone});
return true;
} catch {
ToastCommands.error(i18nGlobal._(RECOVERY_KIT_CREATE_FAILED_DESCRIPTOR));
diff --git a/fluxer_app/src/features/user/components/RecoveryKitReminderGate.tsx b/fluxer_app/src/features/user/components/RecoveryKitReminderGate.tsx
index 7b59b758c..0e6cb52aa 100644
--- a/fluxer_app/src/features/user/components/RecoveryKitReminderGate.tsx
+++ b/fluxer_app/src/features/user/components/RecoveryKitReminderGate.tsx
@@ -60,7 +60,7 @@ function openRecoveryKitPrompt(): void {
export const RecoveryKitReminderGate = observer(() => {
const user = Users.currentUser;
const userId = user?.id ?? null;
- const eligible = RuntimeConfig.usesUsernameSignIn && Boolean(user?.isClaimed());
+ const eligible = RuntimeConfig.usesUsernameSignIn && Boolean(user?.isClaimed()) && Boolean(user?.hasPassword);
useEffect(() => {
if (!eligible || !userId || RecoveryKitStatus.hasShownPrompt(userId)) return;
const timer = window.setTimeout(async () => {
diff --git a/fluxer_app/src/features/user/components/modals/PasswordChangeModal.tsx b/fluxer_app/src/features/user/components/modals/PasswordChangeModal.tsx
index 5ae820578..9a8eeb1c7 100644
--- a/fluxer_app/src/features/user/components/modals/PasswordChangeModal.tsx
+++ b/fluxer_app/src/features/user/components/modals/PasswordChangeModal.tsx
@@ -42,6 +42,10 @@ const UPDATE_YOUR_PASSWORD_DESCRIPTOR = msg({
message: 'Update your password',
comment: 'Short label in the password change modal. Keep it concise. Keep the tone plain and specific.',
});
+const SET_A_PASSWORD_DESCRIPTOR = msg({
+ message: 'Set a password',
+ comment: 'Title of the dialog that adds a password to an account that signs in with email codes.',
+});
const CHANGE_PASSWORD_FORM_DESCRIPTOR = msg({
message: 'Change password form',
comment: 'Short label in the password change modal. Keep it concise. Keep the tone plain and specific.',
@@ -64,6 +68,7 @@ export const PasswordChangeModal = observer(() => {
const {i18n} = useLingui();
const passwordForm = useForm<PasswordForm>();
const usesSudo = RuntimeConfig.usesUsernameSignIn;
+ const settingPassword = Users.currentUser?.hasPassword === false;
const [stage, setStage] = useState<Stage>(usesSudo ? 'changePassword' : 'intro');
const [ticket, setTicket] = useState<string | null>(null);
const [verificationProof, setVerificationProof] = useState<string | null>(null);
@@ -142,9 +147,12 @@ export const PasswordChangeModal = observer(() => {
void RecoveryKitCommands.replaceRecoveryKitAfterPasswordChange(data.new_password);
}
}
- ToastCommands.createToast({type: 'success', children: <Trans>Password changed</Trans>});
+ ToastCommands.createToast({
+ type: 'success',
+ children: settingPassword ? <Trans>Password set</Trans> : <Trans>Password changed</Trans>,
+ });
},
- [usesSudo, ticket, verificationProof, passwordForm, i18n],
+ [usesSudo, ticket, verificationProof, passwordForm, i18n, settingPassword],
);
const {handleSubmit: handlePasswordSubmit, isSubmitting: isPasswordSubmitting} = useFormSubmit({
form: passwordForm,
@@ -153,7 +161,13 @@ export const PasswordChangeModal = observer(() => {
});
const renderIntroStage = () => (
<Modal.Description data-flx="user.password-change-modal.modal-description">
- <Trans>We'll send a verification code to your email before you can change your password.</Trans>
+ {settingPassword ? (
+ <Trans comment="Intro text in the dialog for setting a first password on an account that has none.">
+ We'll send a verification code to your email before you set a password.
+ </Trans>
+ ) : (
+ <Trans>We'll send a verification code to your email before you can change your password.</Trans>
+ )}
</Modal.Description>
);
const renderVerifyEmailStage = () => (
@@ -266,7 +280,7 @@ export const PasswordChangeModal = observer(() => {
submitting={isPasswordSubmitting}
data-flx="user.password-change-modal.button.submit"
>
- <Trans>Change password</Trans>
+ {settingPassword ? <Trans>Set password</Trans> : <Trans>Change password</Trans>}
</Button>
</>
);
@@ -275,7 +289,7 @@ export const PasswordChangeModal = observer(() => {
return (
<Modal.Root size="small" centered data-flx="user.password-change-modal.modal-root">
<Modal.Header
- title={i18n._(UPDATE_YOUR_PASSWORD_DESCRIPTOR)}
+ title={i18n._(settingPassword ? SET_A_PASSWORD_DESCRIPTOR : UPDATE_YOUR_PASSWORD_DESCRIPTOR)}
data-flx="user.password-change-modal.modal-header"
/>
<Modal.Content data-flx="user.password-change-modal.modal-content">