Skip to content
Open
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
4 changes: 4 additions & 0 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ import { WholesalersAuthRoute } from './wholesalers/components/WholesalersAuthRo
import { WholesalersPartnersPage } from './wholesalers/views/WholesalersPartnersPage';
import { WholesalersPartnerDetailPage } from './wholesalers/views/WholesalersPartnerDetailPage';
import { WholesalersSettingsPage } from './wholesalers/views/WholesalersSettingsPage';
import { WholesalersForgotPasswordPage } from './wholesalers/views/WholesalersForgotPasswordPage';
import { WholesalersResetPasswordPage } from './wholesalers/views/WholesalersResetPasswordPage';

const DEFAULT_LOGIN_PATH = '/subaccount/login';

Expand Down Expand Up @@ -103,6 +105,8 @@ export function App() {
{import.meta.env.VITE_ENABLE_WHOLESALER_PANEL === 'true' && (
<>
<Route path="/wholesalers/login" element={<WholesalersLoginPage />} />
<Route path="/wholesalers/forgot-password" element={<WholesalersForgotPasswordPage />} />
<Route path="/wholesalers/reset-password" element={<WholesalersResetPasswordPage />} />
<Route element={<WholesalersAuthRoute />}>
<Route path="/wholesalers" element={<Navigate to="/wholesalers/partners" />} />
<Route path="/wholesalers/partners" element={<WholesalersPartnersPage />} />
Expand Down
18 changes: 18 additions & 0 deletions src/utils/publicAuthPage.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { describe, expect, test } from 'vitest';
import { isPublicAuthPage } from './publicAuthPage';

describe('isPublicAuthPage', () => {
test.each(['/wholesalers/login', '/wholesalers/forgot-password', '/wholesalers/reset-password'])(
'when the path is %s, then it is a public auth page',
(pathname) => {
expect(isPublicAuthPage(pathname)).toBe(true);
},
);

test.each(['/wholesalers/partners', '/wholesalers/settings', '/wholesalers/reset-password/extra'])(
'when the path is %s, then it is not a public auth page',
(pathname) => {
expect(isPublicAuthPage(pathname)).toBe(false);
},
);
});
5 changes: 5 additions & 0 deletions src/utils/publicAuthPage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const PUBLIC_AUTH_PAGE_SUFFIXES = ['/login', '/forgot-password', '/reset-password'];

export function isPublicAuthPage(pathname: string): boolean {
return PUBLIC_AUTH_PAGE_SUFFIXES.some((suffix) => pathname.endsWith(suffix));
}
12 changes: 12 additions & 0 deletions src/wholesalers/console-branding.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export const wholesalersConsoleBranding = {
consoleTitle: 'Wholesalers Console',
rightHeadline: (
<>
Object Storage
<br />
Wholesalers
</>
),
rightDescription: 'Create partners, monitor their storage usage, and manage aggregated billing from one place.',
rightFeaturePills: ['Partner management', 'Usage monitoring', 'Aggregated billing'],
};
31 changes: 30 additions & 1 deletion src/wholesalers/core/wholesalers-axios.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,37 @@
import { describe } from 'vitest';
import { afterEach, describe, expect, test, vi } from 'vitest';
import wholesalersAxios from './wholesalers-axios';
import { wholesalersAuthService } from '../services/wholesalers-auth.service';
import notificationsService from '../../services/notifications.service';
import { describeScopedAxiosContract } from '../../testing/scoped-axios-contract';
import { mockAdapter } from '../../testing/mock-axios-adapter';
import { stubLocation } from '../../testing/stub-location';

describe('wholesalersAxios', () => {
describeScopedAxiosContract(() => wholesalersAxios, wholesalersAuthService, '/wholesalers/login');

describe('on the password recovery pages', () => {
const realLocation = window.location;

afterEach(() => {
Object.defineProperty(window, 'location', { value: realLocation, writable: true, configurable: true });
vi.restoreAllMocks();
});

test.each(['/wholesalers/forgot-password', '/wholesalers/reset-password'])(
'when a stale token gets a 401 on %s, then it does not log out, notify or redirect away',
async (pathname) => {
vi.spyOn(wholesalersAuthService, 'getToken').mockReturnValue('stale-token');
const logOutSpy = vi.spyOn(wholesalersAuthService, 'logOut').mockImplementation(() => {});
const notifySpy = vi.spyOn(notificationsService, 'error').mockImplementation(() => {});
stubLocation(pathname);
wholesalersAxios.defaults.adapter = mockAdapter(() => ({ status: 401 }));

await expect(wholesalersAxios.get('/wholesalers/me')).rejects.toMatchObject({ isAxiosError: true });

expect(logOutSpy).not.toHaveBeenCalled();
expect(notifySpy).not.toHaveBeenCalled();
expect(window.location.href).toBe('');
},
);
});
});
3 changes: 2 additions & 1 deletion src/wholesalers/core/wholesalers-axios.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import axios from 'axios';
import { wholesalersAuthService } from '../services/wholesalers-auth.service';
import notificationsService from '../../services/notifications.service';
import { isPublicAuthPage } from '../../utils/publicAuthPage';

const wholesalersAxios = axios.create({
baseURL: import.meta.env.VITE_OBJECT_STORAGE_API_URL,
Expand All @@ -17,7 +18,7 @@ wholesalersAxios.interceptors.request.use((config) => {
wholesalersAxios.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401 && !window.location.pathname.endsWith('/login')) {
if (error.response?.status === 401 && !isPublicAuthPage(window.location.pathname)) {
wholesalersAuthService.logOut();
notificationsService.error({ text: 'Session expired. Please log in again.' });
window.location.href = '/wholesalers/login';
Expand Down
57 changes: 57 additions & 0 deletions src/wholesalers/services/wholesalers-auth.service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,63 @@ describe('wholesalersAuthService', () => {
});
});

describe('requestPasswordReset', () => {
test('when requestPasswordReset is called, then it posts the email to the forgot-password endpoint', async () => {
let seenConfig: { url?: string; data?: string } | undefined;
wholesalersAxios.defaults.adapter = mockAdapter((config) => {
seenConfig = config;
return { status: 204 };
});

await wholesalersAuthService.requestPasswordReset('[email protected]');

expect(seenConfig?.url).toBe('/wholesalers/forgot-password');
expect(JSON.parse(seenConfig?.data ?? '{}')).toEqual({ email: '[email protected]' });
});

test('when the backend rejects the captcha, then it maps that into a CaptchaUnavailableError', async () => {
wholesalersAxios.defaults.adapter = mockAdapter(() => ({
status: 403,
data: { code: 'CAPTCHA_FAILED' },
}));

const error = await wholesalersAuthService.requestPasswordReset('[email protected]').catch((e) => e);

expect(error.name).toBe('CaptchaUnavailableError');
});

test('when the backend rejects for any other reason, then requestPasswordReset rethrows the error untouched', async () => {
wholesalersAxios.defaults.adapter = mockAdapter(() => ({ status: 429 }));

await expect(wholesalersAuthService.requestPasswordReset('[email protected]')).rejects.toMatchObject({
isAxiosError: true,
});
});
});

describe('resetPassword', () => {
test('when resetPassword is called, then it posts the reset token and the new password', async () => {
let seenConfig: { url?: string; data?: string } | undefined;
wholesalersAxios.defaults.adapter = mockAdapter((config) => {
seenConfig = config;
return { status: 204 };
});

await wholesalersAuthService.resetPassword('reset-token', 'new-secret');

expect(seenConfig?.url).toBe('/wholesalers/reset-password');
expect(JSON.parse(seenConfig?.data ?? '{}')).toEqual({ token: 'reset-token', newPassword: 'new-secret' });
});

test('when the reset token is invalid or expired, then resetPassword rethrows the 400', async () => {
wholesalersAxios.defaults.adapter = mockAdapter(() => ({ status: 400 }));

await expect(wholesalersAuthService.resetPassword('stale-token', 'new-secret')).rejects.toMatchObject({
response: { status: 400 },
});
});
});

describe('token management', () => {
test('when no one is logged in, then getToken returns null', () => {
expect(wholesalersAuthService.getToken()).toBeNull();
Expand Down
18 changes: 18 additions & 0 deletions src/wholesalers/services/wholesalers-auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import wholesalersAxios from '../core/wholesalers-axios';
import { CaptchaUnavailableError, captchaService } from '../../services/captcha.service';

const WHOLESALERS_TOKEN_KEY = 'wholesalersToken';

Expand All @@ -23,6 +24,21 @@ async function logIn(email: string, password: string, code?: string): Promise<{
return { twoFactorSetupRequired: !!response.data.twoFactorSetupRequired };
}

async function requestPasswordReset(email: string): Promise<void> {
const captchaHeaders = await captchaService.tryGetHeaders('ForgotPassword');

try {
await wholesalersAxios.post('/wholesalers/forgot-password', { email }, { headers: captchaHeaders });
} catch (err) {
if (captchaService.isCaptchaRejection(err)) throw new CaptchaUnavailableError();
throw err;
}
}

async function resetPassword(token: string, newPassword: string): Promise<void> {
await wholesalersAxios.post('/wholesalers/reset-password', { token, newPassword });
}

function logOut(): void {
removeToken();
}
Expand All @@ -48,6 +64,8 @@ function getRole(): 'wholesaler' | 'member' | null {
export const wholesalersAuthService = {
getRole,
logIn,
requestPasswordReset,
resetPassword,
setToken,
logOut,
getToken,
Expand Down
13 changes: 13 additions & 0 deletions src/wholesalers/views/WholesalersForgotPasswordPage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { ForgotPasswordView } from '../../components/auth/ForgotPasswordView';
import { wholesalersAuthService } from '../services/wholesalers-auth.service';
import { wholesalersConsoleBranding } from '../console-branding';

export const WholesalersForgotPasswordPage = () => {
return (
<ForgotPasswordView
{...wholesalersConsoleBranding}
loginPath="/wholesalers/login"
requestPasswordReset={wholesalersAuthService.requestPasswordReset}
/>
);
};
13 changes: 3 additions & 10 deletions src/wholesalers/views/WholesalersLoginPage.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,18 @@
import { LoginPageView } from '../../components/auth/LoginPageView';
import { useWholesalers } from '../context/useWholesalers';
import { wholesalersConsoleBranding } from '../console-branding';

export const WholesalersLoginPage = () => {
const { isAuthenticated, logIn } = useWholesalers();

return (
<LoginPageView
consoleTitle="Wholesalers Console"
rightHeadline={
<>
Object Storage
<br />
Wholesalers
</>
}
rightDescription="Create partners, monitor their storage usage, and manage aggregated billing from one place."
rightFeaturePills={['Partner management', 'Usage monitoring', 'Aggregated billing']}
{...wholesalersConsoleBranding}
isAuthenticated={isAuthenticated}
logIn={logIn}
supportsTwoFactor
redirectTo="/wholesalers/partners"
forgotPasswordPath="/wholesalers/forgot-password"
/>
);
};
22 changes: 22 additions & 0 deletions src/wholesalers/views/WholesalersResetPasswordPage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { ResetPasswordView } from '../../components/auth/ResetPasswordView';
import { wholesalersAuthService } from '../services/wholesalers-auth.service';
import { wholesalersConsoleBranding } from '../console-branding';
import { useWholesalers } from '../context/useWholesalers';

export const WholesalersResetPasswordPage = () => {
const { logOut } = useWholesalers();

const resetPassword = async (token: string, newPassword: string) => {
await wholesalersAuthService.resetPassword(token, newPassword);
logOut();
};

return (
<ResetPasswordView
{...wholesalersConsoleBranding}
loginPath="/wholesalers/login"
forgotPasswordPath="/wholesalers/forgot-password"
resetPassword={resetPassword}
/>
);
};
Loading