Merge pull request 'feat(client): add cookie-backed browser authentication' (#3) from fix/task-55-authenticated-eventsource-repair-2 into master
Reviewed-on: agent-codex/liqa#3
This commit is contained in:
commit
fe19fb9d56
26 files changed
+1225
-10
No files matched your search
@@ -0,0 +1,28 @@
|
||||
import '../../src/i18n';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect, fn, userEvent, within } from 'storybook/test';
|
||||
import { AuthStatusPage } from '../../src/pages/auth/AuthStatusPage';
|
||||
|
||||
const meta: Meta<typeof AuthStatusPage> = {
|
||||
title: 'Authentication/Session status',
|
||||
component: AuthStatusPage,
|
||||
parameters: { layout: 'fullscreen' },
|
||||
tags: ['autodocs'],
|
||||
args: { onRetry: fn() },
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof AuthStatusPage>;
|
||||
|
||||
export const Checking: Story = {};
|
||||
|
||||
export const SessionCheckFailure: Story = {
|
||||
args: { failed: true },
|
||||
play: async ({ canvasElement, args }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(canvas.getByRole('alert')).toHaveTextContent(
|
||||
"Couldn't check your session. Try again.",
|
||||
);
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Retry' }));
|
||||
await expect(args.onRetry).toHaveBeenCalledTimes(1);
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect } from 'storybook/test';
|
||||
import { auth } from '../../src/api/client';
|
||||
import { createRunEventSource } from '../../src/hooks/useRunNotifications';
|
||||
|
||||
function TransportExample() {
|
||||
return <p>Browser auth uses HttpOnly cookies for API and run-event requests.</p>;
|
||||
}
|
||||
|
||||
const meta: Meta<typeof TransportExample> = {
|
||||
title: 'Authentication/Cookie transport',
|
||||
component: TransportExample,
|
||||
tags: ['autodocs'],
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof TransportExample>;
|
||||
|
||||
export const CookieCredentials: Story = {
|
||||
play: async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const localStorageLength = localStorage.length;
|
||||
let requestInit: RequestInit | undefined;
|
||||
globalThis.fetch = async (_input, init) => {
|
||||
requestInit = init;
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
user: {
|
||||
id: 'synthetic-user-id',
|
||||
username: 'synthetic-operator',
|
||||
createdAt: '2026-01-01T00:00:00.000Z',
|
||||
updatedAt: '2026-01-01T00:00:00.000Z',
|
||||
},
|
||||
}),
|
||||
{ status: 200, headers: { 'Content-Type': 'application/json' } },
|
||||
);
|
||||
};
|
||||
try {
|
||||
const user = await auth.login('synthetic-operator', 'synthetic-password');
|
||||
await expect(requestInit?.credentials).toBe('include');
|
||||
await expect(user.username).toBe('synthetic-operator');
|
||||
await expect(new Headers(requestInit?.headers).has('Authorization')).toBe(false);
|
||||
await expect(localStorage.length).toBe(localStorageLength);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export const EventStreamIncludesCookieCredentials: Story = {
|
||||
play: async () => {
|
||||
const previous = Object.getOwnPropertyDescriptor(globalThis, 'EventSource');
|
||||
let options: EventSourceInit | undefined;
|
||||
class StubEventSource {
|
||||
constructor(_url: string | URL, init?: EventSourceInit) {
|
||||
options = init;
|
||||
}
|
||||
close() {}
|
||||
}
|
||||
Object.defineProperty(globalThis, 'EventSource', {
|
||||
configurable: true,
|
||||
value: StubEventSource,
|
||||
});
|
||||
try {
|
||||
createRunEventSource().close();
|
||||
await expect(options?.withCredentials).toBe(true);
|
||||
} finally {
|
||||
if (previous) Object.defineProperty(globalThis, 'EventSource', previous);
|
||||
else Reflect.deleteProperty(globalThis, 'EventSource');
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,132 @@
|
||||
import '../../src/i18n';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect, userEvent, within } from 'storybook/test';
|
||||
import { ApiError } from '../../src/api/client';
|
||||
import { LoginForm } from '../../src/pages/auth/LoginForm';
|
||||
|
||||
const meta: Meta<typeof LoginForm> = {
|
||||
title: 'Authentication/Login form',
|
||||
component: LoginForm,
|
||||
parameters: { layout: 'centered' },
|
||||
tags: ['autodocs'],
|
||||
args: { onSubmit: async () => undefined },
|
||||
decorators: [
|
||||
(Story) => (
|
||||
<div style={{ width: 'min(calc(100vw - 32px), 440px)' }}>
|
||||
<Story />
|
||||
</div>
|
||||
),
|
||||
],
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof LoginForm>;
|
||||
|
||||
async function expectLoginSurfaces(canvasElement: HTMLElement) {
|
||||
const canvas = within(canvasElement);
|
||||
const card = canvasElement.querySelector('section');
|
||||
const notice = canvas.getByText('Your session has expired. Sign in again to continue.');
|
||||
const username = canvas.getByRole('textbox', { name: 'Username' });
|
||||
if (!card) throw new Error('Login card was not rendered.');
|
||||
|
||||
await expect(window.getComputedStyle(notice).marginBottom).not.toBe('0px');
|
||||
await expect(window.getComputedStyle(username).backgroundColor).not.toBe(
|
||||
window.getComputedStyle(card).backgroundColor,
|
||||
);
|
||||
}
|
||||
|
||||
export const Initial: Story = {};
|
||||
|
||||
export const ExpiredSession: Story = {
|
||||
args: { expired: true },
|
||||
play: async ({ canvasElement }) => expectLoginSurfaces(canvasElement),
|
||||
};
|
||||
|
||||
export const SignedOut: Story = { args: { signedOut: true } };
|
||||
|
||||
export const DarkTheme: Story = {
|
||||
args: { expired: true },
|
||||
decorators: [
|
||||
(Story) => (
|
||||
<div data-theme="dark" style={{ width: 440, padding: 24, background: 'var(--color-bg)' }}>
|
||||
<Story />
|
||||
</div>
|
||||
),
|
||||
],
|
||||
play: async ({ canvasElement }) => expectLoginSurfaces(canvasElement),
|
||||
};
|
||||
|
||||
export const NarrowViewport: Story = {
|
||||
decorators: [
|
||||
(Story) => (
|
||||
<div style={{ width: 320, padding: 16, background: 'var(--color-bg)' }}>
|
||||
<Story />
|
||||
</div>
|
||||
),
|
||||
],
|
||||
};
|
||||
|
||||
export const EmptyFieldValidation: Story = {
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Sign in' }));
|
||||
await expect(canvas.getByText('Enter your username.')).toBeVisible();
|
||||
await expect(canvas.getByRole('textbox', { name: 'Username' })).toHaveFocus();
|
||||
await expect(canvas.getByLabelText('Password')).toHaveAttribute('aria-invalid', 'true');
|
||||
},
|
||||
};
|
||||
|
||||
export const InvalidCredentials: Story = {
|
||||
args: {
|
||||
onSubmit: async () => {
|
||||
throw new ApiError(401, 'Unauthorized');
|
||||
},
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.type(canvas.getByRole('textbox', { name: 'Username' }), 'operator');
|
||||
await userEvent.type(canvas.getByLabelText('Password'), 'wrong-password');
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Sign in' }));
|
||||
await expect(await canvas.findByRole('alert')).toHaveTextContent(
|
||||
'Username or password is incorrect.',
|
||||
);
|
||||
await expect(canvas.getByRole('textbox', { name: 'Username' })).toHaveValue('operator');
|
||||
await expect(canvas.getByLabelText('Password')).toHaveValue('');
|
||||
await expect(canvas.getByLabelText('Password')).toHaveFocus();
|
||||
},
|
||||
};
|
||||
|
||||
export const RequestFailureAndRetry: Story = {
|
||||
args: {
|
||||
onSubmit: (() => {
|
||||
let attempts = 0;
|
||||
return async () => {
|
||||
attempts += 1;
|
||||
if (attempts === 1) throw new ApiError(503, 'Unavailable');
|
||||
};
|
||||
})(),
|
||||
},
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.type(canvas.getByRole('textbox', { name: 'Username' }), 'operator');
|
||||
await userEvent.type(canvas.getByLabelText('Password'), 'temporary');
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Sign in' }));
|
||||
await expect(await canvas.findByRole('alert')).toHaveTextContent(
|
||||
"Couldn't sign in. Check your connection and try again.",
|
||||
);
|
||||
await expect(canvas.getByLabelText('Password')).toHaveValue('temporary');
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Sign in' }));
|
||||
await expect(canvas.queryByRole('alert')).not.toBeInTheDocument();
|
||||
},
|
||||
};
|
||||
|
||||
export const Submitting: Story = {
|
||||
args: { onSubmit: () => new Promise(() => undefined) },
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.type(canvas.getByRole('textbox', { name: 'Username' }), 'operator');
|
||||
await userEvent.type(canvas.getByLabelText('Password'), 'secret');
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Sign in' }));
|
||||
await expect(canvas.getByRole('status')).toHaveTextContent('Signing in…');
|
||||
await expect(canvas.getByRole('button', { name: 'Signing in…' })).toBeDisabled();
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect } from 'storybook/test';
|
||||
import { safeReturnTo } from '../../src/auth/returnTo';
|
||||
|
||||
function ReturnToSafetyExample() {
|
||||
return <p>Local return destinations are checked before use.</p>;
|
||||
}
|
||||
|
||||
const meta: Meta<typeof ReturnToSafetyExample> = {
|
||||
title: 'Authentication/Return destination safety',
|
||||
component: ReturnToSafetyExample,
|
||||
tags: ['autodocs'],
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof ReturnToSafetyExample>;
|
||||
|
||||
export const Validation: Story = {
|
||||
play: async () => {
|
||||
await expect(safeReturnTo('/scenarios/123/runs/456?example=1#details')).toBe(
|
||||
'/scenarios/123/runs/456?example=1#details',
|
||||
);
|
||||
await expect(safeReturnTo('/scenarios')).toBe('/scenarios');
|
||||
await expect(safeReturnTo('//external.example/path')).toBeNull();
|
||||
await expect(safeReturnTo('https://external.example/path')).toBeNull();
|
||||
await expect(safeReturnTo('/%2f%2fexternal.example')).toBeNull();
|
||||
await expect(safeReturnTo('/%5c%5cexternal.example')).toBeNull();
|
||||
await expect(safeReturnTo('/login?returnTo=/scenarios')).toBeNull();
|
||||
await expect(safeReturnTo('/auth/me')).toBeNull();
|
||||
await expect(safeReturnTo('/%')).toBeNull();
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
import '../../src/i18n';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { expect, fn, userEvent, within } from 'storybook/test';
|
||||
import { SignOutControl } from '../../src/pages/auth/SignOutControl';
|
||||
|
||||
const meta: Meta<typeof SignOutControl> = {
|
||||
title: 'Authentication/Sign out',
|
||||
component: SignOutControl,
|
||||
parameters: { layout: 'centered' },
|
||||
tags: ['autodocs'],
|
||||
args: { onSignOut: fn() },
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<typeof SignOutControl>;
|
||||
|
||||
export const Ready: Story = {};
|
||||
|
||||
export const Pending: Story = {
|
||||
args: { pending: true },
|
||||
play: async ({ canvasElement }) => {
|
||||
const button = within(canvasElement).getByRole('button', { name: 'Signing out…' });
|
||||
await expect(button).toBeDisabled();
|
||||
},
|
||||
};
|
||||
|
||||
export const FailureAndRetry: Story = {
|
||||
args: { failed: true },
|
||||
play: async ({ canvasElement, args }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(canvas.getByRole('alert')).toHaveTextContent("Couldn't sign out. Try again.");
|
||||
await userEvent.click(canvas.getByRole('button', { name: 'Retry' }));
|
||||
await expect(args.onSignOut).toHaveBeenCalledTimes(1);
|
||||
},
|
||||
};
|
||||
@@ -38,6 +38,7 @@
|
||||
|
||||
.footerButtons {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
@@ -47,6 +48,7 @@
|
||||
padding: var(--space-3) var(--space-2) var(--space-2);
|
||||
border-top: var(--border-width) solid var(--color-border);
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
@@ -68,6 +70,68 @@
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.signOut,
|
||||
.expandForSignOut {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
padding: 0;
|
||||
color: var(--color-text-muted);
|
||||
background: transparent;
|
||||
border: var(--border-width) solid var(--color-border);
|
||||
border-radius: var(--radius-md);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.signOut:hover,
|
||||
.expandForSignOut:hover {
|
||||
color: var(--color-text);
|
||||
background: var(--color-secondary);
|
||||
}
|
||||
|
||||
.signOut:focus-visible,
|
||||
.expandForSignOut:focus-visible,
|
||||
.logoutFailure button:focus-visible {
|
||||
outline: 2px solid var(--color-primary-text);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.signOut:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: wait;
|
||||
}
|
||||
|
||||
.logoutFailure {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-2);
|
||||
color: var(--color-error-fg);
|
||||
background: var(--color-error-bg);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
|
||||
.logoutFailure button {
|
||||
min-height: 32px;
|
||||
color: inherit;
|
||||
background: transparent;
|
||||
border: var(--border-width) solid currentColor;
|
||||
border-radius: var(--radius-sm);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.expandForSignOut {
|
||||
position: fixed;
|
||||
left: 8px;
|
||||
bottom: 12px;
|
||||
z-index: 20;
|
||||
background: var(--color-bg-subtle);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
|
||||
.navItem {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
+77
-2
@@ -1,5 +1,6 @@
|
||||
import { lazy, Suspense } from 'react';
|
||||
import { NavLink, Navigate, Route, Routes } from 'react-router-dom';
|
||||
import { lazy, Suspense, useEffect, useRef, useState } from 'react';
|
||||
import { LogOut } from 'lucide-react';
|
||||
import { NavLink, Navigate, Route, Routes, useLocation, useSearchParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Globe, Monitor, ClipboardList, Activity, KeyRound, Braces, Upload } from 'lucide-react';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
@@ -8,6 +9,11 @@ import { NotificationToggle, SidePanel, ThemeSwitcher } from './ui';
|
||||
import liqaLogo from './assets/liqa.svg';
|
||||
import { useManifest } from './hooks/useManifest';
|
||||
import { useRunNotifications } from './hooks/useRunNotifications';
|
||||
import { useAuth } from './auth/useAuth';
|
||||
import { safeReturnTo } from './auth/returnTo';
|
||||
import { AuthStatusPage } from './pages/auth/AuthStatusPage';
|
||||
import { LoginPage } from './pages/auth/LoginPage';
|
||||
import { SignOutControl } from './pages/auth/SignOutControl';
|
||||
|
||||
const EnvironmentsPage = lazy(() =>
|
||||
import('./pages/environment/EnvironmentsPage').then((m) => ({ default: m.EnvironmentsPage })),
|
||||
@@ -109,12 +115,59 @@ const NAV: ({ path: string; labelKey: string; Icon: LucideIcon } | { separator:
|
||||
|
||||
export default function App() {
|
||||
const { t } = useTranslation();
|
||||
const auth = useAuth();
|
||||
const location = useLocation();
|
||||
const [search] = useSearchParams();
|
||||
const [collapsed, setCollapsed] = useState(false);
|
||||
const [loggingOut, setLoggingOut] = useState(false);
|
||||
const [logoutFailed, setLogoutFailed] = useState(false);
|
||||
const focusSignOut = useRef(false);
|
||||
const { version } = useManifest();
|
||||
const notifications = useRunNotifications();
|
||||
|
||||
useEffect(() => {
|
||||
if (!collapsed && focusSignOut.current) {
|
||||
focusSignOut.current = false;
|
||||
document.querySelector<HTMLButtonElement>('[data-sign-out="true"]')?.focus();
|
||||
}
|
||||
}, [collapsed]);
|
||||
|
||||
async function signOut() {
|
||||
if (loggingOut) return;
|
||||
setLoggingOut(true);
|
||||
setLogoutFailed(false);
|
||||
try {
|
||||
await auth.logout();
|
||||
} catch {
|
||||
setLogoutFailed(true);
|
||||
} finally {
|
||||
setLoggingOut(false);
|
||||
}
|
||||
}
|
||||
|
||||
const onLogin = location.pathname === '/login';
|
||||
if (auth.enabled && (auth.status === 'checking' || auth.status === 'disabled')) {
|
||||
return <AuthStatusPage />;
|
||||
}
|
||||
if (auth.enabled && auth.status === 'error') {
|
||||
return <AuthStatusPage failed onRetry={() => void auth.checkSession()} />;
|
||||
}
|
||||
if (!auth.enabled && onLogin) return <Navigate to="/scenarios" replace />;
|
||||
if (auth.enabled && auth.status === 'authenticated' && onLogin) {
|
||||
return <Navigate to={safeReturnTo(search.get('returnTo')) ?? '/scenarios'} replace />;
|
||||
}
|
||||
if (auth.enabled && auth.status === 'unauthenticated' && !onLogin) {
|
||||
const returnTo =
|
||||
safeReturnTo(`${location.pathname}${location.search}${location.hash}`) ?? '/scenarios';
|
||||
return <Navigate to={`/login?returnTo=${encodeURIComponent(returnTo)}`} replace />;
|
||||
}
|
||||
if (onLogin) return <LoginPage />;
|
||||
|
||||
return (
|
||||
<div className={styles.shell}>
|
||||
<SidePanel
|
||||
collapsed={collapsed}
|
||||
onCollapsedChange={setCollapsed}
|
||||
header={
|
||||
<div className={styles.header}>
|
||||
<img src={liqaLogo} alt="Liqa" className={styles.brand} />
|
||||
@@ -148,6 +201,13 @@ export default function App() {
|
||||
{notifications && (
|
||||
<NotificationToggle state={notifications.state} onToggle={notifications.toggle} />
|
||||
)}
|
||||
{auth.enabled && auth.status === 'authenticated' && (
|
||||
<SignOutControl
|
||||
pending={loggingOut}
|
||||
failed={logoutFailed}
|
||||
onSignOut={() => void signOut()}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className={styles.version}>
|
||||
<span
|
||||
@@ -173,6 +233,21 @@ export default function App() {
|
||||
</div>
|
||||
</SidePanel>
|
||||
|
||||
{collapsed && auth.enabled && auth.status === 'authenticated' && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.expandForSignOut}
|
||||
aria-label={t('auth.show_sign_out')}
|
||||
title={t('auth.show_sign_out')}
|
||||
onClick={() => {
|
||||
focusSignOut.current = true;
|
||||
setCollapsed(false);
|
||||
}}
|
||||
>
|
||||
<LogOut size={18} aria-hidden="true" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
<main className={styles.main}>
|
||||
<Suspense fallback={<p>Loading…</p>}>
|
||||
<Routes>
|
||||
|
||||
@@ -31,7 +31,25 @@ const BASE_URL = ((import.meta.env.VITE_API_URL as string | undefined) ?? '/api/
|
||||
/** URL of the server-sent events stream of run lifecycle events. */
|
||||
export const RUN_EVENTS_URL = `${BASE_URL}/scenarios/runs/events`;
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
public readonly status: number,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'ApiError';
|
||||
}
|
||||
}
|
||||
|
||||
interface RequestOptions {
|
||||
quietErrors?: boolean;
|
||||
}
|
||||
|
||||
async function request<T>(
|
||||
path: string,
|
||||
init?: RequestInit,
|
||||
options: RequestOptions = {},
|
||||
): Promise<T> {
|
||||
let res: Response;
|
||||
try {
|
||||
const headers = new Headers(init?.headers);
|
||||
@@ -41,18 +59,26 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
|
||||
res = await fetch(`${BASE_URL}${path}`, {
|
||||
...init,
|
||||
credentials: init?.credentials ?? 'include',
|
||||
headers,
|
||||
});
|
||||
} catch (err) {
|
||||
const message = (err as Error).message || 'Network request failed';
|
||||
emitApiErrorToast(message);
|
||||
if (!options.quietErrors) emitApiErrorToast(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => res.statusText);
|
||||
const message = `${res.status} ${text}`;
|
||||
const error = new ApiError(res.status, message);
|
||||
if (res.status === 401 && !path.startsWith('/auth/')) {
|
||||
const event = new CustomEvent('liqa:unauthorized', { cancelable: true });
|
||||
const handled = !window.dispatchEvent(event);
|
||||
if (!handled && !options.quietErrors) emitApiErrorToast(message);
|
||||
} else if (!options.quietErrors && !path.startsWith('/auth/')) {
|
||||
emitApiErrorToast(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
const contentLength = res.headers.get('content-length');
|
||||
if (res.status === 204 || contentLength === '0') return undefined as T;
|
||||
@@ -65,6 +91,30 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
return text as T;
|
||||
}
|
||||
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
username: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export const auth = {
|
||||
async login(username: string, password: string): Promise<AuthUser> {
|
||||
const response = await request<{ user: AuthUser }>(
|
||||
'/auth/login',
|
||||
{ method: 'POST', body: JSON.stringify({ username, password }) },
|
||||
{ quietErrors: true },
|
||||
);
|
||||
return response.user;
|
||||
},
|
||||
me(): Promise<AuthUser> {
|
||||
return request('/auth/me', undefined, { quietErrors: true });
|
||||
},
|
||||
logout(): Promise<void> {
|
||||
return request('/auth/logout', { method: 'POST' }, { quietErrors: true });
|
||||
},
|
||||
};
|
||||
|
||||
// ── Credentials ───────────────────────────────────────────────────────────────
|
||||
|
||||
export const credentials = {
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import { useLocation, useNavigate } from 'react-router-dom';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { ApiError, auth as authApi, type AuthUser } from '../api/client';
|
||||
import { refreshManifest } from '../lib/manifest';
|
||||
import { useManifest } from '../hooks/useManifest';
|
||||
import { loginPath, safeReturnTo } from './returnTo';
|
||||
import { AuthContext } from './context';
|
||||
import type { AuthStatus } from './context';
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const { auth: manifestAuth } = useManifest();
|
||||
const enabled = manifestAuth.enabled;
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
const [status, setStatus] = useState<AuthStatus>('checking');
|
||||
const [user, setUser] = useState<AuthUser | null>(null);
|
||||
const statusRef = useRef(status);
|
||||
const enabledRef = useRef(enabled);
|
||||
const handledUnauthorized = useRef(false);
|
||||
const checkInFlight = useRef<Promise<void> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
enabledRef.current = enabled;
|
||||
statusRef.current = status;
|
||||
}, [enabled, status]);
|
||||
|
||||
const updateStatus = useCallback((next: AuthStatus) => {
|
||||
statusRef.current = next;
|
||||
setStatus(next);
|
||||
}, []);
|
||||
|
||||
const checkSession = useCallback(async () => {
|
||||
if (!enabledRef.current) {
|
||||
setUser(null);
|
||||
updateStatus('disabled');
|
||||
return;
|
||||
}
|
||||
if (checkInFlight.current) return checkInFlight.current;
|
||||
updateStatus('checking');
|
||||
const check = authApi
|
||||
.me()
|
||||
.then((account) => {
|
||||
setUser(account);
|
||||
handledUnauthorized.current = false;
|
||||
updateStatus('authenticated');
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
setUser(null);
|
||||
updateStatus(
|
||||
error instanceof ApiError && error.status === 401 ? 'unauthenticated' : 'error',
|
||||
);
|
||||
})
|
||||
.finally(() => {
|
||||
checkInFlight.current = null;
|
||||
});
|
||||
checkInFlight.current = check;
|
||||
return check;
|
||||
}, [updateStatus]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
// This synchronizes the session state with the server's feature flag.
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setUser(null);
|
||||
updateStatus('disabled');
|
||||
queryClient.clear();
|
||||
return;
|
||||
}
|
||||
void checkSession();
|
||||
}, [enabled, checkSession, queryClient, updateStatus]);
|
||||
|
||||
useEffect(() => {
|
||||
const onUnauthorized = (event: Event) => {
|
||||
if (!enabledRef.current) return;
|
||||
if (handledUnauthorized.current) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
if (statusRef.current !== 'authenticated') return;
|
||||
event.preventDefault();
|
||||
handledUnauthorized.current = true;
|
||||
queryClient.clear();
|
||||
setUser(null);
|
||||
updateStatus('unauthenticated');
|
||||
const target =
|
||||
safeReturnTo(`${location.pathname}${location.search}${location.hash}`) ?? '/scenarios';
|
||||
navigate(loginPath(target, true), { replace: true });
|
||||
};
|
||||
window.addEventListener('liqa:unauthorized', onUnauthorized);
|
||||
return () => window.removeEventListener('liqa:unauthorized', onUnauthorized);
|
||||
}, [location.hash, location.pathname, location.search, navigate, queryClient, updateStatus]);
|
||||
|
||||
const login = useCallback(
|
||||
async (username: string, password: string) => {
|
||||
let account: AuthUser;
|
||||
try {
|
||||
account = await authApi.login(username, password);
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.status === 404) await refreshManifest();
|
||||
throw error;
|
||||
}
|
||||
queryClient.clear();
|
||||
handledUnauthorized.current = false;
|
||||
setUser(account);
|
||||
updateStatus('authenticated');
|
||||
},
|
||||
[queryClient, updateStatus],
|
||||
);
|
||||
|
||||
const logout = useCallback(async () => {
|
||||
try {
|
||||
await authApi.logout();
|
||||
} catch (error) {
|
||||
if (!(error instanceof ApiError && error.status === 401)) {
|
||||
await checkSession();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
queryClient.clear();
|
||||
setUser(null);
|
||||
updateStatus('unauthenticated');
|
||||
handledUnauthorized.current = false;
|
||||
navigate('/login?notice=signedOut', { replace: true });
|
||||
}, [checkSession, navigate, queryClient, updateStatus]);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ enabled, status, user, login, logout, checkSession }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { createContext } from 'react';
|
||||
import type { AuthUser } from '../api/client';
|
||||
|
||||
export type AuthStatus = 'disabled' | 'checking' | 'authenticated' | 'unauthenticated' | 'error';
|
||||
|
||||
export interface AuthContextValue {
|
||||
enabled: boolean;
|
||||
status: AuthStatus;
|
||||
user: AuthUser | null;
|
||||
login: (username: string, password: string) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
checkSession: () => Promise<void>;
|
||||
}
|
||||
|
||||
export const AuthContext = createContext<AuthContextValue | null>(null);
|
||||
@@ -0,0 +1,45 @@
|
||||
/** Return only a well-formed route on this app's origin. */
|
||||
export function safeReturnTo(value: string | null | undefined): string | null {
|
||||
if (
|
||||
!value ||
|
||||
!value.startsWith('/') ||
|
||||
value.startsWith('//') ||
|
||||
value.includes('\\') ||
|
||||
/%(?:2f|5c)/i.test(value)
|
||||
)
|
||||
return null;
|
||||
|
||||
let decoded = value;
|
||||
try {
|
||||
for (let pass = 0; pass < 3; pass += 1) {
|
||||
const next = decodeURIComponent(decoded);
|
||||
if (next === decoded) break;
|
||||
decoded = next;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const containsControl = [...decoded].some((character) => {
|
||||
const code = character.charCodeAt(0);
|
||||
return code < 32 || code === 127;
|
||||
});
|
||||
if (decoded.startsWith('//') || decoded.includes('\\') || containsControl) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const target = new URL(value, window.location.origin);
|
||||
if (target.origin !== window.location.origin) return null;
|
||||
if (/^\/(?:login|auth)(?:\/|$)/i.test(target.pathname)) return null;
|
||||
return `${target.pathname}${target.search}${target.hash}`;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function loginPath(returnTo: string, expired = false): string {
|
||||
const query = new URLSearchParams();
|
||||
query.set('returnTo', safeReturnTo(returnTo) ?? '/scenarios');
|
||||
if (expired) query.set('expired', '1');
|
||||
return `/login?${query.toString()}`;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { useContext } from 'react';
|
||||
import { AuthContext } from './context';
|
||||
|
||||
export function useAuth() {
|
||||
const value = useContext(AuthContext);
|
||||
if (!value) throw new Error('useAuth must be used inside AuthProvider');
|
||||
return value;
|
||||
}
|
||||
@@ -5,11 +5,16 @@ import { useTranslation } from 'react-i18next';
|
||||
import { RUN_EVENTS_URL } from '../api/client';
|
||||
import type { RunEvent } from '../api/types';
|
||||
import type { NotificationToggleState } from '../ui';
|
||||
import { useAuth } from '../auth/useAuth';
|
||||
|
||||
const STORAGE_KEY = 'liqa-run-notifications';
|
||||
const RETRY_MIN_MS = 1_000;
|
||||
const RETRY_MAX_MS = 30_000;
|
||||
|
||||
export function createRunEventSource(): EventSource {
|
||||
return new EventSource(RUN_EVENTS_URL, { withCredentials: true });
|
||||
}
|
||||
|
||||
function supported(): boolean {
|
||||
return typeof window !== 'undefined' && 'Notification' in window && 'EventSource' in window;
|
||||
}
|
||||
@@ -41,6 +46,7 @@ export function useRunNotifications(): {
|
||||
state: NotificationToggleState;
|
||||
toggle: () => void;
|
||||
} | null {
|
||||
const auth = useAuth();
|
||||
const isSupported = supported();
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
@@ -81,7 +87,11 @@ export function useRunNotifications(): {
|
||||
handlers.current = { t, navigate };
|
||||
});
|
||||
|
||||
const active = isSupported && enabled && permission === 'granted';
|
||||
const active =
|
||||
isSupported &&
|
||||
enabled &&
|
||||
permission === 'granted' &&
|
||||
(!auth.enabled || auth.status === 'authenticated');
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
@@ -122,7 +132,7 @@ export function useRunNotifications(): {
|
||||
};
|
||||
|
||||
const connect = () => {
|
||||
source = new EventSource(RUN_EVENTS_URL);
|
||||
source = createRunEventSource();
|
||||
source.addEventListener('open', () => {
|
||||
retryDelay = RETRY_MIN_MS;
|
||||
});
|
||||
|
||||
@@ -1,4 +1,24 @@
|
||||
{
|
||||
"auth": {
|
||||
"page_title": "Sign in",
|
||||
"sign_in": "Sign in",
|
||||
"signing_in": "Signing in…",
|
||||
"username": "Username",
|
||||
"password": "Password",
|
||||
"username_required": "Enter your username.",
|
||||
"password_required": "Enter your password.",
|
||||
"invalid_credentials": "Username or password is incorrect.",
|
||||
"sign_in_failed": "Couldn't sign in. Check your connection and try again.",
|
||||
"checking_session": "Checking your session…",
|
||||
"session_check_failed": "Couldn't check your session. Try again.",
|
||||
"retry": "Retry",
|
||||
"session_expired": "Your session has expired. Sign in again to continue.",
|
||||
"sign_out": "Sign out",
|
||||
"signing_out": "Signing out…",
|
||||
"signed_out": "You have signed out.",
|
||||
"sign_out_failed": "Couldn't sign out. Try again.",
|
||||
"show_sign_out": "Expand the menu to sign out"
|
||||
},
|
||||
"common": {
|
||||
"button_cancel": "Cancel",
|
||||
"button_confirm": "Confirm",
|
||||
|
||||
@@ -8,12 +8,16 @@ export interface Manifest {
|
||||
runLogs: {
|
||||
dataLimits: LogDataLimits;
|
||||
};
|
||||
auth: {
|
||||
enabled: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export const DEFAULT_MANIFEST: Manifest = {
|
||||
name: 'liqa',
|
||||
version: __APP_VERSION__,
|
||||
runLogs: { dataLimits: DEFAULT_LOG_DATA_LIMITS },
|
||||
auth: { enabled: false },
|
||||
};
|
||||
|
||||
const STORAGE_KEY = 'liqa-manifest';
|
||||
@@ -39,6 +43,7 @@ function normalize(raw: unknown): Manifest | null {
|
||||
return {
|
||||
name: typeof m.name === 'string' ? m.name : DEFAULT_MANIFEST.name,
|
||||
version: typeof m.version === 'string' ? m.version : DEFAULT_MANIFEST.version,
|
||||
auth: { enabled: m.auth?.enabled === true },
|
||||
runLogs: {
|
||||
dataLimits: {
|
||||
bytes: num(limits.bytes, DEFAULT_LOG_DATA_LIMITS.bytes),
|
||||
@@ -77,7 +82,10 @@ const listeners = new Set<() => void>();
|
||||
* silent: the cached (or default) manifest stays in use.
|
||||
*/
|
||||
export function refreshManifest(): Promise<void> {
|
||||
inFlight ??= fetch(MANIFEST_URL, { headers: { Accept: 'application/json' } })
|
||||
inFlight ??= fetch(MANIFEST_URL, {
|
||||
headers: { Accept: 'application/json' },
|
||||
credentials: 'include',
|
||||
})
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((raw: unknown) => {
|
||||
const next = normalize(raw);
|
||||
|
||||
+12
-1
@@ -6,15 +6,26 @@ import './i18n';
|
||||
import './ui/tokens.css';
|
||||
import App from './App';
|
||||
import { ToastProvider } from './ui';
|
||||
import { AuthProvider } from './auth/AuthContext';
|
||||
import { ApiError } from './api/client';
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
retry: (failureCount, error) =>
|
||||
error instanceof ApiError && error.status === 401 ? false : failureCount < 3,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ToastProvider>
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<App />
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
</ToastProvider>
|
||||
</QueryClientProvider>
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
.page {
|
||||
min-height: 100vh;
|
||||
padding: 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
color: var(--color-text);
|
||||
background: var(--color-bg);
|
||||
font-family: var(--font-family);
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.logo {
|
||||
display: block;
|
||||
width: auto;
|
||||
height: 32px;
|
||||
padding: 3px 6px;
|
||||
background: #e6edea;
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
|
||||
.main {
|
||||
flex: 1;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: var(--space-6) 0;
|
||||
}
|
||||
|
||||
.message {
|
||||
width: min(100%, 440px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: var(--space-4);
|
||||
margin: 0;
|
||||
padding: var(--space-6);
|
||||
text-align: center;
|
||||
background: var(--color-bg);
|
||||
border: var(--border-width) solid var(--color-border);
|
||||
border-radius: var(--radius-lg);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
|
||||
.message p {
|
||||
margin: 0;
|
||||
color: var(--color-error-fg);
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.page {
|
||||
padding: 16px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button, ThemeSwitcher } from '../../ui';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import liqaLogo from '../../assets/liqa.svg';
|
||||
import styles from './AuthStatusPage.module.css';
|
||||
|
||||
export function AuthStatusPage({
|
||||
failed = false,
|
||||
onRetry,
|
||||
}: {
|
||||
failed?: boolean;
|
||||
onRetry?: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
usePageTitle(t('auth.page_title'));
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<header className={styles.header}>
|
||||
<img src={liqaLogo} alt="Liqa" className={styles.logo} />
|
||||
<ThemeSwitcher />
|
||||
</header>
|
||||
<main className={styles.main} aria-live="polite">
|
||||
{failed ? (
|
||||
<section className={styles.message}>
|
||||
<p role="alert">{t('auth.session_check_failed')}</p>
|
||||
<Button type="button" size="lg" onClick={onRetry}>
|
||||
{t('auth.retry')}
|
||||
</Button>
|
||||
</section>
|
||||
) : (
|
||||
<p className={styles.message} role="status">
|
||||
{t('auth.checking_session')}
|
||||
</p>
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
.card {
|
||||
width: min(100%, 400px);
|
||||
padding: 24px;
|
||||
color: var(--color-text);
|
||||
background: var(--color-bg);
|
||||
border: var(--border-width) solid var(--color-border);
|
||||
border-radius: var(--radius-lg);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
|
||||
.title {
|
||||
margin: 0 0 var(--space-5);
|
||||
font-size: var(--font-size-lg);
|
||||
line-height: 1.3;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.title:focus {
|
||||
outline: 2px solid var(--color-primary-text);
|
||||
outline-offset: 4px;
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.notice,
|
||||
.formError {
|
||||
margin: 0;
|
||||
padding: var(--space-3) var(--space-4);
|
||||
color: var(--color-error-fg);
|
||||
background: var(--color-error-bg);
|
||||
border-radius: var(--radius-md);
|
||||
font-size: var(--font-size-sm);
|
||||
}
|
||||
|
||||
.notice {
|
||||
margin-bottom: var(--space-4);
|
||||
}
|
||||
|
||||
.form .loginInput {
|
||||
background: var(--color-bg-subtle);
|
||||
}
|
||||
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.submit {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.status {
|
||||
margin: 0;
|
||||
color: var(--color-text-muted);
|
||||
font-size: var(--font-size-sm);
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.card {
|
||||
padding: var(--space-4);
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { useEffect, useRef, useState, type FormEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ApiError } from '../../api/client';
|
||||
import { Button, Input } from '../../ui';
|
||||
import styles from './LoginForm.module.css';
|
||||
|
||||
export interface LoginFormProps {
|
||||
expired?: boolean;
|
||||
signedOut?: boolean;
|
||||
onSubmit: (username: string, password: string) => Promise<void>;
|
||||
}
|
||||
|
||||
export function LoginForm({ expired = false, signedOut = false, onSubmit }: LoginFormProps) {
|
||||
const { t } = useTranslation();
|
||||
const titleRef = useRef<HTMLHeadingElement>(null);
|
||||
const formRef = useRef<HTMLFormElement>(null);
|
||||
const focusPasswordAfterInvalidCredentialsRef = useRef(false);
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [usernameError, setUsernameError] = useState('');
|
||||
const [passwordError, setPasswordError] = useState('');
|
||||
const [formError, setFormError] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
titleRef.current?.focus();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!submitting && focusPasswordAfterInvalidCredentialsRef.current) {
|
||||
focusPasswordAfterInvalidCredentialsRef.current = false;
|
||||
formRef.current?.querySelector<HTMLInputElement>('input[name="password"]')?.focus();
|
||||
}
|
||||
}, [submitting]);
|
||||
|
||||
function focusInput(name: string) {
|
||||
formRef.current?.querySelector<HTMLInputElement>(`input[name="${name}"]`)?.focus();
|
||||
}
|
||||
|
||||
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (submitting) return;
|
||||
setFormError('');
|
||||
const missingUsername = username.trim().length === 0;
|
||||
const missingPassword = password.length === 0;
|
||||
setUsernameError(missingUsername ? t('auth.username_required') : '');
|
||||
setPasswordError(missingPassword ? t('auth.password_required') : '');
|
||||
if (missingUsername || missingPassword) {
|
||||
focusInput(missingUsername ? 'username' : 'password');
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitting(true);
|
||||
try {
|
||||
await onSubmit(username, password);
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.status === 401) {
|
||||
setFormError(t('auth.invalid_credentials'));
|
||||
setPassword('');
|
||||
focusPasswordAfterInvalidCredentialsRef.current = true;
|
||||
} else {
|
||||
setFormError(t('auth.sign_in_failed'));
|
||||
}
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<section className={styles.card} aria-labelledby="login-title">
|
||||
<h1 id="login-title" ref={titleRef} tabIndex={-1} className={styles.title}>
|
||||
{t('auth.sign_in')}
|
||||
</h1>
|
||||
{expired && <p className={styles.notice}>{t('auth.session_expired')}</p>}
|
||||
{signedOut && <p className={styles.notice}>{t('auth.signed_out')}</p>}
|
||||
<form
|
||||
ref={formRef}
|
||||
className={styles.form}
|
||||
onSubmit={(event) => void handleSubmit(event)}
|
||||
noValidate
|
||||
>
|
||||
<Input
|
||||
name="username"
|
||||
className={styles.loginInput}
|
||||
label={t('auth.username')}
|
||||
autoComplete="username"
|
||||
autoCapitalize="none"
|
||||
autoCorrect="off"
|
||||
value={username}
|
||||
onChange={(event) => {
|
||||
setUsername(event.target.value);
|
||||
if (usernameError) setUsernameError('');
|
||||
}}
|
||||
error={usernameError || undefined}
|
||||
disabled={submitting}
|
||||
/>
|
||||
<Input
|
||||
name="password"
|
||||
className={styles.loginInput}
|
||||
type="password"
|
||||
label={t('auth.password')}
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={(event) => {
|
||||
setPassword(event.target.value);
|
||||
if (passwordError) setPasswordError('');
|
||||
}}
|
||||
error={passwordError || undefined}
|
||||
disabled={submitting}
|
||||
/>
|
||||
{formError && (
|
||||
<p className={styles.formError} role="alert">
|
||||
{formError}
|
||||
</p>
|
||||
)}
|
||||
{submitting && (
|
||||
<p className={styles.status} role="status" aria-live="polite">
|
||||
{t('auth.signing_in')}
|
||||
</p>
|
||||
)}
|
||||
<Button
|
||||
type="submit"
|
||||
size="lg"
|
||||
loading={submitting}
|
||||
disabled={submitting}
|
||||
className={styles.submit}
|
||||
>
|
||||
{t(submitting ? 'auth.signing_in' : 'auth.sign_in')}
|
||||
</Button>
|
||||
</form>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
.page {
|
||||
min-height: 100vh;
|
||||
padding: 24px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
color: var(--color-text);
|
||||
background: var(--color-bg);
|
||||
font-family: var(--font-family);
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
|
||||
.logo {
|
||||
display: block;
|
||||
width: auto;
|
||||
height: 32px;
|
||||
padding: 3px 6px;
|
||||
background: #e6edea;
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
|
||||
.main {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: var(--space-6) 0;
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.page {
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.main {
|
||||
align-items: start;
|
||||
padding-top: clamp(40px, 12vh, 96px);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useCallback } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useAuth } from '../../auth/useAuth';
|
||||
import { safeReturnTo } from '../../auth/returnTo';
|
||||
import { usePageTitle } from '../../hooks/usePageTitle';
|
||||
import { ThemeSwitcher } from '../../ui';
|
||||
import liqaLogo from '../../assets/liqa.svg';
|
||||
import { LoginForm } from './LoginForm';
|
||||
import styles from './LoginPage.module.css';
|
||||
|
||||
export function LoginPage() {
|
||||
const auth = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [search] = useSearchParams();
|
||||
const { t } = useTranslation();
|
||||
const returnTo = safeReturnTo(search.get('returnTo')) ?? '/scenarios';
|
||||
const expired = search.get('expired') === '1';
|
||||
const signedOut = search.get('notice') === 'signedOut';
|
||||
usePageTitle(t('auth.page_title'));
|
||||
|
||||
const handleSubmit = useCallback(
|
||||
async (username: string, password: string) => {
|
||||
await auth.login(username, password);
|
||||
navigate(returnTo, { replace: true });
|
||||
},
|
||||
[auth, navigate, returnTo],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={styles.page}>
|
||||
<header className={styles.header}>
|
||||
<img src={liqaLogo} alt="Liqa" className={styles.logo} />
|
||||
<ThemeSwitcher />
|
||||
</header>
|
||||
<main className={styles.main}>
|
||||
<LoginForm expired={expired} signedOut={signedOut} onSubmit={handleSubmit} />
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
.root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.button {
|
||||
min-height: 44px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-2) var(--space-3);
|
||||
color: var(--color-text);
|
||||
background: transparent;
|
||||
border: var(--border-width) solid var(--color-border);
|
||||
border-radius: var(--radius-md);
|
||||
font: inherit;
|
||||
font-size: var(--font-size-xs);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.button:hover:not(:disabled) {
|
||||
background: var(--color-secondary);
|
||||
}
|
||||
|
||||
.button:focus-visible,
|
||||
.failure button:focus-visible {
|
||||
outline: 2px solid var(--color-primary-text);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.button:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: wait;
|
||||
}
|
||||
|
||||
.failure {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-2);
|
||||
color: var(--color-error-fg);
|
||||
background: var(--color-error-bg);
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: var(--font-size-xs);
|
||||
}
|
||||
|
||||
.failure button {
|
||||
min-height: 32px;
|
||||
color: inherit;
|
||||
background: transparent;
|
||||
border: var(--border-width) solid currentColor;
|
||||
border-radius: var(--radius-sm);
|
||||
cursor: pointer;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { LogOut } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import styles from './SignOutControl.module.css';
|
||||
|
||||
export function SignOutControl({
|
||||
pending = false,
|
||||
failed = false,
|
||||
onSignOut,
|
||||
}: {
|
||||
pending?: boolean;
|
||||
failed?: boolean;
|
||||
onSignOut: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.button}
|
||||
onClick={onSignOut}
|
||||
disabled={pending}
|
||||
data-sign-out="true"
|
||||
aria-label={t(pending ? 'auth.signing_out' : 'auth.sign_out')}
|
||||
title={t(pending ? 'auth.signing_out' : 'auth.sign_out')}
|
||||
>
|
||||
<LogOut size={16} aria-hidden="true" />
|
||||
<span>{t(pending ? 'auth.signing_out' : 'auth.sign_out')}</span>
|
||||
</button>
|
||||
{failed && (
|
||||
<div className={styles.failure} role="alert">
|
||||
<span>{t('auth.sign_out_failed')}</span>
|
||||
<button type="button" onClick={onSignOut} disabled={pending}>
|
||||
{t('auth.retry')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -88,3 +88,9 @@
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.spinner {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,7 @@ export function SidePanel({
|
||||
style={{ '--side-panel-width': `${width}px` } as React.CSSProperties}
|
||||
aria-expanded={!collapsed}
|
||||
>
|
||||
<div className={styles.inner}>
|
||||
<div className={styles.inner} aria-hidden={collapsed} inert={collapsed}>
|
||||
{header && <div className={styles.header}>{header}</div>}
|
||||
<div className={styles.content}>{children}</div>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user