Skip to content
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
9 changes: 1 addition & 8 deletions src/components/auth/LoginPageView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@ import { useForm } from 'react-hook-form';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import { BaseSyntheticEvent, type CSSProperties, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import axios from 'axios';
import dayjs from 'dayjs';
import { WarningCircle } from '@phosphor-icons/react';
import TextInput from './TextInput';
import PasswordInput, { IFormValues } from '../PasswordInput';
import { BrandLogo } from '../BrandLogo';
import { isTwoFactorRequiredError } from '../../utils/apiError';
import { getLockedUntil, isTwoFactorRequiredError } from '../../utils/apiError';

// Only app-internal paths are allowed as a post-login destination, so a crafted
// ?redirect= can never send the user to another origin.
Expand All @@ -19,12 +18,6 @@ const getSafeRedirect = (raw: string | null): string | null => {
return isInternalPath && !isExternalUrl ? raw : null;
};

const getLockedUntil = (error: unknown): string | undefined => {
if (!axios.isAxiosError(error)) return undefined;
const data = error.response?.data as { code?: string; lockedUntil?: string } | undefined;
return data?.code === 'ACCOUNT_LOCKED' ? data.lockedUntil : undefined;
};

interface LoginBranding {
logoUrl: string | null;
styles?: CSSProperties;
Expand Down
48 changes: 48 additions & 0 deletions src/components/two-factor/ForcedTwoFactorSetupLayout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { ReactNode } from 'react';
import { ShieldWarningIcon } from '@phosphor-icons/react';
import { T, text, card } from '../../sub-account/tokens';

interface ForcedTwoFactorSetupLayoutProps {
reason: string;
children: ReactNode;
}

export const ForcedTwoFactorSetupLayout = ({ reason, children }: ForcedTwoFactorSetupLayoutProps) => (
<div
style={{
minHeight: '100vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: T.gray5,
padding: 24,
}}
>
<div style={{ ...card, borderRadius: 16, padding: 32, width: '100%', maxWidth: 440 }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<div
style={{
width: 40,
height: 40,
borderRadius: 10,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: 'rgba(239,68,68,0.1)',
color: T.red,
}}
>
<ShieldWarningIcon size={20} weight="fill" />
</div>
<p style={{ ...text.heading, margin: 0 }}>Set up two-factor authentication</p>
<p style={{ fontSize: 13, color: T.gray60, margin: 0 }}>
{reason} You must set it up again before you can continue.
</p>
</div>

{children}
</div>
</div>
</div>
);
22 changes: 22 additions & 0 deletions src/management/components/ForcedTwoFactorSetup.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { TwoFactorSetupForm } from '../../components/two-factor/TwoFactorSetupForm';
import { ForcedTwoFactorSetupLayout } from '../../components/two-factor/ForcedTwoFactorSetupLayout';
import { useManagement } from '../context/useManagement';
import { managementTwoFactorService } from '../services/management-two-factor.service';
import { TWO_FACTOR_SETUP_LABELS, twoFactorErrorMessage } from './twoFactorCopy';

export const ForcedTwoFactorSetup = () => {
const { clearTwoFactorSetupRequired, logOut } = useManagement();

return (
<ForcedTwoFactorSetupLayout reason="The account owner reset two-factor authentication on this account.">
<TwoFactorSetupForm
labels={{ ...TWO_FACTOR_SETUP_LABELS, cancel: 'Log out' }}
getSetup={managementTwoFactorService.getSetup}
enable={managementTwoFactorService.enable}
errorMessage={twoFactorErrorMessage}
onComplete={clearTwoFactorSetupRequired}
onCancel={logOut}
/>
</ForcedTwoFactorSetupLayout>
);
};
12 changes: 11 additions & 1 deletion src/management/components/ManagementAuthRoute.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
import { Navigate, Outlet } from 'react-router-dom';
import { useManagement } from '../context/useManagement';
import { ManagementLayout } from './ManagementLayout';
import { ForcedTwoFactorSetup } from './ForcedTwoFactorSetup';
import Loader from '../../components/Loader';

export const ManagementAuthRoute = () => {
const { isAuthenticated } = useManagement();
const { isAuthenticated, isMeLoading, twoFactorSetupRequired } = useManagement();

if (!isAuthenticated) {
return <Navigate to="/management/login" replace />;
}

if (isMeLoading) {
return <Loader classNameContainer="flex min-h-screen items-center justify-center" />;
}

if (twoFactorSetupRequired) {
return <ForcedTwoFactorSetup />;
}

return (
<ManagementLayout>
<Outlet />
Expand Down
3 changes: 3 additions & 0 deletions src/management/components/ManagementMembersCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { memberEmailError, memberPasswordError } from '../../components/memberVa
import { PASSWORD_MIN_LENGTH } from '../../components/auth/passwordPolicy';
import notificationsService from '../../services/notifications.service';
import { apiErrorMessage } from '../../utils/apiError';
import { isReauthCancelled } from '../core/management-reauth';
import { SectionCard } from '../../sub-account/components/SettingsAtoms';
import { T, text, shadow } from '../../sub-account/tokens';
import { ConfirmActionModal } from './ConfirmActionModal';
Expand Down Expand Up @@ -242,6 +243,7 @@ export const ManagementMembersCard = () => {
closeCreate();
fetchMembers();
} catch (err) {
if (isReauthCancelled(err)) return;
notificationsService.error({ text: apiErrorMessage(err, 'Failed to create member') });
} finally {
setIsCreating(false);
Expand All @@ -262,6 +264,7 @@ export const ManagementMembersCard = () => {
}
fetchMembers();
} catch (err) {
if (isReauthCancelled(err)) return;
notificationsService.error({ text: apiErrorMessage(err, 'Failed to update the member') });
}
};
Expand Down
117 changes: 117 additions & 0 deletions src/management/components/ReauthDialog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { FormEvent, useEffect, useRef, useState } from 'react';
import dayjs from 'dayjs';
import Modal from '../../components/Modal';
import Button from '../../components/Button';
import Input from '../../components/Input';
import { TwoFactorCodeInput, TWO_FACTOR_CODE_LENGTH } from '../../components/two-factor/TwoFactorCodeInput';
import { apiErrorMessage, getLockedUntil, hasApiErrorStatus, isTwoFactorRequiredError } from '../../utils/apiError';
import { setReauthHandler } from '../core/management-reauth';
import { managementAuthService } from '../services/management-auth.service';
import { managementTwoFactorService } from '../services/management-two-factor.service';
import { text, form } from '../../sub-account/tokens';

const errorMessage = (err: unknown): string => {
if (isTwoFactorRequiredError(err)) return 'Enter the code from your authenticator app.';
const lockedUntil = getLockedUntil(err);
if (lockedUntil) return `Too many failed attempts. Try again at ${dayjs(lockedUntil).format('HH:mm')}.`;
if (hasApiErrorStatus(err, 403)) return 'Incorrect password or code.';
if (hasApiErrorStatus(err, 400)) return apiErrorMessage(err, 'Check your password and code.');
return 'Something went wrong. Please try again.';
};

export const ReauthDialog = () => {
const [isOpen, setIsOpen] = useState(false);
const [needsCode, setNeedsCode] = useState(false);
const [password, setPassword] = useState('');
const [code, setCode] = useState('');
const [error, setError] = useState<string>();
const [isSubmitting, setIsSubmitting] = useState(false);
const resolveRef = useRef<((confirmed: boolean) => void) | null>(null);

useEffect(() => {
setReauthHandler(
() =>
new Promise<boolean>((resolve) => {
resolveRef.current = resolve;
setPassword('');
setCode('');
setError(undefined);
setNeedsCode(false);
setIsOpen(true);
managementTwoFactorService
.getStatus()
.then((status) => setNeedsCode((current) => current || status.enabled))
.catch(() => undefined);
}),
);
return () => setReauthHandler(null);
}, []);

const finish = (confirmed: boolean) => {
setIsOpen(false);
resolveRef.current?.(confirmed);
resolveRef.current = null;
};

const handleSubmit = async (event?: FormEvent) => {
event?.preventDefault();
if (!canSubmit) return;
setIsSubmitting(true);
setError(undefined);
try {
await managementAuthService.reauthenticate(password, code);
finish(true);
} catch (err) {
if (hasApiErrorStatus(err, 401)) {
finish(false);
return;
}
if (isTwoFactorRequiredError(err)) setNeedsCode(true);
setError(errorMessage(err));
} finally {
setIsSubmitting(false);
}
};

const canSubmit = !!password && (!needsCode || code.length === TWO_FACTOR_CODE_LENGTH) && !isSubmitting;

return (
<Modal isOpen={isOpen} onClose={() => !isSubmitting && finish(false)}>
<form onSubmit={handleSubmit} style={{ display: 'flex', flexDirection: 'column', gap: 20, paddingTop: 4 }}>
<div>
<p style={{ ...text.heading, margin: 0 }}>Confirm your password</p>
<p style={{ ...text.hint, margin: '4px 0 0' }}>
{needsCode
? 'For your security, enter your password and a code from your authenticator app to continue.'
: 'For your security, enter your password to continue.'}
</p>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
<label style={form.label}>Password</label>
<Input
value={password}
onChange={setPassword}
variant="password"
autofocus
accent={error && !needsCode ? 'error' : undefined}
message={needsCode ? undefined : error}
/>
</div>
{needsCode && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
<label style={form.label}>Verification code</label>
<TwoFactorCodeInput value={code} onChange={setCode} placeholder="000000" error={error} />
</div>
)}
<div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, paddingTop: 4 }}>
<Button variant="secondary" type="button" onClick={() => finish(false)} disabled={isSubmitting}>
Cancel
</Button>
<Button type="submit" disabled={!canSubmit} loading={isSubmitting}>
Confirm
</Button>
</div>
</form>
</Modal>
);
};
30 changes: 4 additions & 26 deletions src/management/components/TwoFactorCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,11 @@ import Input from '../../components/Input';
import { TwoFactorSetupForm } from '../../components/two-factor/TwoFactorSetupForm';
import { TwoFactorCodeInput, TWO_FACTOR_CODE_LENGTH } from '../../components/two-factor/TwoFactorCodeInput';
import notificationsService from '../../services/notifications.service';
import { apiErrorCode } from '../../utils/apiError';
import { TWO_FACTOR_SETUP_LABELS, twoFactorErrorMessage } from './twoFactorCopy';
import { managementTwoFactorService, TwoFactorStatus } from '../services/management-two-factor.service';
import { SectionCard } from '../../sub-account/components/SettingsAtoms';
import { T, text, form } from '../../sub-account/tokens';

const ERROR_MESSAGES: Record<string, string> = {
INVALID_PASSWORD: 'Incorrect password.',
TWO_FACTOR_INVALID_CODE: 'Invalid code. Check your authenticator app and try again.',
TWO_FACTOR_NO_PENDING_SETUP: 'The setup expired. Close this window and start again.',
TWO_FACTOR_ALREADY_ENABLED: 'Two-factor authentication is already enabled.',
TWO_FACTOR_NOT_ENABLED: 'Two-factor authentication is not enabled.',
};

const errorMessage = (err: unknown): string =>
ERROR_MESSAGES[apiErrorCode(err) ?? ''] ?? 'Something went wrong. Please try again.';

type CardState =
{ kind: 'loading' } | { kind: 'failed' } | { kind: 'ready'; status: TwoFactorStatus };

Expand Down Expand Up @@ -64,7 +53,7 @@ export const TwoFactorCard = () => {
setState({ kind: 'ready', status: { enabled: false } });
notificationsService.success({ text: 'Two-factor authentication disabled' });
} catch (err) {
setDisableError(errorMessage(err));
setDisableError(twoFactorErrorMessage(err));
} finally {
setIsDisabling(false);
}
Expand Down Expand Up @@ -115,21 +104,10 @@ export const TwoFactorCard = () => {
<p style={{ ...text.heading, margin: 0 }}>Set up two-factor authentication</p>
{isSetupOpen && (
<TwoFactorSetupForm
labels={{
scanInstructions:
'Scan this QR code with your authenticator app, then enter the 6-digit code it shows.',
qrCodeAlt: 'Two-factor authentication QR code',
manualEntry: "Can't scan it? Enter this key manually:",
codeLabel: 'Verification code',
codePlaceholder: '000000',
loading: 'Loading…',
loadFailed: "Couldn't start the setup. Please try again.",
cancel: 'Cancel',
confirm: 'Confirm',
}}
labels={TWO_FACTOR_SETUP_LABELS}
getSetup={managementTwoFactorService.getSetup}
enable={managementTwoFactorService.enable}
errorMessage={errorMessage}
errorMessage={twoFactorErrorMessage}
onComplete={handleEnabled}
onCancel={() => setIsSetupOpen(false)}
/>
Expand Down
25 changes: 25 additions & 0 deletions src/management/components/twoFactorCopy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import type { TwoFactorSetupFormLabels } from '../../components/two-factor/TwoFactorSetupForm';
import { apiErrorCode } from '../../utils/apiError';

const ERROR_MESSAGES: Record<string, string> = {
INVALID_PASSWORD: 'Incorrect password.',
TWO_FACTOR_INVALID_CODE: 'Invalid code. Check your authenticator app and try again.',
TWO_FACTOR_NO_PENDING_SETUP: 'The setup expired. Close this window and start again.',
TWO_FACTOR_ALREADY_ENABLED: 'Two-factor authentication is already enabled.',
TWO_FACTOR_NOT_ENABLED: 'Two-factor authentication is not enabled.',
};

export const twoFactorErrorMessage = (err: unknown): string =>
ERROR_MESSAGES[apiErrorCode(err) ?? ''] ?? 'Something went wrong. Please try again.';

export const TWO_FACTOR_SETUP_LABELS: TwoFactorSetupFormLabels = {
scanInstructions: 'Scan this QR code with your authenticator app, then enter the 6-digit code it shows.',
qrCodeAlt: 'Two-factor authentication QR code',
manualEntry: "Can't scan it? Enter this key manually:",
codeLabel: 'Verification code',
codePlaceholder: '000000',
loading: 'Loading…',
loadFailed: "Couldn't start the setup. Please try again.",
cancel: 'Cancel',
confirm: 'Confirm',
};
Loading
Loading