From 91f86c075c7c92abf349966b8d1fda76c3c1ac8e Mon Sep 17 00:00:00 2001 From: jzunigax2 <125698953+jzunigax2@users.noreply.github.com> Date: Fri, 30 Oct 2026 17:48:42 +0100 Subject: [PATCH 1/3] feat: implement reauthentication flow in management context - Added ReauthDialog component for handling user reauthentication when required by the API. - Integrated reauthentication logic into managementAxios to prompt users for credentials upon receiving a REAUTH_REQUIRED error. - Updated management context to include ReauthDialog, ensuring it is rendered alongside other components. - Enhanced managementAuthService with reauthenticate method to facilitate password and two-factor code submission. - Added tests to verify reauthentication behavior and ensure proper handling of API responses. --- .../components/ManagementMembersCard.tsx | 3 + src/management/components/ReauthDialog.tsx | 124 ++++++++++++++++++ src/management/context/managementContext.tsx | 8 +- src/management/core/management-axios.test.ts | 96 +++++++++++++- src/management/core/management-axios.ts | 20 ++- src/management/core/management-reauth.ts | 31 +++++ .../services/management-auth.service.test.ts | 35 +++++ .../services/management-auth.service.ts | 9 ++ src/utils/apiError.ts | 3 + 9 files changed, 325 insertions(+), 4 deletions(-) create mode 100644 src/management/components/ReauthDialog.tsx create mode 100644 src/management/core/management-reauth.ts diff --git a/src/management/components/ManagementMembersCard.tsx b/src/management/components/ManagementMembersCard.tsx index 44f05569..596c0547 100644 --- a/src/management/components/ManagementMembersCard.tsx +++ b/src/management/components/ManagementMembersCard.tsx @@ -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'; @@ -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); @@ -262,6 +264,7 @@ export const ManagementMembersCard = () => { } fetchMembers(); } catch (err) { + if (isReauthCancelled(err)) return; notificationsService.error({ text: apiErrorMessage(err, 'Failed to update the member') }); } }; diff --git a/src/management/components/ReauthDialog.tsx b/src/management/components/ReauthDialog.tsx new file mode 100644 index 00000000..cadd895e --- /dev/null +++ b/src/management/components/ReauthDialog.tsx @@ -0,0 +1,124 @@ +import { FormEvent, useEffect, useRef, useState } from 'react'; +import axios from 'axios'; +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, 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 getLockedUntil = (err: unknown): string | undefined => { + if (!axios.isAxiosError(err)) return undefined; + const data = err.response?.data as { code?: string; lockedUntil?: string } | undefined; + return data?.code === 'ACCOUNT_LOCKED' ? data.lockedUntil : undefined; +}; + +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(); + const [isSubmitting, setIsSubmitting] = useState(false); + const resolveRef = useRef<((confirmed: boolean) => void) | null>(null); + + useEffect(() => { + setReauthHandler( + () => + new Promise((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, needsCode ? code : undefined); + 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 ( + !isSubmitting && finish(false)}> +
+
+

Confirm your password

+

+ {needsCode + ? 'For your security, enter your password and a code from your authenticator app to continue.' + : 'For your security, enter your password to continue.'} +

