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 new file mode 100644 index 00000000..56b0fd72 --- /dev/null +++ b/src/management/components/ForcedTwoFactorSetup.tsx @@ -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 ( + + + + ); +}; diff --git a/src/management/components/ManagementAuthRoute.tsx b/src/management/components/ManagementAuthRoute.tsx index db5220ee..4580e717 100644 --- a/src/management/components/ManagementAuthRoute.tsx +++ b/src/management/components/ManagementAuthRoute.tsx @@ -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 ; } + if (isMeLoading) { + return ; + } + + if (twoFactorSetupRequired) { + return ; + } + return ( 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..da98740b --- /dev/null +++ b/src/management/components/ReauthDialog.tsx @@ -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(); + 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, 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 ( + !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/components/TwoFactorCard.tsx b/src/management/components/TwoFactorCard.tsx index ebef2745..8857175a 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 { 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 = { - 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); } @@ -115,21 +104,10 @@ export const TwoFactorCard = () => {

Set up two-factor authentication

{isSetupOpen && ( setIsSetupOpen(false)} /> diff --git a/src/management/components/twoFactorCopy.ts b/src/management/components/twoFactorCopy.ts new file mode 100644 index 00000000..28568b45 --- /dev/null +++ b/src/management/components/twoFactorCopy.ts @@ -0,0 +1,25 @@ +import type { TwoFactorSetupFormLabels } from '../../components/two-factor/TwoFactorSetupForm'; +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.'; + +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 b334a718..c713789c 100644 --- a/src/management/context/managementContext.tsx +++ b/src/management/context/managementContext.tsx @@ -2,37 +2,62 @@ 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( () => !!managementAuthService.getToken() ); const [me, setMe] = useState(null); + const [isMeLoading, setIsMeLoading] = useState(isAuthenticated); + const [twoFactorSetupRequired, setTwoFactorSetupRequired] = useState(false); const isOwner = isAuthenticated && me?.role === 'owner'; useEffect(() => { if (!isAuthenticated) return; managementService .getMe() - .then(setMe) - .catch(() => setMe(null)); + .then((info) => { + setMe(info); + setTwoFactorSetupRequired(!!info.twoFactorSetupRequired); + }) + .catch(() => setMe(null)) + .finally(() => setIsMeLoading(false)); }, [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, + isMeLoading, + twoFactorSetupRequired, + clearTwoFactorSetupRequired, + logIn, + logOut, + }), + [isAuthenticated, isOwner, me, isMeLoading, twoFactorSetupRequired] ); - return {children}; + return ( + + {children} + + + ); }; diff --git a/src/management/context/useManagement.ts b/src/management/context/useManagement.ts index 06737fe1..12685b3e 100644 --- a/src/management/context/useManagement.ts +++ b/src/management/context/useManagement.ts @@ -5,6 +5,9 @@ export interface ManagementContextType { isAuthenticated: boolean; isOwner: boolean; me: ManagementMe | null; + isMeLoading: boolean; + twoFactorSetupRequired: boolean; + clearTwoFactorSetupRequired: () => void; logIn: (email: string, password: string, code?: string) => Promise; logOut: () => void; } 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..b1ce0422 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,13 +20,25 @@ 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'; } - return Promise.reject(error); + + 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); + } + + throw 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..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 })); @@ -38,6 +57,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..ab565327 100644 --- a/src/management/services/management-auth.service.ts +++ b/src/management/services/management-auth.service.ts @@ -14,8 +14,20 @@ 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 { + const response = await managementAxios.post<{ token: string }>('/management/me/reauthenticate', { + password, + code: code || undefined, + }); setToken(response.data.token); } @@ -25,6 +37,7 @@ function logOut(): void { export const managementAuthService = { logIn, + reauthenticate, logOut, getToken, setToken, 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 { 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 f44e929c..a6cdc954 100644 --- a/src/utils/apiError.ts +++ b/src/utils/apiError.ts @@ -16,3 +16,9 @@ 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 => + 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. -

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