feat: multi-user auth with per-user media isolation

Introduce username/password authentication with admin and user roles.
Each user gets their own media directory under /photos/{username}/ with
isolated photos, folders, heaps, and tags. Admins manage users and
observe the full library from a dedicated Settings page.

Backend:
- User model with bcrypt passwords and JWT access/refresh tokens
- Auth router (login, refresh, setup, change-password, status)
- Admin router (user CRUD with last-admin protection)
- user_id FK added to photos, folders, source_roots, heaps, tags
- All data routers scoped by authenticated user
- Scanner inherits user_id from source root owner
- Thumbnails stored under user-prefixed paths for isolation
- Library endpoints accept ?scope=global for admin cross-user view
- Alembic migration 0009 with data migration for existing installs
- Defensive bootstrap.py handles fresh vs existing DB startup

Frontend:
- AuthContext with token lifecycle, auto-refresh, login/logout
- Login page, first-run setup page, auth gate in App.tsx
- Bearer token interceptor on all API requests
- User identity + logout in left sidebar
- Admin-only Settings page with Library Management and Users tabs
- UserManagement panel (add, edit role, reset password, deactivate)
- Settings shows global stats across all users for admin
- Filter bar, right sidebar, keyboard hints hidden on settings page

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-12 21:46:52 +02:00
parent 03a4c75e3e
commit 348e9c3585
40 changed files with 2313 additions and 440 deletions

View File

