feat(m2): auth, JWT, invitations, bootstrap, RTOps SPA pages
Crypto + tokens
- app/core/security.py: Argon2id PasswordHasher (time_cost=2, memory_cost=
64 MiB, parallelism=2) + opaque-token SHA-256 helpers (raw token shown
once, only the hash lives in the DB).
- app/core/jwt_tokens.py: HS256, claims iss/sub/type/jti/iat/exp. Access
1h, refresh 30d.
Services
- services/auth.py: login, refresh with token rotation + reuse-detection
chain revoke, logout (idempotent), change_password (forces logout-all).
- services/invitations.py: create, preview, accept, revoke. Default 7d TTL.
- services/bootstrap.py: seeds the 3 system groups (admin/redteam/blueteam),
consumes the install token, attaches the first user to admin.
- core/install_token.py: mints, persists in settings, marks consumed,
regenerate hook for /diag/reset.
API
- POST /setup (consume install token, create 1st admin) + GET /setup
(status).
- POST /auth/{login,refresh,logout,change-password} + GET /auth/me.
- POST /invitations + GET /invitations + GET /invitations/preview/<token> +
POST /invitations/accept/<token> + POST /invitations/<id>/revoke.
- POST /diag/reset: test-only kill switch (truncate auth tables + mint
fresh install token). Allowed in dev too (with WARNING log) so the e2e
suite can run against a make-up stack; production locked out.
Middleware
- @require_auth populates g.current_user (snapshot dataclass, session
closed before request handler runs).
- @require_perm(*codes): atomic perm union check; admin group bypasses.
Perm catalogue lands in M3, scaffolding here.
- flask-limiter: 10/min/IP on /auth/login & /auth/refresh, 5/min on
/auth/change-password & /setup, 10–20/min on invitation endpoints.
Disabled in APP_ENV=test.
CLI
- flask --app app.cli metamorph print-install-token [--force]
- flask --app app.cli metamorph seed-mitre (M4 placeholder)
Refresh cookie metamorph_refresh: HttpOnly + Secure (localhost is a secure
context for modern browsers) + SameSite=Strict + Path=/api/v1/auth/.
Email validation: app.api._validation.Email permissive RFC-shape regex so
internal TLDs (.local/.corp/.test) are accepted — pydantic.EmailStr's
deliverability check is too strict for red-team labs.
Frontend
- lib/{api,auth}.ts: access token in module memory, refresh cookie,
automatic 401-retry via /auth/refresh, useAuth() hook.
- components/{Layout,RequireAuth}.tsx + ui/{TextField,Alert}.tsx.
- pages/{Login,Setup,Register,Profile}.
Testing
- tests/test_auth_flow.py: 15 integration tests (24 backend total).
- e2e/tests/m2-auth.spec.ts: 8 Playwright tests (20 e2e total).
- tasks/testing-m2.md.
DoD: make test-api → 24 passed, make e2e → 20 passed; spec-reviewer pass
applied (Secure unconditional, refresh limit 10/min/IP).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
76
frontend/src/components/Layout.tsx
Normal file
76
frontend/src/components/Layout.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
import { Link, NavLink, Outlet, useNavigate } from 'react-router-dom';
|
||||
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
import { cn } from '@/lib/cn';
|
||||
|
||||
export function Layout() {
|
||||
const { state, logout } = useAuth();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const navItem = (to: string, label: string) => (
|
||||
<NavLink
|
||||
to={to}
|
||||
end
|
||||
className={({ isActive }) =>
|
||||
cn(
|
||||
'font-mono text-xs uppercase tracking-wider2 px-3 py-1 rounded',
|
||||
isActive ? 'text-cyan accent-fill-cyan' : 'text-text-dim hover:text-text-bright',
|
||||
)
|
||||
}
|
||||
>
|
||||
{label}
|
||||
</NavLink>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="px-[60px] py-10">
|
||||
<div className="mx-auto max-w-page">
|
||||
<header className="flex items-baseline justify-between mb-12">
|
||||
<Link to="/" className="font-mono text-[24px] font-bold tracking-tight text-text-bright">
|
||||
<span className="text-red">Meta</span>
|
||||
<span>morph</span>
|
||||
</Link>
|
||||
<nav className="flex items-center gap-2" aria-label="Primary">
|
||||
{state.user ? (
|
||||
<>
|
||||
{navItem('/', 'Home')}
|
||||
{navItem('/profile', 'Profile')}
|
||||
{state.user.is_admin && (
|
||||
<>
|
||||
{navItem('/admin/users', 'Users')}
|
||||
{navItem('/admin/groups', 'Groups')}
|
||||
{navItem('/admin/invitations', 'Invitations')}
|
||||
</>
|
||||
)}
|
||||
<span className="font-mono text-2xs text-text-dim ml-2" data-testid="me-email">
|
||||
{state.user.email}
|
||||
</span>
|
||||
<Button
|
||||
accent="rose"
|
||||
onClick={async () => {
|
||||
await logout();
|
||||
navigate('/login', { replace: true });
|
||||
}}
|
||||
>
|
||||
Logout
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{navItem('/login', 'Login')}
|
||||
{navItem('/setup', 'Setup')}
|
||||
</>
|
||||
)}
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<Outlet />
|
||||
|
||||
<footer className="mt-[60px] py-8 border-t border-border text-center font-mono text-xs text-text-dim">
|
||||
metamorph · M0 bootstrap · M1 db schema · M2 auth · M3 rbac · design system from tasks/design.md
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
16
frontend/src/components/RequireAuth.tsx
Normal file
16
frontend/src/components/RequireAuth.tsx
Normal file
@@ -0,0 +1,16 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { Navigate, useLocation } from 'react-router-dom';
|
||||
|
||||
import { useAuth } from '@/lib/auth';
|
||||
|
||||
export function RequireAuth({ children }: { children: ReactNode }) {
|
||||
const { state } = useAuth();
|
||||
const loc = useLocation();
|
||||
if (state.loading) {
|
||||
return <p className="font-mono text-xs text-text-dim p-8">Loading session…</p>;
|
||||
}
|
||||
if (!state.user) {
|
||||
return <Navigate to="/login" state={{ from: loc.pathname }} replace />;
|
||||
}
|
||||
return <>{children}</>;
|
||||
}
|
||||
39
frontend/src/components/ui/Alert.tsx
Normal file
39
frontend/src/components/ui/Alert.tsx
Normal file
@@ -0,0 +1,39 @@
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
import { cn, type Accent } from '@/lib/cn';
|
||||
|
||||
interface AlertProps {
|
||||
accent: Accent;
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
/** Optional ARIA role override; defaults to "alert" for errors. */
|
||||
role?: string;
|
||||
}
|
||||
|
||||
const ACCENT_FILL: Record<Accent, string> = {
|
||||
red: 'accent-fill-red',
|
||||
orange: 'accent-fill-orange',
|
||||
yellow: 'accent-fill-yellow',
|
||||
green: 'accent-fill-green',
|
||||
cyan: 'accent-fill-cyan',
|
||||
blue: 'accent-fill-blue',
|
||||
purple: 'accent-fill-purple',
|
||||
pink: 'accent-fill-pink',
|
||||
rose: 'accent-fill-rose',
|
||||
teal: 'accent-fill-teal',
|
||||
};
|
||||
|
||||
export function Alert({ accent, children, className, role }: AlertProps) {
|
||||
return (
|
||||
<div
|
||||
role={role ?? (accent === 'red' || accent === 'rose' ? 'alert' : 'status')}
|
||||
className={cn(
|
||||
'rounded-md border border-current/30 px-3 py-2 font-mono text-xs',
|
||||
ACCENT_FILL[accent],
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
48
frontend/src/components/ui/TextField.tsx
Normal file
48
frontend/src/components/ui/TextField.tsx
Normal file
@@ -0,0 +1,48 @@
|
||||
import { forwardRef, useId, type InputHTMLAttributes } from 'react';
|
||||
|
||||
import { cn } from '@/lib/cn';
|
||||
|
||||
interface TextFieldProps extends InputHTMLAttributes<HTMLInputElement> {
|
||||
label: string;
|
||||
hint?: string;
|
||||
errorText?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Form field with explicit label/input association via `htmlFor` / `id`.
|
||||
* The hint and error text are rendered as siblings, NOT inside the `<label>`,
|
||||
* so the accessible name of the input remains exactly the `label` prop —
|
||||
* crucial for `getByLabel(...)` selectors in Playwright.
|
||||
*/
|
||||
export const TextField = forwardRef<HTMLInputElement, TextFieldProps>(function TextField(
|
||||
{ label, hint, errorText, className, id, ...rest },
|
||||
ref,
|
||||
) {
|
||||
const fallbackId = useId();
|
||||
const inputId = id ?? fallbackId;
|
||||
return (
|
||||
<div className="block">
|
||||
<label
|
||||
htmlFor={inputId}
|
||||
className="block font-mono text-3xs font-semibold uppercase tracking-wider2 text-text-dim"
|
||||
>
|
||||
{label}
|
||||
</label>
|
||||
<input
|
||||
ref={ref}
|
||||
id={inputId}
|
||||
className={cn(
|
||||
'mt-1 w-full rounded-md border bg-bg-card px-3 py-2 font-mono text-xs text-text-bright placeholder:text-text-dim',
|
||||
errorText ? 'border-red' : 'border-border focus:border-cyan',
|
||||
'focus:outline-none',
|
||||
className,
|
||||
)}
|
||||
{...rest}
|
||||
/>
|
||||
{hint && !errorText && (
|
||||
<p className="mt-1 font-mono text-2xs text-text-dim">{hint}</p>
|
||||
)}
|
||||
{errorText && <p className="mt-1 font-mono text-2xs text-red">{errorText}</p>}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
141
frontend/src/lib/api.ts
Normal file
141
frontend/src/lib/api.ts
Normal file
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* Auth-aware fetch wrapper.
|
||||
*
|
||||
* Strategy:
|
||||
* - Access token kept in module memory (never in localStorage).
|
||||
* - Refresh token lives in an HTTPOnly cookie set by the backend.
|
||||
* - On 401, we try ONE silent refresh via /auth/refresh, retry, then give up.
|
||||
*
|
||||
* Consumers go through `apiFetch`, `apiGet`, `apiPost` helpers.
|
||||
*/
|
||||
|
||||
const BASE_URL = (import.meta.env.VITE_API_BASE_URL as string | undefined) ?? '/api/v1';
|
||||
|
||||
type AccessTokenListener = (token: string | null) => void;
|
||||
|
||||
let accessToken: string | null = null;
|
||||
const listeners = new Set<AccessTokenListener>();
|
||||
|
||||
export function setAccessToken(t: string | null) {
|
||||
accessToken = t;
|
||||
for (const l of listeners) l(t);
|
||||
}
|
||||
|
||||
export function getAccessToken(): string | null {
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
export function onAccessTokenChange(fn: AccessTokenListener): () => void {
|
||||
listeners.add(fn);
|
||||
return () => listeners.delete(fn);
|
||||
}
|
||||
|
||||
/** Returns true if the refresh succeeded and `accessToken` is updated. */
|
||||
async function silentRefresh(): Promise<boolean> {
|
||||
try {
|
||||
const res = await fetch(`${BASE_URL}/auth/refresh`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
});
|
||||
if (!res.ok) return false;
|
||||
const body = (await res.json()) as { access_token: string };
|
||||
if (!body.access_token) return false;
|
||||
setAccessToken(body.access_token);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
interface ApiOptions extends RequestInit {
|
||||
/** Skip the silent-refresh path — used by /auth/* endpoints themselves. */
|
||||
noRefresh?: boolean;
|
||||
/** Skip Authorization header — used for /setup and unauthenticated probes. */
|
||||
anonymous?: boolean;
|
||||
}
|
||||
|
||||
export async function apiFetch(path: string, opts: ApiOptions = {}): Promise<Response> {
|
||||
const headers = new Headers(opts.headers);
|
||||
headers.set('Accept', 'application/json');
|
||||
if (!headers.has('Content-Type') && opts.body && !(opts.body instanceof FormData)) {
|
||||
headers.set('Content-Type', 'application/json');
|
||||
}
|
||||
if (!opts.anonymous && accessToken) {
|
||||
headers.set('Authorization', `Bearer ${accessToken}`);
|
||||
}
|
||||
|
||||
let res = await fetch(`${BASE_URL}${path}`, {
|
||||
...opts,
|
||||
headers,
|
||||
credentials: 'include',
|
||||
});
|
||||
|
||||
if (res.status === 401 && !opts.noRefresh && !opts.anonymous) {
|
||||
const refreshed = await silentRefresh();
|
||||
if (refreshed) {
|
||||
headers.set('Authorization', `Bearer ${accessToken}`);
|
||||
res = await fetch(`${BASE_URL}${path}`, {
|
||||
...opts,
|
||||
headers,
|
||||
credentials: 'include',
|
||||
});
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
public payload: unknown,
|
||||
message?: string,
|
||||
) {
|
||||
super(message ?? `HTTP ${status}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function parseOrThrow<T>(res: Response): Promise<T> {
|
||||
if (res.status === 204) return undefined as T;
|
||||
const isJson = (res.headers.get('content-type') ?? '').includes('application/json');
|
||||
const body = isJson ? await res.json() : await res.text();
|
||||
if (!res.ok) throw new ApiError(res.status, body);
|
||||
return body as T;
|
||||
}
|
||||
|
||||
export async function apiGet<T>(path: string, opts?: ApiOptions): Promise<T> {
|
||||
return parseOrThrow<T>(await apiFetch(path, { ...opts, method: 'GET' }));
|
||||
}
|
||||
|
||||
export async function apiPost<T>(path: string, body?: unknown, opts?: ApiOptions): Promise<T> {
|
||||
return parseOrThrow<T>(
|
||||
await apiFetch(path, {
|
||||
...opts,
|
||||
method: 'POST',
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function apiPatch<T>(path: string, body?: unknown, opts?: ApiOptions): Promise<T> {
|
||||
return parseOrThrow<T>(
|
||||
await apiFetch(path, {
|
||||
...opts,
|
||||
method: 'PATCH',
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function apiPut<T>(path: string, body?: unknown, opts?: ApiOptions): Promise<T> {
|
||||
return parseOrThrow<T>(
|
||||
await apiFetch(path, {
|
||||
...opts,
|
||||
method: 'PUT',
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function apiDelete<T>(path: string, opts?: ApiOptions): Promise<T> {
|
||||
return parseOrThrow<T>(await apiFetch(path, { ...opts, method: 'DELETE' }));
|
||||
}
|
||||
125
frontend/src/lib/auth.ts
Normal file
125
frontend/src/lib/auth.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* Auth state hook + login/logout helpers.
|
||||
*
|
||||
* The hook tries a silent /auth/refresh on mount so a returning user sees
|
||||
* "logged in" without typing credentials again. If that fails, the SPA
|
||||
* renders /login.
|
||||
*/
|
||||
import { createContext, useContext, useEffect, useState } from 'react';
|
||||
|
||||
import { apiPost, getAccessToken, onAccessTokenChange, setAccessToken } from '@/lib/api';
|
||||
|
||||
export interface MeResponse {
|
||||
id: string;
|
||||
email: string;
|
||||
display_name: string | null;
|
||||
locale: string;
|
||||
is_admin: boolean;
|
||||
groups: string[];
|
||||
permissions: string[];
|
||||
}
|
||||
|
||||
export interface AuthState {
|
||||
loading: boolean;
|
||||
user: MeResponse | null;
|
||||
hasAccessToken: boolean;
|
||||
}
|
||||
|
||||
export interface AuthApi {
|
||||
state: AuthState;
|
||||
login: (email: string, password: string) => Promise<MeResponse>;
|
||||
logout: () => Promise<void>;
|
||||
reload: () => Promise<void>;
|
||||
}
|
||||
|
||||
interface LoginResponse {
|
||||
access_token: string;
|
||||
user_id: string;
|
||||
}
|
||||
|
||||
async function fetchMe(): Promise<MeResponse> {
|
||||
const { apiGet } = await import('@/lib/api');
|
||||
return apiGet<MeResponse>('/auth/me');
|
||||
}
|
||||
|
||||
export const AuthContext = createContext<AuthApi | null>(null);
|
||||
|
||||
export function useAuth(): AuthApi {
|
||||
const v = useContext(AuthContext);
|
||||
if (!v) throw new Error('useAuth must be used inside <AuthProvider>');
|
||||
return v;
|
||||
}
|
||||
|
||||
export function useProvideAuth(): AuthApi {
|
||||
const [user, setUser] = useState<MeResponse | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [hasToken, setHasToken] = useState<boolean>(getAccessToken() !== null);
|
||||
|
||||
useEffect(() => onAccessTokenChange((t) => setHasToken(t !== null)), []);
|
||||
|
||||
const reload = async () => {
|
||||
if (!getAccessToken()) {
|
||||
// Try a silent refresh — if a refresh cookie exists from a prior session.
|
||||
try {
|
||||
const r = await apiPost<{ access_token: string }>('/auth/refresh', undefined, {
|
||||
noRefresh: true,
|
||||
anonymous: true,
|
||||
});
|
||||
if (r.access_token) setAccessToken(r.access_token);
|
||||
} catch {
|
||||
/* no cookie, no big deal */
|
||||
}
|
||||
}
|
||||
if (!getAccessToken()) {
|
||||
setUser(null);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
setUser(await fetchMe());
|
||||
} catch {
|
||||
setAccessToken(null);
|
||||
setUser(null);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
await reload();
|
||||
if (!cancelled) setLoading(false);
|
||||
})();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const login = async (email: string, password: string): Promise<MeResponse> => {
|
||||
const r = await apiPost<LoginResponse>(
|
||||
'/auth/login',
|
||||
{ email, password },
|
||||
{ noRefresh: true, anonymous: true },
|
||||
);
|
||||
setAccessToken(r.access_token);
|
||||
const me = await fetchMe();
|
||||
setUser(me);
|
||||
return me;
|
||||
};
|
||||
|
||||
const logout = async () => {
|
||||
try {
|
||||
await apiPost('/auth/logout', undefined, { noRefresh: true });
|
||||
} catch {
|
||||
/* idempotent */
|
||||
}
|
||||
setAccessToken(null);
|
||||
setUser(null);
|
||||
};
|
||||
|
||||
return {
|
||||
state: { loading, user, hasAccessToken: hasToken },
|
||||
login,
|
||||
logout,
|
||||
reload,
|
||||
};
|
||||
}
|
||||
95
frontend/src/pages/LoginPage.tsx
Normal file
95
frontend/src/pages/LoginPage.tsx
Normal file
@@ -0,0 +1,95 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
|
||||
import { Alert } from '@/components/ui/Alert';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Card } from '@/components/ui/Card';
|
||||
import { SectionHeader } from '@/components/ui/SectionHeader';
|
||||
import { TextField } from '@/components/ui/TextField';
|
||||
import { ApiError, apiGet } from '@/lib/api';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
|
||||
interface SetupStatus {
|
||||
completed: boolean;
|
||||
}
|
||||
|
||||
export function LoginPage() {
|
||||
const auth = useAuth();
|
||||
const navigate = useNavigate();
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [setupNeeded, setSetupNeeded] = useState(false);
|
||||
const emailRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
apiGet<SetupStatus>('/setup', { anonymous: true })
|
||||
.then((s) => setSetupNeeded(!s.completed))
|
||||
.catch(() => setSetupNeeded(false));
|
||||
emailRef.current?.focus();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (auth.state.user) navigate('/', { replace: true });
|
||||
}, [auth.state.user, navigate]);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
try {
|
||||
await auth.login(email, password);
|
||||
navigate('/', { replace: true });
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 401) {
|
||||
setError('Invalid email or password.');
|
||||
} else if (err instanceof ApiError && err.status === 429) {
|
||||
setError('Too many attempts. Wait a minute.');
|
||||
} else {
|
||||
setError(err instanceof Error ? err.message : 'Login failed.');
|
||||
}
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-md mt-12">
|
||||
<SectionHeader prefix="Operator" highlight="Login" accent="cyan" />
|
||||
{setupNeeded && (
|
||||
<Alert accent="orange" className="mb-4">
|
||||
No admin account exists yet.{' '}
|
||||
<Link to="/setup" className="underline text-cyan">
|
||||
Run the bootstrap setup →
|
||||
</Link>
|
||||
</Alert>
|
||||
)}
|
||||
<Card accent="cyan">
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<TextField
|
||||
ref={emailRef}
|
||||
label="Email"
|
||||
type="email"
|
||||
autoComplete="username"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<TextField
|
||||
label="Password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
{error && <Alert accent="red">{error}</Alert>}
|
||||
<Button type="submit" accent="cyan" disabled={busy}>
|
||||
{busy ? 'Signing in…' : 'Sign in'}
|
||||
</Button>
|
||||
</form>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
137
frontend/src/pages/ProfilePage.tsx
Normal file
137
frontend/src/pages/ProfilePage.tsx
Normal file
@@ -0,0 +1,137 @@
|
||||
import { useState } from 'react';
|
||||
|
||||
import { Alert } from '@/components/ui/Alert';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Card } from '@/components/ui/Card';
|
||||
import { SectionHeader } from '@/components/ui/SectionHeader';
|
||||
import { Tag } from '@/components/ui/Tag';
|
||||
import { TextField } from '@/components/ui/TextField';
|
||||
import { ApiError, apiPost } from '@/lib/api';
|
||||
import { useAuth } from '@/lib/auth';
|
||||
|
||||
export function ProfilePage() {
|
||||
const { state, logout } = useAuth();
|
||||
const user = state.user!;
|
||||
const [current, setCurrent] = useState('');
|
||||
const [next, setNext] = useState('');
|
||||
const [confirm, setConfirm] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);
|
||||
|
||||
async function handleChangePassword(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setMsg(null);
|
||||
if (next !== confirm) {
|
||||
setMsg({ kind: 'err', text: 'New passwords do not match.' });
|
||||
return;
|
||||
}
|
||||
if (next.length < 8) {
|
||||
setMsg({ kind: 'err', text: 'New password must be at least 8 characters.' });
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
await apiPost('/auth/change-password', {
|
||||
current_password: current,
|
||||
new_password: next,
|
||||
});
|
||||
setMsg({ kind: 'ok', text: 'Password updated. You will be signed out for security.' });
|
||||
setCurrent('');
|
||||
setNext('');
|
||||
setConfirm('');
|
||||
setTimeout(() => logout(), 1500);
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError) {
|
||||
const payload = err.payload as { error?: string; message?: string } | null;
|
||||
setMsg({
|
||||
kind: 'err',
|
||||
text: payload?.message ?? payload?.error ?? `HTTP ${err.status}`,
|
||||
});
|
||||
} else {
|
||||
setMsg({ kind: 'err', text: err instanceof Error ? err.message : 'Update failed.' });
|
||||
}
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<SectionHeader prefix="Account" highlight="Profile" accent="cyan" />
|
||||
<div className="grid gap-4 [grid-template-columns:repeat(auto-fill,minmax(420px,1fr))]">
|
||||
<Card accent="cyan" title="Identity" sub={user.is_admin ? 'admin account' : 'operator account'}>
|
||||
<p>
|
||||
<span className="text-text-dim">email </span>
|
||||
<code className="accent-fill-cyan px-2 py-[2px] rounded-sm font-mono text-4xs">
|
||||
{user.email}
|
||||
</code>
|
||||
</p>
|
||||
<p className="mt-2">
|
||||
<span className="text-text-dim">display </span>
|
||||
<code className="accent-fill-cyan px-2 py-[2px] rounded-sm font-mono text-4xs">
|
||||
{user.display_name ?? '—'}
|
||||
</code>
|
||||
</p>
|
||||
<p className="mt-2">
|
||||
<span className="text-text-dim">locale </span>
|
||||
<code className="accent-fill-cyan px-2 py-[2px] rounded-sm font-mono text-4xs">
|
||||
{user.locale}
|
||||
</code>
|
||||
</p>
|
||||
</Card>
|
||||
|
||||
<Card accent="purple" title="Groups" sub={user.groups.length ? '' : 'no groups assigned'}>
|
||||
{user.groups.length === 0 && <p className="text-text-dim">No groups yet.</p>}
|
||||
{user.groups.map((g) => (
|
||||
<Tag key={g} accent="purple">
|
||||
{g}
|
||||
</Tag>
|
||||
))}
|
||||
</Card>
|
||||
|
||||
<Card accent="orange" title="Permissions" sub={user.permissions.length ? '' : user.is_admin ? 'admin (all)' : 'no perms'}>
|
||||
{user.is_admin && <Tag accent="orange">ADMIN — bypasses checks</Tag>}
|
||||
{user.permissions.map((p) => (
|
||||
<Tag key={p} accent="orange">
|
||||
{p}
|
||||
</Tag>
|
||||
))}
|
||||
</Card>
|
||||
|
||||
<Card accent="rose" title="Change password">
|
||||
<form onSubmit={handleChangePassword} className="space-y-3">
|
||||
<TextField
|
||||
label="Current password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
value={current}
|
||||
onChange={(e) => setCurrent(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<TextField
|
||||
label="New password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={next}
|
||||
onChange={(e) => setNext(e.target.value)}
|
||||
required
|
||||
hint="Min 8 characters."
|
||||
/>
|
||||
<TextField
|
||||
label="Confirm new password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={confirm}
|
||||
onChange={(e) => setConfirm(e.target.value)}
|
||||
required
|
||||
/>
|
||||
{msg && <Alert accent={msg.kind === 'ok' ? 'green' : 'red'}>{msg.text}</Alert>}
|
||||
<Button type="submit" accent="rose" disabled={busy}>
|
||||
{busy ? 'Updating…' : 'Update password'}
|
||||
</Button>
|
||||
</form>
|
||||
</Card>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
163
frontend/src/pages/RegisterPage.tsx
Normal file
163
frontend/src/pages/RegisterPage.tsx
Normal file
@@ -0,0 +1,163 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
|
||||
import { Alert } from '@/components/ui/Alert';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Card } from '@/components/ui/Card';
|
||||
import { SectionHeader } from '@/components/ui/SectionHeader';
|
||||
import { TextField } from '@/components/ui/TextField';
|
||||
import { ApiError, apiGet, apiPost } from '@/lib/api';
|
||||
|
||||
interface InvitationPreview {
|
||||
is_valid: boolean;
|
||||
reason: string | null;
|
||||
email_hint: string | null;
|
||||
expires_at: string;
|
||||
groups: string[];
|
||||
}
|
||||
|
||||
export function RegisterPage() {
|
||||
const [params] = useSearchParams();
|
||||
const token = params.get('token') ?? '';
|
||||
const navigate = useNavigate();
|
||||
|
||||
const [preview, setPreview] = useState<InvitationPreview | null>(null);
|
||||
const [previewError, setPreviewError] = useState<string | null>(null);
|
||||
const [email, setEmail] = useState('');
|
||||
const [displayName, setDisplayName] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirm, setConfirm] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [done, setDone] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!token) {
|
||||
setPreviewError('Missing invitation token in the URL.');
|
||||
return;
|
||||
}
|
||||
apiGet<InvitationPreview>(`/invitations/preview/${encodeURIComponent(token)}`, {
|
||||
anonymous: true,
|
||||
})
|
||||
.then((p) => {
|
||||
setPreview(p);
|
||||
if (p.email_hint) setEmail(p.email_hint);
|
||||
})
|
||||
.catch((err: unknown) =>
|
||||
setPreviewError(err instanceof Error ? err.message : 'Could not load invitation.'),
|
||||
);
|
||||
}, [token]);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
if (password !== confirm) {
|
||||
setError('Passwords do not match.');
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
await apiPost(
|
||||
`/invitations/accept/${encodeURIComponent(token)}`,
|
||||
{ email, password, display_name: displayName || undefined },
|
||||
{ anonymous: true, noRefresh: true },
|
||||
);
|
||||
setDone(true);
|
||||
setTimeout(() => navigate('/login', { replace: true }), 1500);
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError) {
|
||||
const payload = err.payload as { error?: string; message?: string } | null;
|
||||
setError(payload?.message ?? payload?.error ?? `HTTP ${err.status}`);
|
||||
} else {
|
||||
setError(err instanceof Error ? err.message : 'Registration failed.');
|
||||
}
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (done) {
|
||||
return (
|
||||
<div className="mx-auto max-w-md mt-12">
|
||||
<Alert accent="green">Account created. Redirecting to login…</Alert>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (previewError) {
|
||||
return (
|
||||
<div className="mx-auto max-w-md mt-12">
|
||||
<Alert accent="red">{previewError}</Alert>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!preview) {
|
||||
return (
|
||||
<div className="mx-auto max-w-md mt-12">
|
||||
<Alert accent="cyan">Loading invitation…</Alert>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!preview.is_valid) {
|
||||
return (
|
||||
<div className="mx-auto max-w-md mt-12">
|
||||
<Alert accent="red">
|
||||
This invitation is not usable: <code>{preview.reason}</code>
|
||||
</Alert>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-xl mt-12">
|
||||
<SectionHeader
|
||||
prefix="Account"
|
||||
highlight="Registration"
|
||||
accent="green"
|
||||
description="Welcome — pick a password to join the platform."
|
||||
/>
|
||||
<Card accent="green">
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<TextField
|
||||
label="Email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
hint={preview.email_hint ? `Invited as ${preview.email_hint}` : undefined}
|
||||
required
|
||||
/>
|
||||
<TextField
|
||||
label="Display name (optional)"
|
||||
value={displayName}
|
||||
onChange={(e) => setDisplayName(e.target.value)}
|
||||
/>
|
||||
<TextField
|
||||
label="Password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<TextField
|
||||
label="Confirm password"
|
||||
type="password"
|
||||
value={confirm}
|
||||
onChange={(e) => setConfirm(e.target.value)}
|
||||
required
|
||||
/>
|
||||
{preview.groups.length > 0 && (
|
||||
<Alert accent="cyan">
|
||||
You will be added to: {preview.groups.map((g) => `[${g}]`).join(' ')}
|
||||
</Alert>
|
||||
)}
|
||||
{error && <Alert accent="red">{error}</Alert>}
|
||||
<Button type="submit" accent="green" disabled={busy}>
|
||||
{busy ? 'Creating account…' : 'Create account'}
|
||||
</Button>
|
||||
</form>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
144
frontend/src/pages/SetupPage.tsx
Normal file
144
frontend/src/pages/SetupPage.tsx
Normal file
@@ -0,0 +1,144 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
|
||||
import { Alert } from '@/components/ui/Alert';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Card } from '@/components/ui/Card';
|
||||
import { SectionHeader } from '@/components/ui/SectionHeader';
|
||||
import { TextField } from '@/components/ui/TextField';
|
||||
import { ApiError, apiGet, apiPost } from '@/lib/api';
|
||||
|
||||
interface SetupStatus {
|
||||
completed: boolean;
|
||||
}
|
||||
|
||||
export function SetupPage() {
|
||||
const navigate = useNavigate();
|
||||
const [token, setToken] = useState('');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirm, setConfirm] = useState('');
|
||||
const [displayName, setDisplayName] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [done, setDone] = useState(false);
|
||||
const [completed, setCompleted] = useState<boolean | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
apiGet<SetupStatus>('/setup', { anonymous: true })
|
||||
.then((s) => setCompleted(s.completed))
|
||||
.catch(() => setCompleted(null));
|
||||
}, []);
|
||||
|
||||
if (completed) {
|
||||
return (
|
||||
<div className="mx-auto max-w-md mt-12">
|
||||
<SectionHeader prefix="Setup" highlight="Already Done" accent="green" />
|
||||
<Card accent="green">
|
||||
<p>An admin account already exists on this instance.</p>
|
||||
<Link to="/login" className="mt-3 inline-block underline text-cyan">
|
||||
Go to login →
|
||||
</Link>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
if (password !== confirm) {
|
||||
setError('Passwords do not match.');
|
||||
return;
|
||||
}
|
||||
if (password.length < 8) {
|
||||
setError('Password must be at least 8 characters.');
|
||||
return;
|
||||
}
|
||||
setBusy(true);
|
||||
try {
|
||||
await apiPost(
|
||||
'/setup',
|
||||
{
|
||||
install_token: token.trim(),
|
||||
email,
|
||||
password,
|
||||
display_name: displayName || undefined,
|
||||
},
|
||||
{ anonymous: true, noRefresh: true },
|
||||
);
|
||||
setDone(true);
|
||||
setTimeout(() => navigate('/login', { replace: true }), 1500);
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError) {
|
||||
const payload = err.payload as { error?: string; message?: string } | null;
|
||||
setError(payload?.message ?? payload?.error ?? `HTTP ${err.status}`);
|
||||
} else {
|
||||
setError(err instanceof Error ? err.message : 'Setup failed.');
|
||||
}
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (done) {
|
||||
return (
|
||||
<div className="mx-auto max-w-md mt-12">
|
||||
<Alert accent="green">Admin created. Redirecting to login…</Alert>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-xl mt-12">
|
||||
<SectionHeader
|
||||
prefix="Bootstrap"
|
||||
highlight="Setup"
|
||||
accent="orange"
|
||||
description="One-shot — paste the install token from the api container logs to create the first admin."
|
||||
/>
|
||||
<Card accent="orange">
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<TextField
|
||||
label="Install token"
|
||||
value={token}
|
||||
onChange={(e) => setToken(e.target.value)}
|
||||
required
|
||||
hint="Found in `make logs-api` (banner: 'INSTALL TOKEN: …')."
|
||||
/>
|
||||
<TextField
|
||||
label="Admin email"
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
<TextField
|
||||
label="Display name (optional)"
|
||||
value={displayName}
|
||||
onChange={(e) => setDisplayName(e.target.value)}
|
||||
/>
|
||||
<TextField
|
||||
label="Password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
hint="Min 8 characters."
|
||||
/>
|
||||
<TextField
|
||||
label="Confirm password"
|
||||
type="password"
|
||||
value={confirm}
|
||||
onChange={(e) => setConfirm(e.target.value)}
|
||||
required
|
||||
/>
|
||||
{error && <Alert accent="red">{error}</Alert>}
|
||||
<Button type="submit" accent="orange" disabled={busy}>
|
||||
{busy ? 'Creating admin…' : 'Create admin'}
|
||||
</Button>
|
||||
</form>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user