+
+
+ + +
+ {needsCode && ( +
+ + +
+ )} +
+ + +
+
+
+ ); +}; diff --git a/src/management/context/managementContext.tsx b/src/management/context/managementContext.tsx index b334a718..65c8aab3 100644 --- a/src/management/context/managementContext.tsx +++ b/src/management/context/managementContext.tsx @@ -2,6 +2,7 @@ import { useState, ReactNode, useMemo, useEffect } from 'react'; import { managementAuthService } from '../services/management-auth.service'; import { managementService, ManagementMe } from '../services/management.service'; import { ManagementContext } from './useManagement'; +import { ReauthDialog } from '../components/ReauthDialog'; export const ManagementProvider = ({ children }: { children: ReactNode }) => { const [isAuthenticated, setIsAuthenticated] = useState( @@ -34,5 +35,10 @@ export const ManagementProvider = ({ children }: { children: ReactNode }) => { [isAuthenticated, isOwner, me] ); - return {children}; + return ( + + {children} + + + ); }; diff --git a/src/management/core/management-axios.test.ts b/src/management/core/management-axios.test.ts index 3bc24f48..6a9dced2 100644 --- a/src/management/core/management-axios.test.ts +++ b/src/management/core/management-axios.test.ts @@ -1,8 +1,102 @@ -import { describe } from 'vitest'; +import { afterEach, describe, expect, test, vi } from 'vitest'; import managementAxios from './management-axios'; +import { isReauthCancelled, setReauthHandler } from './management-reauth'; import { managementAuthService } from '../services/management-auth.service'; import { describeScopedAxiosContract } from '../../testing/scoped-axios-contract'; +import { mockAdapter } from '../../testing/mock-axios-adapter'; +import { stubLocation } from '../../testing/stub-location'; + +const REAUTH_REQUIRED = { status: 403, data: { code: 'REAUTH_REQUIRED', message: 'Recent authentication required' } }; describe('managementAxios', () => { describeScopedAxiosContract(() => managementAxios, managementAuthService, '/management/login'); + + describe('when the API asks for recent authentication', () => { + afterEach(() => { + setReauthHandler(null); + localStorage.clear(); + }); + + test('when the user confirms, then the request is retried once with the fresh token', async () => { + stubLocation('/management/settings'); + managementAuthService.setToken('stale-token'); + setReauthHandler(async () => { + managementAuthService.setToken('fresh-token'); + return true; + }); + const seenTokens: unknown[] = []; + managementAxios.defaults.adapter = mockAdapter((config) => { + seenTokens.push((config.headers as Record)?.Authorization); + return seenTokens.length === 1 ? REAUTH_REQUIRED : { status: 204 }; + }); + + await expect(managementAxios.delete('/management/members/m1')).resolves.toMatchObject({ status: 204 }); + + expect(seenTokens).toEqual(['Bearer stale-token', 'Bearer fresh-token']); + }); + + test('when the user cancels, then the original error is rejected and marked as cancelled', async () => { + stubLocation('/management/settings'); + setReauthHandler(async () => false); + let calls = 0; + managementAxios.defaults.adapter = mockAdapter(() => { + calls++; + return REAUTH_REQUIRED; + }); + + const error = await managementAxios.delete('/management/members/m1').catch((err) => err); + + expect(error.response.status).toBe(403); + expect(isReauthCancelled(error)).toBe(true); + expect(calls).toBe(1); + }); + + test('when the retry is rejected again, then it does not prompt a second time', async () => { + stubLocation('/management/settings'); + const handler = vi.fn(async () => true); + setReauthHandler(handler); + let calls = 0; + managementAxios.defaults.adapter = mockAdapter(() => { + calls++; + return REAUTH_REQUIRED; + }); + + const error = await managementAxios.post('/management/members', {}).catch((err) => err); + + expect(error.response.status).toBe(403); + expect(isReauthCancelled(error)).toBe(false); + expect(handler).toHaveBeenCalledTimes(1); + expect(calls).toBe(2); + }); + + test('when several requests need it at once, then the user is prompted only once', async () => { + stubLocation('/management/settings'); + const handler = vi.fn(async () => true); + setReauthHandler(handler); + const seen = new Set(); + managementAxios.defaults.adapter = mockAdapter((config) => { + const first = !seen.has(config.url!); + seen.add(config.url!); + return first ? REAUTH_REQUIRED : { status: 204 }; + }); + + await Promise.all([ + managementAxios.delete('/management/members/m1'), + managementAxios.delete('/management/members/m2'), + ]); + + expect(handler).toHaveBeenCalledTimes(1); + }); + + test('when a 403 has another code, then no prompt is shown', async () => { + stubLocation('/management/settings'); + const handler = vi.fn(async () => true); + setReauthHandler(handler); + managementAxios.defaults.adapter = mockAdapter(() => ({ status: 403, data: { message: 'Forbidden' } })); + + await expect(managementAxios.delete('/management/members/m1')).rejects.toMatchObject({ isAxiosError: true }); + + expect(handler).not.toHaveBeenCalled(); + }); + }); }); diff --git a/src/management/core/management-axios.ts b/src/management/core/management-axios.ts index d79806c6..2b95797e 100644 --- a/src/management/core/management-axios.ts +++ b/src/management/core/management-axios.ts @@ -1,6 +1,10 @@ -import axios from 'axios'; +import axios, { InternalAxiosRequestConfig } from 'axios'; import { managementAuthService } from '../services/management-auth.service'; import notificationsService from '../../services/notifications.service'; +import { isReauthRequiredError } from '../../utils/apiError'; +import { markReauthCancelled, requestReauth } from './management-reauth'; + +type RetriableConfig = InternalAxiosRequestConfig & { _reauthRetried?: boolean }; const managementAxios = axios.create({ baseURL: import.meta.env.VITE_OBJECT_STORAGE_API_URL, @@ -16,12 +20,24 @@ managementAxios.interceptors.request.use((config) => { managementAxios.interceptors.response.use( (response) => response, - (error) => { + async (error) => { if (error.response?.status === 401 && !window.location.pathname.endsWith('/login')) { managementAuthService.logOut(); notificationsService.error({ text: 'Session expired. Please log in again.' }); window.location.href = '/management/login'; } + + const config = error.config as RetriableConfig | undefined; + if (isReauthRequiredError(error) && config && !config._reauthRetried) { + const confirmed = await requestReauth(); + if (!confirmed) { + markReauthCancelled(error); + throw error; + } + config._reauthRetried = true; + return managementAxios(config); + } + return Promise.reject(error); }, ); diff --git a/src/management/core/management-reauth.ts b/src/management/core/management-reauth.ts new file mode 100644 index 00000000..3bd72732 --- /dev/null +++ b/src/management/core/management-reauth.ts @@ -0,0 +1,31 @@ +/** + * Bridge between the management axios client and the "Confirm your password" dialog. + * The dialog registers a handler on mount; the response interceptor calls requestReauth() + * when the API answers 403 REAUTH_REQUIRED. Concurrent callers share the same prompt. + */ +type ReauthHandler = () => Promise; + +let handler: ReauthHandler | null = null; +let pending: Promise | null = null; + +export function setReauthHandler(next: ReauthHandler | null): void { + handler = next; +} + +export function requestReauth(): Promise { + if (!handler) return Promise.resolve(false); + pending ??= handler().finally(() => { + pending = null; + }); + return pending; +} + +const CANCELLED = Symbol('reauthCancelled'); + +export function markReauthCancelled(err: object): void { + (err as Record)[CANCELLED] = true; +} + +export function isReauthCancelled(err: unknown): boolean { + return typeof err === 'object' && err !== null && (err as Record)[CANCELLED] === true; +} diff --git a/src/management/services/management-auth.service.test.ts b/src/management/services/management-auth.service.test.ts index 429b6913..357c139a 100644 --- a/src/management/services/management-auth.service.test.ts +++ b/src/management/services/management-auth.service.test.ts @@ -38,6 +38,41 @@ describe('managementAuthService', () => { expect(managementAuthService.getToken()).toBeNull(); }); + test('when reauthenticate succeeds, then it posts the password and code and stores the returned token', async () => { + let seenConfig: { url?: string; method?: string; data?: string } | undefined; + managementAxios.defaults.adapter = mockAdapter((config) => { + seenConfig = config; + return { status: 200, data: { token: 'reauth-jwt' } }; + }); + + await managementAuthService.reauthenticate('secret', '123456'); + + expect(seenConfig?.method).toBe('post'); + expect(seenConfig?.url).toBe('/management/me/reauthenticate'); + expect(JSON.parse(seenConfig?.data ?? '{}')).toEqual({ password: 'secret', code: '123456' }); + expect(managementAuthService.getToken()).toBe('reauth-jwt'); + }); + + test('when reauthenticate is called without a code, then the code is omitted', async () => { + let seenData: string | undefined; + managementAxios.defaults.adapter = mockAdapter((config) => { + seenData = config.data; + return { status: 200, data: { token: 't' } }; + }); + + await managementAuthService.reauthenticate('secret'); + + expect(JSON.parse(seenData ?? '{}')).toEqual({ password: 'secret' }); + }); + + test('when reauthenticate is rejected, then the stored token is kept', async () => { + managementAuthService.setToken('current-jwt'); + managementAxios.defaults.adapter = mockAdapter(() => ({ status: 403, data: { message: 'Invalid credentials' } })); + + await expect(managementAuthService.reauthenticate('wrong')).rejects.toMatchObject({ isAxiosError: true }); + expect(managementAuthService.getToken()).toBe('current-jwt'); + }); + test('when logOut is called, then it clears the stored token', async () => { managementAxios.defaults.adapter = mockAdapter(() => ({ status: 200, data: { token: 'management-jwt' } })); await managementAuthService.logIn('admin@internxt.com', 'secret'); diff --git a/src/management/services/management-auth.service.ts b/src/management/services/management-auth.service.ts index ff5cf364..4709985f 100644 --- a/src/management/services/management-auth.service.ts +++ b/src/management/services/management-auth.service.ts @@ -19,12 +19,21 @@ async function logIn(email: string, password: string, code?: string): Promise { + const response = await managementAxios.post<{ token: string }>('/management/me/reauthenticate', { + password, + code: code || undefined, + }); + setToken(response.data.token); +} + function logOut(): void { removeToken(); } export const managementAuthService = { logIn, + reauthenticate, logOut, getToken, setToken, diff --git a/src/utils/apiError.ts b/src/utils/apiError.ts index f44e929c..ea709c38 100644 --- a/src/utils/apiError.ts +++ b/src/utils/apiError.ts @@ -16,3 +16,6 @@ export const apiErrorCode = (err: unknown): string | undefined => { export const isTwoFactorRequiredError = (err: unknown): boolean => axios.isAxiosError(err) && err.response?.status === 403 && err.response?.data?.message === '2FA_REQUIRED'; + +export const isReauthRequiredError = (err: unknown): boolean => + axios.isAxiosError(err) && err.response?.status === 403 && err.response?.data?.code === 'REAUTH_REQUIRED'; From 0a4c405119d5274f1bf8162d5320c2b9b36f70b0 Mon Sep 17 00:00:00 2001 From: jzunigax2 <125698953+jzunigax2@users.noreply.github.com> Date: Fri, 30 Oct 2026 18:19:46 +0100 Subject: [PATCH 2/3] feat: implement forced two-factor authentication setup - Added ForcedTwoFactorSetup component to prompt users for two-factor authentication setup when required. - Updated ManagementAuthRoute to render ForcedTwoFactorSetup based on twoFactorSetupRequired state. - Introduced twoFactorErrorMessage utility for consistent error handling across two-factor authentication components. - Modified management context to manage twoFactorSetupRequired state and clear it upon completion. - Enhanced managementAuthService to return twoFactorSetupRequired flag during login. - Updated tests to verify the new two-factor authentication flow and its integration. --- .../components/ForcedTwoFactorSetup.tsx | 69 +++++++++++++++++++ .../components/ManagementAuthRoute.tsx | 7 +- src/management/components/TwoFactorCard.tsx | 17 +---- .../components/twoFactorErrorMessage.ts | 12 ++++ src/management/context/managementContext.tsx | 16 +++-- src/management/context/useManagement.ts | 2 + .../services/management-auth.service.test.ts | 19 +++++ .../services/management-auth.service.ts | 8 ++- src/management/services/management.service.ts | 1 + 9 files changed, 130 insertions(+), 21 deletions(-) create mode 100644 src/management/components/ForcedTwoFactorSetup.tsx create mode 100644 src/management/components/twoFactorErrorMessage.ts diff --git a/src/management/components/ForcedTwoFactorSetup.tsx b/src/management/components/ForcedTwoFactorSetup.tsx new file mode 100644 index 00000000..72c17f3e --- /dev/null +++ b/src/management/components/ForcedTwoFactorSetup.tsx @@ -0,0 +1,69 @@ +import { ShieldWarningIcon } from '@phosphor-icons/react'; +import { TwoFactorSetupForm } from '../../components/two-factor/TwoFactorSetupForm'; +import { useManagement } from '../context/useManagement'; +import { managementTwoFactorService } from '../services/management-two-factor.service'; +import { twoFactorErrorMessage } from './twoFactorErrorMessage'; +import { T, text, card } from '../../sub-account/tokens'; + +export const ForcedTwoFactorSetup = () => { + const { clearTwoFactorSetupRequired, logOut } = useManagement(); + + return ( +
+
+
+
+
+ +
+

Set up two-factor authentication

+

+ The account owner reset two-factor authentication on this account. You must set it up again before you + can continue. +

+
+ + {/* enable() stores the token from the response; the server clears the flag at the same time. */} + +
+
+
+ ); +}; diff --git a/src/management/components/ManagementAuthRoute.tsx b/src/management/components/ManagementAuthRoute.tsx index db5220ee..1c2e2305 100644 --- a/src/management/components/ManagementAuthRoute.tsx +++ b/src/management/components/ManagementAuthRoute.tsx @@ -1,14 +1,19 @@ import { Navigate, Outlet } from 'react-router-dom'; import { useManagement } from '../context/useManagement'; import { ManagementLayout } from './ManagementLayout'; +import { ForcedTwoFactorSetup } from './ForcedTwoFactorSetup'; export const ManagementAuthRoute = () => { - const { isAuthenticated } = useManagement(); + const { isAuthenticated, twoFactorSetupRequired } = useManagement(); if (!isAuthenticated) { return ; } + if (twoFactorSetupRequired) { + return ; + } + return ( diff --git a/src/management/components/TwoFactorCard.tsx b/src/management/components/TwoFactorCard.tsx index ebef2745..bfea4049 100644 --- a/src/management/components/TwoFactorCard.tsx +++ b/src/management/components/TwoFactorCard.tsx @@ -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 { twoFactorErrorMessage } from './twoFactorErrorMessage'; 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 = { - 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 }; @@ -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); } @@ -129,7 +118,7 @@ export const TwoFactorCard = () => { }} getSetup={managementTwoFactorService.getSetup} enable={managementTwoFactorService.enable} - errorMessage={errorMessage} + errorMessage={twoFactorErrorMessage} onComplete={handleEnabled} onCancel={() => setIsSetupOpen(false)} /> diff --git a/src/management/components/twoFactorErrorMessage.ts b/src/management/components/twoFactorErrorMessage.ts new file mode 100644 index 00000000..65b4cb1b --- /dev/null +++ b/src/management/components/twoFactorErrorMessage.ts @@ -0,0 +1,12 @@ +import { apiErrorCode } from '../../utils/apiError'; + +const ERROR_MESSAGES: Record = { + 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.'; diff --git a/src/management/context/managementContext.tsx b/src/management/context/managementContext.tsx index 65c8aab3..849023f9 100644 --- a/src/management/context/managementContext.tsx +++ b/src/management/context/managementContext.tsx @@ -9,30 +9,38 @@ export const ManagementProvider = ({ children }: { children: ReactNode }) => { () => !!managementAuthService.getToken() ); const [me, setMe] = useState(null); + const [twoFactorSetupRequired, setTwoFactorSetupRequired] = useState(false); const isOwner = isAuthenticated && me?.role === 'owner'; useEffect(() => { if (!isAuthenticated) return; managementService .getMe() - .then(setMe) + .then((info) => { + setMe(info); + setTwoFactorSetupRequired(!!info.twoFactorSetupRequired); + }) .catch(() => setMe(null)); }, [isAuthenticated]); const logIn = async (email: string, password: string, code?: string) => { - await managementAuthService.logIn(email, password, code); + const { twoFactorSetupRequired } = await managementAuthService.logIn(email, password, code); setIsAuthenticated(true); + setTwoFactorSetupRequired(twoFactorSetupRequired); }; const logOut = () => { managementAuthService.logOut(); setIsAuthenticated(false); setMe(null); + setTwoFactorSetupRequired(false); }; + const clearTwoFactorSetupRequired = () => setTwoFactorSetupRequired(false); + const value = useMemo( - () => ({ isAuthenticated, isOwner, me, logIn, logOut }), - [isAuthenticated, isOwner, me] + () => ({ isAuthenticated, isOwner, me, twoFactorSetupRequired, clearTwoFactorSetupRequired, logIn, logOut }), + [isAuthenticated, isOwner, me, twoFactorSetupRequired] ); return ( diff --git a/src/management/context/useManagement.ts b/src/management/context/useManagement.ts index 06737fe1..95e18acd 100644 --- a/src/management/context/useManagement.ts +++ b/src/management/context/useManagement.ts @@ -5,6 +5,8 @@ export interface ManagementContextType { isAuthenticated: boolean; isOwner: boolean; me: ManagementMe | null; + twoFactorSetupRequired: boolean; + clearTwoFactorSetupRequired: () => void; logIn: (email: string, password: string, code?: string) => Promise; logOut: () => void; } diff --git a/src/management/services/management-auth.service.test.ts b/src/management/services/management-auth.service.test.ts index 357c139a..d0966817 100644 --- a/src/management/services/management-auth.service.test.ts +++ b/src/management/services/management-auth.service.test.ts @@ -29,6 +29,25 @@ describe('managementAuthService', () => { expect(managementAuthService.getToken()).toBe('management-jwt'); }); + test('when logIn returns twoFactorSetupRequired, then it passes the flag on', async () => { + managementAxios.defaults.adapter = mockAdapter(() => ({ + status: 200, + data: { token: 'management-jwt', twoFactorSetupRequired: true }, + })); + + await expect(managementAuthService.logIn('admin@internxt.com', 'secret')).resolves.toEqual({ + twoFactorSetupRequired: true, + }); + }); + + test('when the login response has no twoFactorSetupRequired, then the flag is false', async () => { + managementAxios.defaults.adapter = mockAdapter(() => ({ status: 200, data: { token: 'management-jwt' } })); + + await expect(managementAuthService.logIn('admin@internxt.com', 'secret')).resolves.toEqual({ + twoFactorSetupRequired: false, + }); + }); + test('when the backend rejects the credentials, then logIn rejects and stores nothing', async () => { managementAxios.defaults.adapter = mockAdapter(() => ({ status: 401 })); diff --git a/src/management/services/management-auth.service.ts b/src/management/services/management-auth.service.ts index 4709985f..ab565327 100644 --- a/src/management/services/management-auth.service.ts +++ b/src/management/services/management-auth.service.ts @@ -14,9 +14,13 @@ function removeToken(): void { localStorage.removeItem(MANAGEMENT_TOKEN_KEY); } -async function logIn(email: string, password: string, code?: string): Promise { - const response = await managementAxios.post<{ token: string }>('/management/login', { email, password, code }); +async function logIn(email: string, password: string, code?: string): Promise<{ twoFactorSetupRequired: boolean }> { + const response = await managementAxios.post<{ token: string; twoFactorSetupRequired?: boolean }>( + '/management/login', + { email, password, code }, + ); setToken(response.data.token); + return { twoFactorSetupRequired: !!response.data.twoFactorSetupRequired }; } async function reauthenticate(password: string, code?: string): Promise { diff --git a/src/management/services/management.service.ts b/src/management/services/management.service.ts index 2ede576a..3e0154f2 100644 --- a/src/management/services/management.service.ts +++ b/src/management/services/management.service.ts @@ -120,6 +120,7 @@ export interface ManagementMe { id: string; email: string; role: ManagementRole; + twoFactorSetupRequired?: boolean; } async function getMe(): Promise { From 8da83cf4328165d3473d4d9916bedeeb1d9bac5e Mon Sep 17 00:00:00 2001 From: jzunigax2 <125698953+jzunigax2@users.noreply.github.com> Date: Mon, 2 Nov 2026 12:38:04 +0100 Subject: [PATCH 3/3] feat: enhance two-factor authentication setup and error handling - Introduced ForcedTwoFactorSetupLayout component for consistent UI across forced two-factor authentication prompts. - Refactored ForcedTwoFactorSetup components in partners and wholesalers to utilize the new layout. - Updated two-factor error handling by consolidating error messages and labels into twoFactorCopy for better maintainability. - Improved API error handling in ReauthDialog and other components by integrating getLockedUntil utility. - Streamlined two-factor setup forms to use shared labels, enhancing consistency across the application. --- src/components/auth/LoginPageView.tsx | 9 +-- .../two-factor/ForcedTwoFactorSetupLayout.tsx | 48 +++++++++++++ .../components/ForcedTwoFactorSetup.tsx | 71 ++++--------------- .../components/ManagementAuthRoute.tsx | 7 +- src/management/components/ReauthDialog.tsx | 11 +-- src/management/components/TwoFactorCard.tsx | 15 +--- ...FactorErrorMessage.ts => twoFactorCopy.ts} | 13 ++++ src/management/context/managementContext.tsx | 17 ++++- src/management/context/useManagement.ts | 1 + src/management/core/management-axios.ts | 2 +- .../components/ForcedTwoFactorSetup.tsx | 44 ++---------- src/utils/apiError.ts | 5 +- .../WholesalersForcedTwoFactorSetup.tsx | 44 ++---------- 13 files changed, 112 insertions(+), 175 deletions(-) create mode 100644 src/components/two-factor/ForcedTwoFactorSetupLayout.tsx rename src/management/components/{twoFactorErrorMessage.ts => twoFactorCopy.ts} (52%) diff --git a/src/components/auth/LoginPageView.tsx b/src/components/auth/LoginPageView.tsx index d78248cf..08360416 100644 --- a/src/components/auth/LoginPageView.tsx +++ b/src/components/auth/LoginPageView.tsx @@ -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. @@ -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; diff --git a/src/components/two-factor/ForcedTwoFactorSetupLayout.tsx b/src/components/two-factor/ForcedTwoFactorSetupLayout.tsx new file mode 100644 index 00000000..b1743ef5 --- /dev/null +++ b/src/components/two-factor/ForcedTwoFactorSetupLayout.tsx @@ -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) => ( +
+
+
+
+
+ +
+

Set up two-factor authentication

+

+ {reason} You must set it up again before you can continue. +

+
+ + {children} +
+
+
+); diff --git a/src/management/components/ForcedTwoFactorSetup.tsx b/src/management/components/ForcedTwoFactorSetup.tsx index 72c17f3e..56b0fd72 100644 --- a/src/management/components/ForcedTwoFactorSetup.tsx +++ b/src/management/components/ForcedTwoFactorSetup.tsx @@ -1,69 +1,22 @@ -import { ShieldWarningIcon } from '@phosphor-icons/react'; 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 { twoFactorErrorMessage } from './twoFactorErrorMessage'; -import { T, text, card } from '../../sub-account/tokens'; +import { TWO_FACTOR_SETUP_LABELS, twoFactorErrorMessage } from './twoFactorCopy'; export const ForcedTwoFactorSetup = () => { const { clearTwoFactorSetupRequired, logOut } = useManagement(); return ( -
-
-
-
-
- -
-

Set up two-factor authentication

-

- The account owner reset two-factor authentication on this account. You must set it up again before you - can continue. -

-
- - {/* enable() stores the token from the response; the server clears the flag at the same time. */} - -
-
-
+ + + ); }; diff --git a/src/management/components/ManagementAuthRoute.tsx b/src/management/components/ManagementAuthRoute.tsx index 1c2e2305..4580e717 100644 --- a/src/management/components/ManagementAuthRoute.tsx +++ b/src/management/components/ManagementAuthRoute.tsx @@ -2,14 +2,19 @@ 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, twoFactorSetupRequired } = useManagement(); + const { isAuthenticated, isMeLoading, twoFactorSetupRequired } = useManagement(); if (!isAuthenticated) { return ; } + if (isMeLoading) { + return ; + } + if (twoFactorSetupRequired) { return ; } diff --git a/src/management/components/ReauthDialog.tsx b/src/management/components/ReauthDialog.tsx index cadd895e..da98740b 100644 --- a/src/management/components/ReauthDialog.tsx +++ b/src/management/components/ReauthDialog.tsx @@ -1,22 +1,15 @@ import { FormEvent, useEffect, useRef, useState } from 'react'; -import axios from 'axios'; 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, hasApiErrorStatus, isTwoFactorRequiredError } from '../../utils/apiError'; +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 getLockedUntil = (err: unknown): string | undefined => { - if (!axios.isAxiosError(err)) return undefined; - const data = err.response?.data as { code?: string; lockedUntil?: string } | undefined; - return data?.code === 'ACCOUNT_LOCKED' ? data.lockedUntil : undefined; -}; - const errorMessage = (err: unknown): string => { if (isTwoFactorRequiredError(err)) return 'Enter the code from your authenticator app.'; const lockedUntil = getLockedUntil(err); @@ -66,7 +59,7 @@ export const ReauthDialog = () => { setIsSubmitting(true); setError(undefined); try { - await managementAuthService.reauthenticate(password, needsCode ? code : undefined); + await managementAuthService.reauthenticate(password, code); finish(true); } catch (err) { if (hasApiErrorStatus(err, 401)) { diff --git a/src/management/components/TwoFactorCard.tsx b/src/management/components/TwoFactorCard.tsx index bfea4049..8857175a 100644 --- a/src/management/components/TwoFactorCard.tsx +++ b/src/management/components/TwoFactorCard.tsx @@ -5,7 +5,7 @@ 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 { twoFactorErrorMessage } from './twoFactorErrorMessage'; +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'; @@ -104,18 +104,7 @@ export const TwoFactorCard = () => {

Set up two-factor authentication

{isSetupOpen && ( = { @@ -10,3 +11,15 @@ const ERROR_MESSAGES: Record = { 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', +}; diff --git a/src/management/context/managementContext.tsx b/src/management/context/managementContext.tsx index 849023f9..c713789c 100644 --- a/src/management/context/managementContext.tsx +++ b/src/management/context/managementContext.tsx @@ -9,6 +9,7 @@ export const ManagementProvider = ({ children }: { children: ReactNode }) => { () => !!managementAuthService.getToken() ); const [me, setMe] = useState(null); + const [isMeLoading, setIsMeLoading] = useState(isAuthenticated); const [twoFactorSetupRequired, setTwoFactorSetupRequired] = useState(false); const isOwner = isAuthenticated && me?.role === 'owner'; @@ -20,7 +21,8 @@ export const ManagementProvider = ({ children }: { children: ReactNode }) => { setMe(info); setTwoFactorSetupRequired(!!info.twoFactorSetupRequired); }) - .catch(() => setMe(null)); + .catch(() => setMe(null)) + .finally(() => setIsMeLoading(false)); }, [isAuthenticated]); const logIn = async (email: string, password: string, code?: string) => { @@ -39,8 +41,17 @@ export const ManagementProvider = ({ children }: { children: ReactNode }) => { const clearTwoFactorSetupRequired = () => setTwoFactorSetupRequired(false); const value = useMemo( - () => ({ isAuthenticated, isOwner, me, twoFactorSetupRequired, clearTwoFactorSetupRequired, logIn, logOut }), - [isAuthenticated, isOwner, me, twoFactorSetupRequired] + () => ({ + isAuthenticated, + isOwner, + me, + isMeLoading, + twoFactorSetupRequired, + clearTwoFactorSetupRequired, + logIn, + logOut, + }), + [isAuthenticated, isOwner, me, isMeLoading, twoFactorSetupRequired] ); return ( diff --git a/src/management/context/useManagement.ts b/src/management/context/useManagement.ts index 95e18acd..12685b3e 100644 --- a/src/management/context/useManagement.ts +++ b/src/management/context/useManagement.ts @@ -5,6 +5,7 @@ export interface ManagementContextType { isAuthenticated: boolean; isOwner: boolean; me: ManagementMe | null; + isMeLoading: boolean; twoFactorSetupRequired: boolean; clearTwoFactorSetupRequired: () => void; logIn: (email: string, password: string, code?: string) => Promise; diff --git a/src/management/core/management-axios.ts b/src/management/core/management-axios.ts index 2b95797e..b1ce0422 100644 --- a/src/management/core/management-axios.ts +++ b/src/management/core/management-axios.ts @@ -38,7 +38,7 @@ managementAxios.interceptors.response.use( return managementAxios(config); } - return Promise.reject(error); + throw error; }, ); diff --git a/src/partners/components/ForcedTwoFactorSetup.tsx b/src/partners/components/ForcedTwoFactorSetup.tsx index 6ab42fc5..04db6b86 100644 --- a/src/partners/components/ForcedTwoFactorSetup.tsx +++ b/src/partners/components/ForcedTwoFactorSetup.tsx @@ -1,49 +1,13 @@ -import { ShieldWarningIcon } from '@phosphor-icons/react'; import { usePartners } from '../context/usePartners'; import { TwoFactorSetupForm } from './TwoFactorSetupForm'; -import { T, text, card } from '../../sub-account/tokens'; +import { ForcedTwoFactorSetupLayout } from '../../components/two-factor/ForcedTwoFactorSetupLayout'; export const ForcedTwoFactorSetup = () => { const { clearTwoFactorSetupRequired } = usePartners(); return ( -
-
-
-
-
- -
-

Set up two-factor authentication

-

- Your administrator reset two-factor authentication on this account. You must set it up again before you - can continue. -

-
- - -
-
-
+ + + ); }; diff --git a/src/utils/apiError.ts b/src/utils/apiError.ts index ea709c38..a6cdc954 100644 --- a/src/utils/apiError.ts +++ b/src/utils/apiError.ts @@ -18,4 +18,7 @@ export const isTwoFactorRequiredError = (err: unknown): boolean => axios.isAxiosError(err) && err.response?.status === 403 && err.response?.data?.message === '2FA_REQUIRED'; export const isReauthRequiredError = (err: unknown): boolean => - axios.isAxiosError(err) && err.response?.status === 403 && err.response?.data?.code === 'REAUTH_REQUIRED'; + hasApiErrorStatus(err, 403) && apiErrorCode(err) === 'REAUTH_REQUIRED'; + +export const getLockedUntil = (err: unknown): string | undefined => + apiErrorCode(err) === 'ACCOUNT_LOCKED' && axios.isAxiosError(err) ? err.response?.data?.lockedUntil : undefined; diff --git a/src/wholesalers/components/WholesalersForcedTwoFactorSetup.tsx b/src/wholesalers/components/WholesalersForcedTwoFactorSetup.tsx index 5f7d024c..2b6139c7 100644 --- a/src/wholesalers/components/WholesalersForcedTwoFactorSetup.tsx +++ b/src/wholesalers/components/WholesalersForcedTwoFactorSetup.tsx @@ -1,49 +1,13 @@ -import { ShieldWarningIcon } from '@phosphor-icons/react'; import { useWholesalers } from '../context/useWholesalers'; import { WholesalersTwoFactorSetupForm } from './WholesalersTwoFactorSetupForm'; -import { T, text, card } from '../../sub-account/tokens'; +import { ForcedTwoFactorSetupLayout } from '../../components/two-factor/ForcedTwoFactorSetupLayout'; export const WholesalersForcedTwoFactorSetup = () => { const { clearTwoFactorSetupRequired } = useWholesalers(); return ( -
-
-
-
-
- -
-

Set up two-factor authentication

-

- Your administrator reset two-factor authentication on this account. You must set it up again before you - can continue. -

-
- - -
-
-
+ + + ); };