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
7 changes: 3 additions & 4 deletions frontend/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import FreighterBanner from './components/FreighterBanner';
import DemoBanner from './components/DemoBanner';
import NavBar from './components/NavBar';
import SkipToContent from './components/SkipToContent';
import RequireAuth from './components/RequireAuth';

export default function App() {
const [dark, setDark] = useDarkMode();
Expand All @@ -21,14 +22,12 @@ export default function App() {
<DemoBanner />
<NavBar dark={dark} onToggleDark={() => setDark((d) => !d)} />
<SkipToContent />
<DemoBanner/>
<NavBar dark={dark} onToggleDark={() => setDark(d => !d)} />
<FreighterBanner />
<main id="main-content" tabIndex={-1} style={{ outline: 'none' }}>
<Routes>
<Route path="/" element={<Landing />} />
<Route path="/patient" element={<PatientDashboard />} />
<Route path="/issuer" element={<IssuerDashboard />} />
<Route path="/patient" element={<RequireAuth><PatientDashboard /></RequireAuth>} />
<Route path="/issuer" element={<RequireAuth requiredRole="issuer"><IssuerDashboard /></RequireAuth>} />
<Route path="/verify" element={<VerifyPage />} />
<Route path="/admin" element={<AdminDashboard />} />
<Route path="/apply" element={<IssuerOnboarding />} />
Expand Down
20 changes: 20 additions & 0 deletions frontend/src/components/RequireAuth.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { useLocation, Navigate } from 'react-router-dom';
import { useAuth } from '../hooks/useFreighter';

/**
* Route guard component.
*
* @param {string} [requiredRole] - If set, user must also have this role.
*/
export default function RequireAuth({ children, requiredRole }) {
const { isConnected, role, hydrating } = useAuth();
const location = useLocation();

if (hydrating) return null;

if (!isConnected || (requiredRole && role !== requiredRole)) {
return <Navigate to="/" state={{ from: location.pathname }} replace />;
}

return children;
}
131 changes: 131 additions & 0 deletions frontend/src/components/RequireAuth.test.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import { render, screen } from '@testing-library/react';
import { MemoryRouter, Routes, Route } from 'react-router-dom';
import RequireAuth from './RequireAuth';

jest.mock('../hooks/useFreighter', () => ({ useAuth: jest.fn() }));
import { useAuth } from '../hooks/useFreighter';

const Protected = () => <div>protected</div>;
const Landing = () => <div>landing</div>;

function renderWithRouter(initialPath, authValue) {
useAuth.mockReturnValue(authValue);
return render(
<MemoryRouter initialEntries={[initialPath]}>
<Routes>
<Route path="/" element={<Landing />} />
<Route
path="/patient"
element={<RequireAuth><Protected /></RequireAuth>}
/>
<Route
path="/issuer"
element={<RequireAuth requiredRole="issuer"><Protected /></RequireAuth>}
/>
</Routes>
</MemoryRouter>
);
}

describe('RequireAuth', () => {
describe('while hydrating', () => {
it('renders nothing (no flash of protected content)', () => {
const { container } = renderWithRouter('/patient', {
isConnected: false, role: null, hydrating: true,
});
expect(container).toBeEmptyDOMElement();
});
});

describe('/patient — unauthenticated', () => {
it('redirects to / when not connected', () => {
renderWithRouter('/patient', { isConnected: false, role: null, hydrating: false });
expect(screen.getByText('landing')).toBeInTheDocument();
expect(screen.queryByText('protected')).not.toBeInTheDocument();
});
});

describe('/patient — authenticated (any role)', () => {
it('renders the protected page for a patient role', () => {
renderWithRouter('/patient', { isConnected: true, role: 'patient', hydrating: false });
expect(screen.getByText('protected')).toBeInTheDocument();
});

it('renders the protected page for an issuer role', () => {
renderWithRouter('/patient', { isConnected: true, role: 'issuer', hydrating: false });
expect(screen.getByText('protected')).toBeInTheDocument();
});
});

describe('/issuer — no issuer role', () => {
it('redirects to / when not connected', () => {
renderWithRouter('/issuer', { isConnected: false, role: null, hydrating: false });
expect(screen.getByText('landing')).toBeInTheDocument();
});

it('redirects to / when connected as patient', () => {
renderWithRouter('/issuer', { isConnected: true, role: 'patient', hydrating: false });
expect(screen.getByText('landing')).toBeInTheDocument();
expect(screen.queryByText('protected')).not.toBeInTheDocument();
});
});

describe('/issuer — with issuer role', () => {
it('renders the protected page', () => {
renderWithRouter('/issuer', { isConnected: true, role: 'issuer', hydrating: false });
expect(screen.getByText('protected')).toBeInTheDocument();
});
});

describe('redirect preserves intended destination', () => {
it('passes state.from when redirecting from /patient', () => {
let capturedState;
const LandingCapture = () => {
// Access location via useLocation inside a component
const { useLocation } = require('react-router-dom');
capturedState = useLocation().state;
return <div>landing</div>;
};
useAuth.mockReturnValue({ isConnected: false, role: null, hydrating: false });
render(
<MemoryRouter initialEntries={['/patient']}>
<Routes>
<Route path="/" element={<LandingCapture />} />
<Route path="/patient" element={<RequireAuth><Protected /></RequireAuth>} />
</Routes>
</MemoryRouter>
);
expect(capturedState).toEqual({ from: '/patient' });
});
});

describe('re-evaluation on auth change', () => {
it('redirects when isConnected changes to false after render', () => {
// Initial render: connected
const authValue = { isConnected: true, role: 'patient', hydrating: false };
useAuth.mockReturnValue(authValue);
const { rerender } = render(
<MemoryRouter initialEntries={['/patient']}>
<Routes>
<Route path="/" element={<Landing />} />
<Route path="/patient" element={<RequireAuth><Protected /></RequireAuth>} />
</Routes>
</MemoryRouter>
);
expect(screen.getByText('protected')).toBeInTheDocument();

// Simulate JWT expiry: isConnected becomes false
useAuth.mockReturnValue({ isConnected: false, role: null, hydrating: false });
rerender(
<MemoryRouter initialEntries={['/patient']}>
<Routes>
<Route path="/" element={<Landing />} />
<Route path="/patient" element={<RequireAuth><Protected /></RequireAuth>} />
</Routes>
</MemoryRouter>
);
expect(screen.getByText('landing')).toBeInTheDocument();
expect(screen.queryByText('protected')).not.toBeInTheDocument();
});
});
});
13 changes: 8 additions & 5 deletions frontend/src/hooks/useFreighter.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export function AuthProvider({ children }) {
const [role, setRole] = useState(null);
const [loading, setLoading] = useState(false);
const [connectionStep, setConnectionStep] = useState(CONNECTION_STEPS.IDLE);
const [hydrating, setHydrating] = useState(() => !!localStorage.getItem(STORAGE_KEY));
const [error, setError] = useState(null);
const [freighterInstalled, setFreighterInstalled] = useState(() => typeof window !== 'undefined' && !!window.freighter);
// Token lives only in memory — never written to localStorage
Expand Down Expand Up @@ -100,12 +101,13 @@ export function AuthProvider({ children }) {
if (!connected) {
setFreighterInstalled(false);
localStorage.removeItem(STORAGE_KEY);
return;
} else {
// Restore identity so UI shows as connected; token will be fetched on first apiFetch call
setPublicKey(savedKey);
setRole(savedRole);
}
// Restore identity so UI shows as connected; token will be fetched on first apiFetch call
setPublicKey(savedKey);
setRole(savedRole);
}).catch(() => localStorage.removeItem(STORAGE_KEY));
}).catch(() => localStorage.removeItem(STORAGE_KEY))
.finally(() => setHydrating(false));
}, []);

const apiFetch = useCallback(async (url, options = {}) => {
Expand Down Expand Up @@ -148,6 +150,7 @@ export function AuthProvider({ children }) {
isConnected: isConnectedState,
loading,
connectionStep,
hydrating,
error,
}}>
{children}
Expand Down
Loading