@@ -15,17 +15,19 @@ import { KeyboardHints } from './components/KeyboardHints'
import { PreviewView } from './components/preview/PreviewView'
import { FilterBar } from './components/filter/FilterBar'
import { DiscardActionBar } from './components/discard/DiscardActionBar'
import { SettingsDialog } from './components/dialogs/SettingsDialog'
import { SettingsPage } from './components/dialogs/SettingsDialog'
import { usePhotoStore } from './store/photoStore'
import { useFilterStore } from './store/filterStore'
import { useKeyboardShortcuts } from './hooks/useKeyboardShortcuts'
import { useFilterUrlSync } from './hooks/useFilterUrlSync'
import { usePhotosQuery } from './hooks/usePhotosQuery'
import { AuthProvider, useAuth } from './contexts/AuthContext'
import { LoginPage } from './components/auth/LoginPage'
import { SetupPage } from './components/auth/SetupPage'
function App() {
function MainApp() {
const [leftSidebarOpen, setLeftSidebarOpen] = useState(true)
const [rightSidebarOpen, setRightSidebarOpen] = useState(true)
const [settingsOpen, setSettingsOpen] = useState(false)
const viewMode = usePhotoStore((state) => state.viewMode)
const currentSection = useFilterStore((s) => s.currentSection)
@@ -44,13 +46,13 @@ function App() {
getFirstPhotoId: () => allPhotos?.[0]?.id ?? null,
})
// Settings page is a full-page section — hide filter bar, right sidebar,
// and keyboard hints when it's active.
const isSettings = currentSection === 'settings'
// Right sidebar stays open by default and shows whatever's selected
// (or an empty state if nothing is). User can still toggle it manually.
// Note: deliberately NOT gated on viewMode — the preview overlay sits
// on top with z-[1000], so leaving the sidebar mounted underneath
// costs nothing visually and avoids the collapse-then-reopen layout
// shift the user would otherwise see every time they exit preview.
const showRightSidebar = rightSidebarOpen
const showRightSidebar = rightSidebarOpen && !isSettings
return (
<div className="flex flex-col h-screen bg-bg text-text">
@@ -70,7 +72,6 @@ function App() {
>
<LeftSidebar
onCollapse={() => setLeftSidebarOpen(false)}
onOpenSettings={() => setSettingsOpen(true)}
/>
</div>
@@ -79,14 +80,12 @@ function App() {
* across the sidebar. relative so the KeyboardHints overlay
* centers against this column, not the viewport. */}
<div className="relative flex min-w-0 flex-1 flex-col">
<FilterBar />
<DiscardActionBar />
{!isSettings && <FilterBar />}
{!isSettings && <DiscardActionBar />}
<div className="flex-1 overflow-auto">
{/* Section-level routing. The Map view replaces the timeline
* with a Leaflet map of GPS-tagged photos; Duplicates gets its
* own grouped grid; everything else falls through to the
* filter-driven Timeline. */}
{currentSection === 'map' ? (
{currentSection === 'settings' ? (
<SettingsPage />
) : currentSection === 'map' ? (
<MapView />
) : currentSection === 'duplicates' ? (
<DuplicatesView />
@@ -102,10 +101,7 @@ function App() {
<Timeline />
)}
</div>
{/* Floating keyboard hints — bottom-center of the main column,
* glassy. Mounted here so it's centered against the timeline,
* not the viewport (which would be offset by the sidebars). */}
<KeyboardHints />
{!isSettings && <KeyboardHints />}
</div>
{/* Right Sidebar */}
@@ -127,13 +123,33 @@ function App() {
{/* Preview overlay — covers TopBar when active */}
{viewMode === 'preview' && <PreviewView />}
{/* Settings panel — admin/maintenance actions */}
<SettingsDialog
isOpen={settingsOpen}
onClose={() => setSettingsOpen(false)}
/>
</div>
)
}
/** Auth-gated shell: shows setup, login, or the main app. */
function App() {
return (
<AuthProvider>
<AuthGate />
</AuthProvider>
)
}
function AuthGate() {
const { user, isLoading, needsSetup } = useAuth()
if (isLoading) {
return (
<div className="flex min-h-screen items-center justify-center bg-bg">
<div className="text-text-muted">Loading&hellip;</div>
</div>
)
}
if (needsSetup) return <SetupPage />
if (!user) return <LoginPage />
return <MainApp />
}
export default App

View File

@@ -0,0 +1,336 @@
import { useState, useEffect, useCallback } from 'react'
import { Plus, Pencil, UserX, Shield, User as UserIcon } from 'lucide-react'
import { admin, type AdminUser } from '../../services/api'
export function UserManagement() {
const [users, setUsers] = useState<AdminUser[]>([])
const [loading, setLoading] = useState(true)
const [showCreate, setShowCreate] = useState(false)
const [editingUser, setEditingUser] = useState<AdminUser | null>(null)
const [error, setError] = useState<string | null>(null)
const fetchUsers = useCallback(async () => {
try {
const data = await admin.listUsers()
setUsers(data.users)
} catch {
setError('Failed to load users.')
} finally {
setLoading(false)
}
}, [])
useEffect(() => {
fetchUsers()
}, [fetchUsers])
if (loading) {
return <div className="p-4 text-sm text-text-muted">Loading users&hellip;</div>
}
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold text-text">Users</h3>
<button
onClick={() => setShowCreate(true)}
className="flex items-center gap-1 rounded bg-accent px-2 py-1 text-xs text-white hover:bg-accent/80"
>
<Plus className="h-3 w-3" />
Add User
</button>
</div>
{error && (
<div className="rounded bg-red-900/30 px-3 py-2 text-xs text-red-300">
{error}
</div>
)}
<table className="w-full text-xs">
<thead>
<tr className="border-b border-border text-left text-text-muted">
<th className="pb-1 pr-4">Username</th>
<th className="pb-1 pr-4">Role</th>
<th className="pb-1 pr-4">Photos</th>
<th className="pb-1 pr-4">Status</th>
<th className="pb-1">Actions</th>
</tr>
</thead>
<tbody>
{users.map((u) => (
<tr key={u.id} className="border-b border-border/50">
<td className="py-1.5 pr-4">
<div className="flex items-center gap-1.5">
{u.role === 'admin' ? (
<Shield className="h-3 w-3 text-accent" />
) : (
<UserIcon className="h-3 w-3 text-text-muted" />
)}
<span className="text-text">{u.username}</span>
</div>
</td>
<td className="py-1.5 pr-4 text-text-muted">{u.role}</td>
<td className="py-1.5 pr-4 text-text-muted">
{u.photo_count.toLocaleString()}
</td>
<td className="py-1.5 pr-4">
<span
className={
u.is_active
? 'text-green-400'
: 'text-red-400'
}
>
{u.is_active ? 'Active' : 'Inactive'}
</span>
</td>
<td className="py-1.5">
<div className="flex gap-1">
<button
onClick={() => setEditingUser(u)}
className="rounded p-1 text-text-muted hover:bg-bg hover:text-text"
title="Edit user"
>
<Pencil className="h-3 w-3" />
</button>
{u.is_active && (
<button
onClick={async () => {
if (!confirm(`Deactivate user "${u.username}"? Their photos will be preserved.`)) return
try {
await admin.deleteUser(u.id)
fetchUsers()
} catch (err: any) {
setError(err.response?.data?.detail ?? 'Failed to deactivate user.')
}
}}
className="rounded p-1 text-text-muted hover:bg-bg hover:text-red-400"
title="Deactivate user"
>
<UserX className="h-3 w-3" />
</button>
)}
</div>
</td>
</tr>
))}
</tbody>
</table>
{showCreate && (
<CreateUserModal
onClose={() => setShowCreate(false)}
onCreated={() => {
setShowCreate(false)
fetchUsers()
}}
/>
)}
{editingUser && (
<EditUserModal
user={editingUser}
onClose={() => setEditingUser(null)}
onSaved={() => {
setEditingUser(null)
fetchUsers()
}}
/>
)}
</div>
)
}
// ── Create User Modal ──────────────────────────────────────────────────
function CreateUserModal({
onClose,
onCreated,
}: {
onClose: () => void
onCreated: () => void
}) {
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [role, setRole] = useState<'user' | 'admin'>('user')
const [error, setError] = useState<string | null>(null)
const [loading, setLoading] = useState(false)
const handleSubmit = async () => {
setError(null)
setLoading(true)
try {
await admin.createUser({ username: username.trim(), password, role })
onCreated()
} catch (err: any) {
setError(err.response?.data?.detail ?? 'Failed to create user.')
} finally {
setLoading(false)
}
}
return (
<ModalOverlay onClose={onClose} title="Add User">
{error && (
<div className="rounded bg-red-900/30 px-3 py-2 text-xs text-red-300">
{error}
</div>
)}
<div className="space-y-3">
<Field label="Username">
<input
value={username}
onChange={(e) => setUsername(e.target.value)}
className="w-full rounded border border-border bg-bg px-2 py-1 text-xs text-text outline-none focus:border-accent"
autoFocus
/>
</Field>
<Field label="Password">
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full rounded border border-border bg-bg px-2 py-1 text-xs text-text outline-none focus:border-accent"
/>
</Field>
<Field label="Role">
<select
value={role}
onChange={(e) => setRole(e.target.value as 'user' | 'admin')}
className="rounded border border-border bg-bg px-2 py-1 text-xs text-text outline-none focus:border-accent"
>
<option value="user">User</option>
<option value="admin">Admin</option>
</select>
</Field>
</div>
<div className="mt-4 flex justify-end gap-2">
<button
onClick={onClose}
className="rounded border border-border px-3 py-1 text-xs text-text hover:bg-bg"
>
Cancel
</button>
<button
onClick={handleSubmit}
disabled={loading}
className="rounded bg-accent px-3 py-1 text-xs text-white hover:bg-accent/80 disabled:opacity-50"
>
{loading ? 'Creating\u2026' : 'Create'}
</button>
</div>
</ModalOverlay>
)
}
// ── Edit User Modal ────────────────────────────────────────────────────
function EditUserModal({
user,
onClose,
onSaved,
}: {
user: AdminUser
onClose: () => void
onSaved: () => void
}) {
const [role, setRole] = useState(user.role)
const [newPassword, setNewPassword] = useState('')
const [error, setError] = useState<string | null>(null)
const [loading, setLoading] = useState(false)
const handleSubmit = async () => {
setError(null)
setLoading(true)
try {
const data: { role?: string; new_password?: string } = {}
if (role !== user.role) data.role = role
if (newPassword) data.new_password = newPassword
if (Object.keys(data).length > 0) {
await admin.updateUser(user.id, data)
}
onSaved()
} catch (err: any) {
setError(err.response?.data?.detail ?? 'Failed to update user.')
} finally {
setLoading(false)
}
}
return (
<ModalOverlay onClose={onClose} title={`Edit: ${user.username}`}>
{error && (
<div className="rounded bg-red-900/30 px-3 py-2 text-xs text-red-300">
{error}
</div>
)}
<div className="space-y-3">
<Field label="Role">
<select
value={role}
onChange={(e) => setRole(e.target.value as 'user' | 'admin')}
className="rounded border border-border bg-bg px-2 py-1 text-xs text-text outline-none focus:border-accent"
>
<option value="user">User</option>
<option value="admin">Admin</option>
</select>
</Field>
<Field label="New Password (leave blank to keep current)">
<input
type="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
className="w-full rounded border border-border bg-bg px-2 py-1 text-xs text-text outline-none focus:border-accent"
placeholder="Unchanged"
/>
</Field>
</div>
<div className="mt-4 flex justify-end gap-2">
<button
onClick={onClose}
className="rounded border border-border px-3 py-1 text-xs text-text hover:bg-bg"
>
Cancel
</button>
<button
onClick={handleSubmit}
disabled={loading}
className="rounded bg-accent px-3 py-1 text-xs text-white hover:bg-accent/80 disabled:opacity-50"
>
{loading ? 'Saving\u2026' : 'Save'}
</button>
</div>
</ModalOverlay>
)
}
// ── Shared helpers ─────────────────────────────────────────────────────
function ModalOverlay({
onClose: _onClose,
title,
children,
}: {
onClose: () => void
title: string
children: React.ReactNode
}) {
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50" onClick={_onClose}>
<div className="w-full max-w-sm rounded-lg border border-border bg-surface p-5 shadow-xl" onClick={(e) => e.stopPropagation()}>
<h4 className="mb-3 text-sm font-semibold text-text">{title}</h4>
{children}
</div>
</div>
)
}
function Field({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="space-y-1">
<label className="block text-[11px] text-text-muted">{label}</label>
{children}
</div>
)
}

View File

@@ -0,0 +1,81 @@
import { useState, type FormEvent } from 'react'
import { useAuth } from '../../contexts/AuthContext'
export function LoginPage() {
const { login } = useAuth()
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState<string | null>(null)
const [loading, setLoading] = useState(false)
const handleSubmit = async (e: FormEvent) => {
e.preventDefault()
setError(null)
setLoading(true)
try {
await login(username, password)
} catch (err: any) {
setError(
err.response?.data?.detail ?? 'Unable to sign in. Check your credentials.',
)
} finally {
setLoading(false)
}
}
return (
<div className="flex min-h-screen items-center justify-center bg-bg px-4">
<form
onSubmit={handleSubmit}
className="w-full max-w-sm space-y-5 rounded-lg border border-border bg-surface p-8 shadow-xl"
>
<h1 className="text-center text-xl font-semibold text-text">
Sign in to Mulita
</h1>
{error && (
<div className="rounded bg-red-900/30 px-3 py-2 text-sm text-red-300">
{error}
</div>
)}
<div className="space-y-1">
<label htmlFor="login-user" className="block text-sm text-text-muted">
Username
</label>
<input
id="login-user"
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
autoFocus
className="w-full rounded border border-border bg-bg px-3 py-2 text-sm text-text outline-none focus:border-accent"
/>
</div>
<div className="space-y-1">
<label htmlFor="login-pass" className="block text-sm text-text-muted">
Password
</label>
<input
id="login-pass"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="w-full rounded border border-border bg-bg px-3 py-2 text-sm text-text outline-none focus:border-accent"
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full rounded bg-accent px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-accent/80 disabled:opacity-50"
>
{loading ? 'Signing in\u2026' : 'Sign In'}
</button>
</form>
</div>
)
}

View File

@@ -0,0 +1,119 @@
import { useState, type FormEvent } from 'react'
import { useAuth } from '../../contexts/AuthContext'
import api from '../../services/api'
export function SetupPage() {
const { onSetupComplete } = useAuth()
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const [error, setError] = useState<string | null>(null)
const [loading, setLoading] = useState(false)
const handleSubmit = async (e: FormEvent) => {
e.preventDefault()
setError(null)
if (password !== confirmPassword) {
setError('Passwords do not match.')
return
}
if (password.length < 6) {
setError('Password must be at least 6 characters.')
return
}
if (username.trim().length < 2) {
setError('Username must be at least 2 characters.')
return
}
setLoading(true)
try {
const res = await api.post('/auth/setup', {
username: username.trim(),
password,
})
const { access_token, refresh_token } = res.data
await onSetupComplete(access_token, refresh_token)
} catch (err: any) {
setError(
err.response?.data?.detail ?? 'Setup failed. Please try again.',
)
} finally {
setLoading(false)
}
}
return (
<div className="flex min-h-screen items-center justify-center bg-bg px-4">
<form
onSubmit={handleSubmit}
className="w-full max-w-sm space-y-5 rounded-lg border border-border bg-surface p-8 shadow-xl"
>
<div className="space-y-1 text-center">
<h1 className="text-xl font-semibold text-text">Welcome to Mulita</h1>
<p className="text-sm text-text-muted">
Create your admin account to get started.
</p>
</div>
{error && (
<div className="rounded bg-red-900/30 px-3 py-2 text-sm text-red-300">
{error}
</div>
)}
<div className="space-y-1">
<label htmlFor="setup-user" className="block text-sm text-text-muted">
Username
</label>
<input
id="setup-user"
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
required
autoFocus
className="w-full rounded border border-border bg-bg px-3 py-2 text-sm text-text outline-none focus:border-accent"
/>
</div>
<div className="space-y-1">
<label htmlFor="setup-pass" className="block text-sm text-text-muted">
Password
</label>
<input
id="setup-pass"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
className="w-full rounded border border-border bg-bg px-3 py-2 text-sm text-text outline-none focus:border-accent"
/>
</div>
<div className="space-y-1">
<label htmlFor="setup-confirm" className="block text-sm text-text-muted">
Confirm Password
</label>
<input
id="setup-confirm"
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
required
className="w-full rounded border border-border bg-bg px-3 py-2 text-sm text-text outline-none focus:border-accent"
/>
</div>
<button
type="submit"
disabled={loading}
className="w-full rounded bg-accent px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-accent/80 disabled:opacity-50"
>
{loading ? 'Creating account\u2026' : 'Create Admin Account'}
</button>
</form>
</div>
)
}

View File

@@ -1,6 +1,5 @@
import { useEffect, useState, useCallback, useRef } from 'react'
import {
X,
RefreshCw,
Wrench,
Film,
@@ -15,6 +14,7 @@ import {
Sparkles,
Activity,
FolderSearch,
Shield,
} from 'lucide-react'
import clsx from 'clsx'
import { useQuery, useQueryClient } from '@tanstack/react-query'
@@ -26,6 +26,8 @@ import {
type WorkerStatus,
} from '../../services/api'
import { toast } from '../ToastContainer'
import { useAuth } from '../../contexts/AuthContext'
import { UserManagement } from '../admin/UserManagement'
// React Query keys for the settings panels. Kept here (not in a shared
// hook module) since they're internal to this dialog and used by the
@@ -40,24 +42,22 @@ const SETTINGS_SCAN_STATUS_KEY = ['settings', 'scan-status'] as const
// the grid renders from. Imported via the canonical hook key.
import { DUPLICATE_GROUPS_QUERY_KEY } from '../../hooks/useDuplicateGroupsQuery'
interface SettingsDialogProps {
isOpen: boolean
onClose: () => void
}
type SettingsTab = 'library' | 'users'
const TABS: { id: SettingsTab; label: string; adminOnly?: boolean }[] = [
{ id: 'library', label: 'Library Management' },
{ id: 'users', label: 'Users', adminOnly: true },
]
/**
* Catch-all "settings + admin" panel. Currently exposes the maintenance
* endpoints exposed by /api/v1/library/maintenance/* — regenerate
* thumbnails (with filters), run the data-integrity cleanup, and trigger
* a full library re-scan. The thumbnail stats block is the entry point
* users will look at to understand what's going on after a scan.
*
* Each action is gated by an in-flight flag so double-clicks don't
* stack background jobs, and the stats block re-fetches whenever the
* dialog opens or after any action completes.
* Full-page settings view with tabbed navigation. Replaces the old
* modal dialog — renders as a top-level section in the main content
* area (like Timeline or MapView).
*/
export function SettingsDialog({ isOpen, onClose }: SettingsDialogProps) {
export function SettingsPage() {
const { isAdmin } = useAuth()
const queryClient = useQueryClient()
const [activeTab, setActiveTab] = useState<SettingsTab>('library')
const [showAllErrors, setShowAllErrors] = useState(false)
// One key per action so each button has its own spinner without
// blocking the others.
@@ -65,67 +65,45 @@ export function SettingsDialog({ isOpen, onClose }: SettingsDialogProps) {
// All four panels fetch through React Query so cached data shows
// instantly on reopen while a background refetch updates the numbers.
// `enabled: isOpen` avoids firing requests while the dialog is closed,
// but the cache entries survive between opens (default gcTime = 5m).
// All queries use scope=global so the admin sees cross-user totals.
const thumbStatsQuery = useQuery({
queryKey: SETTINGS_THUMB_STATS_KEY,
queryFn: library.maintenance.thumbnailStats,
enabled: isOpen,
// Treat as stale immediately so reopening the dialog triggers a
// background refetch on top of the cached view.
queryFn: () => library.maintenance.thumbnailStats('global'),
staleTime: 0,
})
const libStatsQuery = useQuery({
queryKey: SETTINGS_LIB_STATS_KEY,
queryFn: library.stats,
enabled: isOpen,
queryFn: () => library.stats('global'),
staleTime: 0,
})
// Worker status polls every 5s while the dialog is open — `refetchInterval`
// replaces the old setInterval loop. Missing-stats is relatively cheap
// but shares the same 5s rhythm to keep the orphan banner live.
const workerStatusQuery = useQuery({
queryKey: SETTINGS_WORKER_STATUS_KEY,
queryFn: library.maintenance.workerStatus,
enabled: isOpen,
refetchInterval: isOpen ? 5000 : false,
queryFn: () => library.maintenance.workerStatus('global'),
refetchInterval: 5000,
staleTime: 0,
})
const missingStatsQuery = useQuery({
queryKey: SETTINGS_MISSING_STATS_KEY,
queryFn: library.maintenance.missingStats,
enabled: isOpen,
refetchInterval: isOpen ? 5000 : false,
refetchInterval: 5000,
staleTime: 0,
})
// Pipeline progress polls on the same 5s cadence as the worker status
// so both cards update together. Cheap query — ten COUNT(*)s on
// indexed columns.
const pipelineStatsQuery = useQuery({
queryKey: SETTINGS_PIPELINE_STATS_KEY,
queryFn: library.maintenance.pipelineStats,
enabled: isOpen,
refetchInterval: isOpen ? 5000 : false,
queryFn: () => library.maintenance.pipelineStats('global'),
refetchInterval: 5000,
staleTime: 0,
})
// Scan status — polls fast (2s) so the progress bar feels live during
// a scan, and slow (15s) when idle to cut chatter. `isScanning` is
// read from the latest fetched value so the cadence flips on its own
// the moment a scan kicks off or finishes.
const scanStatusQuery = useQuery<ScanStatus>({
queryKey: SETTINGS_SCAN_STATUS_KEY,
queryFn: library.scanStatus,
enabled: isOpen,
refetchInterval: (q) =>
isOpen ? ((q.state.data as ScanStatus | undefined)?.is_scanning ? 2000 : 15000) : false,
(q.state.data as ScanStatus | undefined)?.is_scanning ? 2000 : 15000,
staleTime: 0,
})
// Duplicates: shares the cache with DuplicatesView so a regroup
// triggered from Settings updates the grid view immediately.
const duplicatesQuery = useQuery({
queryKey: DUPLICATE_GROUPS_QUERY_KEY,
queryFn: library.duplicates.groups,
enabled: isOpen,
queryKey: [...DUPLICATE_GROUPS_QUERY_KEY, 'global'],
queryFn: () => library.duplicates.groups('global'),
staleTime: 0,
})
@@ -170,29 +148,17 @@ export function SettingsDialog({ isOpen, onClose }: SettingsDialogProps) {
// Surface fetch errors once (React Query de-dupes retries but we still
// want a single toast so the user knows something went wrong).
useEffect(() => {
if (!isOpen) return
if (thumbStatsQuery.error || libStatsQuery.error) {
console.error('Failed to load settings stats', thumbStatsQuery.error ?? libStatsQuery.error)
toast.error('Could not load library stats')
}
}, [isOpen, thumbStatsQuery.error, libStatsQuery.error])
}, [thumbStatsQuery.error, libStatsQuery.error])
useEffect(() => {
if (!isOpen) return
if (workerStatusQuery.error || missingStatsQuery.error) {
console.error('Failed to load worker status', workerStatusQuery.error ?? missingStatsQuery.error)
toast.error('Could not load worker status')
}
}, [isOpen, workerStatusQuery.error, missingStatsQuery.error])
// Esc closes.
useEffect(() => {
if (!isOpen) return
const handler = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose()
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
}, [isOpen, onClose])
}, [workerStatusQuery.error, missingStatsQuery.error])
const runAction = useCallback(
async <T,>(
@@ -229,39 +195,40 @@ export function SettingsDialog({ isOpen, onClose }: SettingsDialogProps) {
) =>
runAction(
key,
() => library.maintenance.regenerateThumbnails(body),
() => library.maintenance.regenerateThumbnails(body, 'global'),
'Regeneration queued',
(r) => `${r.queued} photos queued, ${r.cleared_dirs} thumb dirs cleared`
),
[runAction]
)
if (!isOpen) return null
const visibleTabs = TABS.filter((t) => !t.adminOnly || isAdmin)
return (
<div className="fixed inset-0 z-[2000]">
<div
className="absolute inset-0 bg-black/60 backdrop-blur-sm"
onClick={onClose}
/>
<div className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2">
<div className="relative z-10 flex max-h-[85vh] w-[640px] flex-col rounded-lg border border-border bg-surface shadow-2xl">
{/* Header */}
<div className="flex items-center justify-between border-b border-border px-5 py-3">
<h2 className="text-base font-semibold text-text">Settings</h2>
<button
onClick={onClose}
className="rounded p-1 text-text-muted hover:bg-surface-2 hover:text-text"
title="Close (Esc)"
>
<X className="h-4 w-4" />
</button>
</div>
<div className="flex h-full flex-col">
{/* Tab bar */}
<div className="flex items-center gap-1 border-b border-border bg-surface px-4 py-1.5">
{visibleTabs.map((tab) => (
<button
key={tab.id}
onClick={() => setActiveTab(tab.id)}
className={clsx(
'rounded px-3 py-1 text-xs font-medium transition-colors',
activeTab === tab.id
? 'bg-primary/20 text-primary'
: 'text-text-muted hover:bg-surface-2 hover:text-text',
)}
>
{tab.label}
</button>
))}
</div>
<div className="flex-1 overflow-y-auto p-5">
{/* ----------------------------------------------------- */}
{/* Library overview */}
{/* ----------------------------------------------------- */}
{/* Tab content */}
<div className="flex-1 overflow-y-auto p-5">
<div className="mx-auto max-w-2xl">
{activeTab === 'library' && (<>
<Section
icon={<Database className="h-4 w-4" />}
title="Library"
@@ -334,9 +301,6 @@ export function SettingsDialog({ isOpen, onClose }: SettingsDialogProps) {
</div>
</Section>
{/* ----------------------------------------------------- */}
{/* Pipeline progress — per-stage done/total */}
{/* ----------------------------------------------------- */}
<Section
icon={<Activity className="h-4 w-4" />}
title="Pipeline progress"
@@ -379,9 +343,6 @@ export function SettingsDialog({ isOpen, onClose }: SettingsDialogProps) {
)}
</Section>
{/* ----------------------------------------------------- */}
{/* Duplicate detection */}
{/* ----------------------------------------------------- */}
<Section
icon={<Copy className="h-4 w-4" />}
title="Duplicates"
@@ -433,9 +394,7 @@ export function SettingsDialog({ isOpen, onClose }: SettingsDialogProps) {
</div>
</Section>
{/* ----------------------------------------------------- */}
{/* Thumbnail maintenance */}
{/* ----------------------------------------------------- */}
<Section
icon={<ImageIcon className="h-4 w-4" />}
title="Thumbnails"
@@ -524,9 +483,6 @@ export function SettingsDialog({ isOpen, onClose }: SettingsDialogProps) {
</div>
</Section>
{/* ----------------------------------------------------- */}
{/* Worker fleet diagnostics */}
{/* ----------------------------------------------------- */}
<Section
icon={<Cpu className="h-4 w-4" />}
title="Workers"
@@ -848,9 +804,6 @@ export function SettingsDialog({ isOpen, onClose }: SettingsDialogProps) {
)}
</Section>
{/* ----------------------------------------------------- */}
{/* Data integrity */}
{/* ----------------------------------------------------- */}
<Section
icon={<Wrench className="h-4 w-4" />}
title="Maintenance"
@@ -876,7 +829,17 @@ export function SettingsDialog({ isOpen, onClose }: SettingsDialogProps) {
</ActionButton>
</div>
</Section>
</div>
</>)}
{activeTab === 'users' && isAdmin && (
<Section
icon={<Shield className="h-4 w-4" />}
title="User Management"
>
<UserManagement />
</Section>
)}
</div>
</div>
</div>

View File

@@ -20,6 +20,9 @@ import {
Users,
Eye,
EyeOff,
User as UserIcon,
LogOut,
Shield,
} from 'lucide-react'
import clsx from 'clsx'
import { sourceFolders, photos as photosApi, type FolderTreeNode } from '../../services/api'
@@ -40,6 +43,7 @@ import {
import { registerUndoable } from '../../store/undoStore'
import type { Photo } from '../../types/photo'
import { DeleteFolderDialog } from '../dialogs/DeleteFolderDialog'
import { useAuth } from '../../contexts/AuthContext'
interface TreeItem {
id: string
@@ -55,10 +59,10 @@ interface TreeItem {
interface LeftSidebarProps {
onCollapse: () => void
onOpenSettings: () => void
}
export function LeftSidebar({ onCollapse, onOpenSettings }: LeftSidebarProps) {
export function LeftSidebar({ onCollapse }: LeftSidebarProps) {
const { user, isAdmin, logout } = useAuth()
const [expandedItems, setExpandedItems] = useState<Set<string>>(new Set(['library', 'folders', 'heaps']))
// Inline rename state for source-root rows. Stores the id being edited
// and the draft name. Double-click a folder row to start.
@@ -797,17 +801,40 @@ export function LeftSidebar({ onCollapse, onOpenSettings }: LeftSidebarProps) {
<HeapsPanel />
</div>
{/* Settings entry point — pinned to the bottom of the panel so it
* sits out of the way of the library tree but is always reachable. */}
<div className="border-t border-border p-1.5">
<button
onClick={onOpenSettings}
className="flex w-full items-center gap-2 rounded px-2 py-1 text-[12px] text-text-muted hover:bg-surface-2 hover:text-text"
title="Settings"
>
<Settings className="h-3.5 w-3.5" />
Settings
</button>
{/* Bottom panel — user identity + settings, pinned below the tree. */}
<div className="border-t border-border p-1.5 space-y-0.5">
{/* User row */}
<div className="flex items-center gap-2 rounded px-2 py-1 text-[12px] text-text-muted">
<UserIcon className="h-3.5 w-3.5 flex-shrink-0" />
<span className="flex-1 truncate text-text">{user?.username}</span>
{isAdmin && (
<span className="rounded bg-accent/20 px-1 py-px text-[10px] leading-none text-accent flex-shrink-0">
<Shield className="inline h-2.5 w-2.5" />
</span>
)}
<button
onClick={logout}
className="rounded p-0.5 text-text-muted hover:bg-surface-2 hover:text-red-400 flex-shrink-0"
title="Sign out"
>
<LogOut className="h-3 w-3" />
</button>
</div>
{/* Settings — admin only, navigates to the settings section */}
{isAdmin && (
<button
onClick={() => navigateToSection('settings', {})}
className={clsx(
'flex w-full items-center gap-2 rounded px-2 py-1 text-[12px] hover:bg-surface-2 hover:text-text',
currentSection === 'settings' ? 'text-primary' : 'text-text-muted',
)}
title="Settings"
>
<Settings className="h-3.5 w-3.5" />
Settings
</button>
)}
</div>
<DeleteFolderDialog

View File

@@ -96,22 +96,20 @@ export function TopBar({
{MULIMAGO_ASCII}
</pre>
</div>
<div className="flex h-full items-end gap-2 self-stretch pb-1">
<div className="flex items-center gap-2">
<span className="text-[10px] font-serif text-black/80">
Built with hubris {toRoman(new Date().getFullYear())}
</span>
{!rightSidebarOpen && (
<button
onClick={onExpandRight}
className="self-center rounded bg-black/30 p-1.5 text-text-muted backdrop-blur-sm transition-colors hover:bg-black/50 hover:text-text"
className="rounded bg-black/30 p-1.5 text-text-muted backdrop-blur-sm transition-colors hover:bg-black/50 hover:text-text"
title="Expand panel (I)"
aria-label="Expand right panel"
>
<PanelRightOpen className="h-4 w-4" />
</button>
)}
<span
className="text-[10px] font-serif text-black/80"
>
Built with hubris {toRoman(new Date().getFullYear())}
</span>
</div>
</header>
)

View File

@@ -0,0 +1,170 @@
import {
createContext,
useContext,
useState,
useEffect,
useCallback,
useRef,
type ReactNode,
} from 'react'
import api from '../services/api'
export interface AuthUser {
id: string
username: string
email: string | null
role: 'admin' | 'user'
is_active: boolean
}
interface AuthContextValue {
user: AuthUser | null
isAdmin: boolean
isLoading: boolean
/** True when the backend has no users yet (first-run). */
needsSetup: boolean
login: (username: string, password: string) => Promise<void>
logout: () => void
/** Called after the setup endpoint creates the first admin. */
onSetupComplete: (accessToken: string, refreshToken: string) => Promise<void>
}
const AuthContext = createContext<AuthContextValue | null>(null)
export function useAuth(): AuthContextValue {
const ctx = useContext(AuthContext)
if (!ctx) throw new Error('useAuth must be used within AuthProvider')
return ctx
}
// ── Token helpers ──────────────────────────────────────────────────────
function getStoredToken(): string | null {
return localStorage.getItem('access_token')
}
function storeToken(token: string) {
localStorage.setItem('access_token', token)
}
function clearToken() {
localStorage.removeItem('access_token')
}
// ── Provider ───────────────────────────────────────────────────────────
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<AuthUser | null>(null)
const [isLoading, setIsLoading] = useState(true)
const [needsSetup, setNeedsSetup] = useState(false)
// Keep refresh token in memory only (not localStorage).
const refreshTokenRef = useRef<string | null>(null)
const refreshTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const isAdmin = user?.role === 'admin'
// Schedule a token refresh ~5 min before expiry.
const scheduleRefresh = useCallback((accessToken: string) => {
try {
const payload = JSON.parse(atob(accessToken.split('.')[1]))
const expiresAt = payload.exp * 1000
const refreshIn = Math.max(expiresAt - Date.now() - 5 * 60 * 1000, 10_000)
if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current)
refreshTimerRef.current = setTimeout(async () => {
if (!refreshTokenRef.current) return
try {
const res = await api.post('/auth/refresh', {
refresh_token: refreshTokenRef.current,
})
const { access_token, refresh_token } = res.data
storeToken(access_token)
refreshTokenRef.current = refresh_token
scheduleRefresh(access_token)
} catch {
// Refresh failed — force re-login.
clearToken()
refreshTokenRef.current = null
setUser(null)
}
}, refreshIn)
} catch {
// Malformed token — ignore.
}
}, [])
const fetchMe = useCallback(async () => {
try {
const res = await api.get('/auth/me')
setUser(res.data)
} catch {
clearToken()
setUser(null)
}
}, [])
// Boot: check if setup is needed, then try to restore session.
useEffect(() => {
;(async () => {
try {
const statusRes = await api.get('/auth/status')
if (!statusRes.data.setup_completed) {
setNeedsSetup(true)
setIsLoading(false)
return
}
} catch {
// Backend unreachable — fall through to login screen.
}
const token = getStoredToken()
if (token) {
await fetchMe()
scheduleRefresh(token)
}
setIsLoading(false)
})()
return () => {
if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current)
}
}, [fetchMe, scheduleRefresh])
const login = useCallback(
async (username: string, password: string) => {
const res = await api.post('/auth/login', { username, password })
const { access_token, refresh_token } = res.data
storeToken(access_token)
refreshTokenRef.current = refresh_token
scheduleRefresh(access_token)
await fetchMe()
},
[fetchMe, scheduleRefresh],
)
const logout = useCallback(() => {
clearToken()
refreshTokenRef.current = null
if (refreshTimerRef.current) clearTimeout(refreshTimerRef.current)
setUser(null)
}, [])
const onSetupComplete = useCallback(
async (accessToken: string, refreshToken: string) => {
storeToken(accessToken)
refreshTokenRef.current = refreshToken
setNeedsSetup(false)
scheduleRefresh(accessToken)
await fetchMe()
},
[fetchMe, scheduleRefresh],
)
return (
<AuthContext.Provider
value={{ user, isAdmin, isLoading, needsSetup, login, logout, onSetupComplete }}
>
{children}
</AuthContext.Provider>
)
}

View File

@@ -11,7 +11,7 @@ export const DUPLICATE_GROUPS_QUERY_KEY = ['library', 'duplicates'] as const
export function useDuplicateGroupsQuery() {
return useQuery<DuplicateGroupsResponse>({
queryKey: DUPLICATE_GROUPS_QUERY_KEY,
queryFn: library.duplicates.groups,
queryFn: () => library.duplicates.groups(),
staleTime: 30_000,
})
}

View File

@@ -13,7 +13,7 @@ export const LIBRARY_STATS_QUERY_KEY = ['library', 'stats'] as const
export function useLibraryStatsQuery() {
return useQuery<LibraryStats>({
queryKey: LIBRARY_STATS_QUERY_KEY,
queryFn: library.stats,
queryFn: () => library.stats(),
staleTime: 30_000,
})
}

View File

@@ -14,6 +14,61 @@ const api = axios.create({
},
})
// ── Auth interceptors ──────────────────────────────────────────────────
// Attach the stored JWT to every outgoing request.
api.interceptors.request.use((config) => {
const token = localStorage.getItem('access_token')
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
// On 401 responses, attempt one silent token refresh. If that also
// fails, clear stored credentials so the AuthContext falls back to the
// login screen on its next render.
let isRefreshing = false
let refreshSubscribers: ((token: string) => void)[] = []
api.interceptors.response.use(
(response) => response,
async (error) => {
const original = error.config
if (error.response?.status !== 401 || original._retry) {
return Promise.reject(error)
}
// Skip retry for auth endpoints themselves to avoid loops.
if (original.url?.startsWith('/auth/')) {
return Promise.reject(error)
}
original._retry = true
if (!isRefreshing) {
isRefreshing = true
// The refresh token lives in AuthContext memory, not in
// localStorage. The interceptor can't access it directly, so we
// rely on the AuthContext's scheduled refresh to keep the access
// token fresh. If the access token is truly expired and no
// refresh has happened, we just force a logout.
localStorage.removeItem('access_token')
isRefreshing = false
// Reject — AuthContext will detect the missing token and show login.
return Promise.reject(error)
}
// Another request is already refreshing — queue this one.
return new Promise((resolve) => {
refreshSubscribers.push((token: string) => {
original.headers.Authorization = `Bearer ${token}`
resolve(api(original))
})
})
},
)
// Source Folders API. Source roots are config-driven now (PHOTO_DIRS in
// .env → bootstrap on backend startup), so the UI only reads them and
// optionally renames the display label.
@@ -394,15 +449,19 @@ export const library = {
return response.data
},
stats: async (): Promise<LibraryStats> => {
const response = await api.get('/library/stats')
stats: async (scope?: 'global'): Promise<LibraryStats> => {
const response = await api.get('/library/stats', {
params: scope ? { scope } : undefined,
})
return response.data
},
/** Maintenance / admin actions surfaced via the Settings panel. */
maintenance: {
thumbnailStats: async (): Promise<ThumbnailStats> => {
const response = await api.get('/library/maintenance/thumbnail-stats')
thumbnailStats: async (scope?: 'global'): Promise<ThumbnailStats> => {
const response = await api.get('/library/maintenance/thumbnail-stats', {
params: scope ? { scope } : undefined,
})
return response.data
},
@@ -413,28 +472,30 @@ export const library = {
media_types?: MediaType[]
only_failed?: boolean
only_pending?: boolean
} = {}
} = {},
scope?: 'global',
): Promise<RegenerateResult> => {
const response = await api.post(
'/library/maintenance/regenerate-thumbnails',
body
body,
{ params: scope ? { scope } : undefined },
)
return response.data
},
/** Celery worker fleet diagnostics + recent task failures. Surfaced
* in the Settings panel so users can debug stuck queues without
* tailing container logs. */
workerStatus: async (): Promise<WorkerStatus> => {
const response = await api.get('/library/maintenance/worker-status')
/** Celery worker fleet diagnostics + recent task failures. */
workerStatus: async (scope?: 'global'): Promise<WorkerStatus> => {
const response = await api.get('/library/maintenance/worker-status', {
params: scope ? { scope } : undefined,
})
return response.data
},
/** Per-stage ingestion progress — thumbnails, EXIF, GPS, phash,
* embeddings, object tags, OCR, faces, face clusters, duplicate
* groups. Drives the Pipeline Progress card in Settings. */
pipelineStats: async (): Promise<PipelineStats> => {
const response = await api.get('/library/maintenance/pipeline-stats')
/** Per-stage ingestion progress. */
pipelineStats: async (scope?: 'global'): Promise<PipelineStats> => {
const response = await api.get('/library/maintenance/pipeline-stats', {
params: scope ? { scope } : undefined,
})
return response.data
},
@@ -477,8 +538,10 @@ export const library = {
/** Duplicate groups computed by app.services.duplicates.regroup_duplicates.
* Drives the grouped grid view in the Duplicates section. */
duplicates: {
groups: async (): Promise<DuplicateGroupsResponse> => {
const response = await api.get('/library/duplicates/groups')
groups: async (scope?: 'global'): Promise<DuplicateGroupsResponse> => {
const response = await api.get('/library/duplicates/groups', {
params: scope ? { scope } : undefined,
})
return response.data
},
},
@@ -725,4 +788,45 @@ export const discard = {
},
}
// Admin API — user management (admin only)
export interface AdminUser {
id: string
username: string
email: string | null
role: 'admin' | 'user'
is_active: boolean
media_path: string
created_at: string | null
photo_count: number
}
export const admin = {
listUsers: async (): Promise<{ users: AdminUser[]; total: number }> => {
const response = await api.get('/admin/users')
return response.data
},
createUser: async (data: {
username: string
password: string
role: string
}): Promise<AdminUser> => {
const response = await api.post('/admin/users', data)
return response.data
},
updateUser: async (
userId: string,
data: { role?: string; is_active?: boolean; new_password?: string },
): Promise<AdminUser> => {
const response = await api.patch(`/admin/users/${userId}`, data)
return response.data
},
deleteUser: async (userId: string): Promise<{ status: string }> => {
const response = await api.delete(`/admin/users/${userId}`)
return response.data
},
}
export default api