Add profile page, user dropdown, and Authentik SSO integration

- Profile dropdown in header shows user name/email/avatar with links
  to profile, settings, support, theme submenu, and sign out
- New /profile page with editable user info (job title, company, bio)
  and read-only SSO fields when behind Authentik forward-auth
- /api/auth/me endpoint reads X-authentik-* headers and enriches
  with avatar from Authentik API
- Settings page gains Preferences tab with appearance theme picker
  and notification toggle switches
- User profile context backed by localStorage, merges with Authentik
  data when available

Made-with: Cursor
This commit is contained in:
Randall Stillwell 2026-03-12 10:42:39 -05:00
parent 59c4af5db6
commit 38f4229d3b
7 changed files with 983 additions and 242 deletions

View file

@ -16,3 +16,8 @@ MINIO_BUCKET="echos-ocr"
# Folder Watch (optional, mount a host path into the container)
WATCH_DIR=""
# Authentik SSO (optional — user info comes from forward-auth headers automatically;
# these are only needed to enrich profiles with avatars via the Authentik API)
AUTHENTIK_URL="https://auth.stillwell.cloud"
AUTHENTIK_API_TOKEN=""

View file

@ -0,0 +1,71 @@
import { NextRequest, NextResponse } from "next/server";
export type AuthentikUser = {
username: string;
name: string;
email: string;
groups: string[];
uid: string;
avatar: string;
};
/**
* Reads Authentik forward-auth headers injected by Traefik and optionally
* enriches with avatar from the Authentik API.
*
* Headers set by authentik forward-auth:
* X-authentik-username, X-authentik-name, X-authentik-email,
* X-authentik-groups, X-authentik-uid
*/
export async function GET(req: NextRequest) {
const username = req.headers.get("x-authentik-username") ?? "";
const name = req.headers.get("x-authentik-name") ?? "";
const email = req.headers.get("x-authentik-email") ?? "";
const groups = req.headers.get("x-authentik-groups") ?? "";
const uid = req.headers.get("x-authentik-uid") ?? "";
if (!username && !email) {
return NextResponse.json(
{ authenticated: false, user: null },
{ status: 200 }
);
}
const user: AuthentikUser = {
username,
name,
email,
groups: groups ? groups.split("|") : [],
uid,
avatar: "",
};
const authentikUrl = process.env.AUTHENTIK_URL;
const authentikToken = process.env.AUTHENTIK_API_TOKEN;
if (authentikUrl && authentikToken && uid) {
try {
const res = await fetch(
`${authentikUrl}/api/v3/core/users/?search=${encodeURIComponent(username)}&page_size=1`,
{
headers: { Authorization: `Bearer ${authentikToken}` },
signal: AbortSignal.timeout(5000),
next: { revalidate: 300 },
}
);
if (res.ok) {
const data = await res.json();
const matchedUser = data.results?.[0];
if (matchedUser) {
user.avatar = matchedUser.avatar ?? "";
if (!user.name && matchedUser.name) user.name = matchedUser.name;
}
}
} catch {
// Authentik API unavailable — headers still provide the essentials
}
}
return NextResponse.json({ authenticated: true, user });
}

316
src/app/profile/page.tsx Normal file
View file

@ -0,0 +1,316 @@
"use client";
import * as React from "react";
import { toast } from "sonner";
import {
Save,
UserCircle,
Camera,
X,
Mail,
Briefcase,
Building2,
Shield,
Loader2,
} from "lucide-react";
import { Header } from "@/components/layout/header";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardHeader,
CardTitle,
CardDescription,
} from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useUserProfile } from "@/lib/user-profile";
export default function ProfilePage() {
const { profile, updateProfile, initials, authentikUser, isAuthenticated, loading } = useUserProfile();
const [form, setForm] = React.useState({
jobTitle: profile.jobTitle,
company: profile.company,
bio: profile.bio,
// Only editable when NOT coming from Authentik
displayName: profile.displayName,
email: profile.email,
avatarUrl: profile.avatarUrl,
});
const [dirty, setDirty] = React.useState(false);
React.useEffect(() => {
setForm({
jobTitle: profile.jobTitle,
company: profile.company,
bio: profile.bio,
displayName: profile.displayName,
email: profile.email,
avatarUrl: profile.avatarUrl,
});
}, [profile]);
const handleChange = (field: string, value: string) => {
setForm((prev) => ({ ...prev, [field]: value }));
setDirty(true);
};
const handleSave = () => {
const updates: Record<string, string> = {
jobTitle: form.jobTitle,
company: form.company,
bio: form.bio,
};
if (!isAuthenticated) {
updates.displayName = form.displayName;
updates.email = form.email;
updates.avatarUrl = form.avatarUrl;
}
updateProfile(updates);
setDirty(false);
toast.success("Profile updated");
};
const handleAvatarUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
if (!file.type.startsWith("image/")) {
toast.error("Please select an image file");
return;
}
if (file.size > 2 * 1024 * 1024) {
toast.error("Image must be under 2 MB");
return;
}
const reader = new FileReader();
reader.onload = () => {
handleChange("avatarUrl", reader.result as string);
};
reader.readAsDataURL(file);
};
const removeAvatar = () => {
handleChange("avatarUrl", "");
};
if (loading) {
return (
<div className="flex items-center justify-center py-20">
<Loader2 className="size-8 animate-spin text-muted-foreground" />
</div>
);
}
const nameFromAuthentik = isAuthenticated && !!authentikUser?.name;
const emailFromAuthentik = isAuthenticated && !!authentikUser?.email;
const avatarFromAuthentik = isAuthenticated && !!authentikUser?.avatar;
return (
<div className="space-y-6">
<Header title="Profile" description="Manage your personal information" icon={UserCircle}>
<Button className="rounded-xl" onClick={handleSave} disabled={!dirty}>
<Save className="mr-2 size-4" />
Save Changes
</Button>
</Header>
{isAuthenticated && (
<div className="flex items-center gap-2 rounded-xl border border-emerald-500/20 bg-emerald-500/5 px-4 py-3">
<Shield className="size-4 shrink-0 text-emerald-600 dark:text-emerald-400" />
<p className="text-sm text-emerald-700 dark:text-emerald-300">
Signed in via Authentik as <span className="font-medium">{authentikUser?.username}</span>.
Name, email, and avatar are managed by your identity provider.
</p>
</div>
)}
<div className="grid gap-4 sm:gap-6 grid-cols-1 lg:grid-cols-3">
<Card variant="glass" className="lg:col-span-1">
<CardHeader>
<CardTitle className="text-base">Photo</CardTitle>
<CardDescription>
{avatarFromAuthentik
? "Managed by Authentik"
: "Your profile picture is visible in the header"}
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col items-center gap-4">
<div className="relative group">
<Avatar size="lg" className="!size-24 text-2xl">
{form.avatarUrl && (
<AvatarImage src={form.avatarUrl} alt={form.displayName} />
)}
<AvatarFallback className="text-2xl">
{initials || <UserCircle className="size-10 text-muted-foreground" />}
</AvatarFallback>
</Avatar>
{!avatarFromAuthentik && (
<label className="absolute inset-0 flex cursor-pointer items-center justify-center rounded-full bg-black/40 opacity-0 transition-opacity group-hover:opacity-100">
<Camera className="size-6 text-white" />
<input
type="file"
accept="image/*"
className="hidden"
onChange={handleAvatarUpload}
/>
</label>
)}
</div>
{!avatarFromAuthentik && (
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
className="rounded-xl"
onClick={() => document.querySelector<HTMLInputElement>('input[type="file"]')?.click()}
>
<Camera className="mr-1.5 size-3" />
Upload
</Button>
{form.avatarUrl && (
<Button
variant="ghost"
size="sm"
className="rounded-xl text-muted-foreground"
onClick={removeAvatar}
>
<X className="mr-1.5 size-3" />
Remove
</Button>
)}
</div>
)}
{avatarFromAuthentik && (
<p className="text-center text-xs text-muted-foreground">
Update your avatar in{" "}
<a
href="https://auth.stillwell.cloud/if/user/"
target="_blank"
rel="noopener noreferrer"
className="underline underline-offset-2 hover:text-foreground"
>
Authentik
</a>
</p>
)}
{!avatarFromAuthentik && (
<p className="text-center text-xs text-muted-foreground">
JPG, PNG or WebP. Max 2 MB.
</p>
)}
</CardContent>
</Card>
<Card variant="glass" className="lg:col-span-2">
<CardHeader>
<CardTitle className="text-base">Personal Information</CardTitle>
<CardDescription>
{isAuthenticated
? "Some fields are synced from Authentik"
: "Update your name, email, and other details"}
</CardDescription>
</CardHeader>
<CardContent className="space-y-5">
<div className="grid gap-4 sm:grid-cols-2">
<div>
<Label className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
<UserCircle className="size-3" />
Display Name
{nameFromAuthentik && (
<Badge variant="secondary" className="ml-auto text-[10px] px-1.5 py-0">SSO</Badge>
)}
</Label>
<Input
value={form.displayName}
onChange={(e) => handleChange("displayName", e.target.value)}
placeholder="Your name"
readOnly={nameFromAuthentik}
className={nameFromAuthentik ? "bg-muted/40 cursor-default" : ""}
/>
</div>
<div>
<Label className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
<Mail className="size-3" />
Email
{emailFromAuthentik && (
<Badge variant="secondary" className="ml-auto text-[10px] px-1.5 py-0">SSO</Badge>
)}
</Label>
<Input
type="email"
value={form.email}
onChange={(e) => handleChange("email", e.target.value)}
placeholder="you@example.com"
readOnly={emailFromAuthentik}
className={emailFromAuthentik ? "bg-muted/40 cursor-default" : ""}
/>
</div>
</div>
{isAuthenticated && authentikUser?.groups && authentikUser.groups.length > 0 && (
<div>
<Label className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
<Shield className="size-3" />
Groups
<Badge variant="secondary" className="ml-auto text-[10px] px-1.5 py-0">SSO</Badge>
</Label>
<div className="flex flex-wrap gap-1.5 mt-1">
{authentikUser.groups.map((group) => (
<Badge key={group} variant="secondary" className="text-xs">
{group}
</Badge>
))}
</div>
</div>
)}
<div className="grid gap-4 sm:grid-cols-2">
<div>
<Label className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
<Briefcase className="size-3" />
Job Title
</Label>
<Input
value={form.jobTitle}
onChange={(e) => handleChange("jobTitle", e.target.value)}
placeholder="e.g. Project Manager"
/>
</div>
<div>
<Label className="mb-1.5 flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
<Building2 className="size-3" />
Company
</Label>
<Input
value={form.company}
onChange={(e) => handleChange("company", e.target.value)}
placeholder="e.g. Echo Labs"
/>
</div>
</div>
<div>
<Label className="mb-1.5 block text-xs font-medium text-muted-foreground">
Bio
</Label>
<Textarea
value={form.bio}
onChange={(e) => handleChange("bio", e.target.value)}
placeholder="Tell us a little about yourself..."
className="min-h-24 resize-none"
/>
</div>
</CardContent>
</Card>
</div>
</div>
);
}

View file

@ -2,6 +2,7 @@
import * as React from "react";
import { toast } from "sonner";
import { useTheme } from "next-themes";
import {
Loader2,
Save,
@ -13,6 +14,10 @@ import {
HardDrive,
Plug,
Settings,
Sun,
Moon,
Monitor,
Bell,
} from "lucide-react";
import { Header } from "@/components/layout/header";
@ -21,6 +26,7 @@ import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/com
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Switch } from "@/components/ui/switch";
import {
Select,
SelectContent,
@ -28,6 +34,7 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
const AI_PROVIDERS = [
{
@ -55,7 +62,34 @@ type SettingsData = {
aiModel: string;
};
const NOTIFICATION_STORAGE_KEY = "echo-ocr-notification-prefs";
type NotificationPrefs = {
processingComplete: boolean;
processingErrors: boolean;
folderWatchAlerts: boolean;
cleanupReminders: boolean;
};
const DEFAULT_NOTIFICATION_PREFS: NotificationPrefs = {
processingComplete: true,
processingErrors: true,
folderWatchAlerts: true,
cleanupReminders: false,
};
function loadNotificationPrefs(): NotificationPrefs {
if (typeof window === "undefined") return DEFAULT_NOTIFICATION_PREFS;
try {
const raw = localStorage.getItem(NOTIFICATION_STORAGE_KEY);
if (raw) return { ...DEFAULT_NOTIFICATION_PREFS, ...JSON.parse(raw) };
} catch {}
return DEFAULT_NOTIFICATION_PREFS;
}
export default function SettingsPage() {
const { theme, setTheme } = useTheme();
const [settings, setSettings] = React.useState<SettingsData>({
ollamaUrl: "",
model: "",
@ -71,6 +105,20 @@ export default function SettingsPage() {
const [aiTestStatus, setAiTestStatus] = React.useState<"idle" | "testing" | "success" | "error">("idle");
const [cleanupStatus, setCleanupStatus] = React.useState<{ sourcesEligible: number; imagesEligible: number } | null>(null);
const [cleaning, setCleaning] = React.useState(false);
const [notifPrefs, setNotifPrefs] = React.useState<NotificationPrefs>(DEFAULT_NOTIFICATION_PREFS);
React.useEffect(() => {
setNotifPrefs(loadNotificationPrefs());
}, []);
const updateNotifPref = (key: keyof NotificationPrefs, value: boolean) => {
setNotifPrefs((prev) => {
const next = { ...prev, [key]: value };
try { localStorage.setItem(NOTIFICATION_STORAGE_KEY, JSON.stringify(next)); } catch {}
return next;
});
toast.success("Notification preference updated");
};
const fetchCleanupStatus = React.useCallback(() => {
fetch("/api/cleanup")
@ -194,243 +242,344 @@ export default function SettingsPage() {
);
}
const themeOptions = [
{ value: "light", label: "Light", icon: Sun, description: "Clean and bright interface" },
{ value: "dark", label: "Dark", icon: Moon, description: "Easy on the eyes in low light" },
{ value: "system", label: "System", icon: Monitor, description: "Follows your OS preference" },
] as const;
return (
<div className="space-y-6">
<Header title="Settings" description="Configure OCR and app settings" icon={Settings}>
<Header title="Settings" description="Configure your app and preferences" icon={Settings}>
<Button className="rounded-xl" onClick={handleSave} disabled={saving}>
{saving ? <Loader2 className="mr-2 size-4 animate-spin" /> : <Save className="mr-2 size-4" />}
Save Settings
</Button>
</Header>
<div className="grid gap-4 sm:gap-6 grid-cols-1 lg:grid-cols-2">
<Card variant="glass">
<CardHeader>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<CardTitle className="flex items-center gap-2 text-base">
<Brain className="size-4 text-primary" />
AI Provider
</CardTitle>
<CardDescription>Choose the AI model for OCR processing</CardDescription>
</div>
<Badge
variant="secondary"
className={
aiTestStatus === "success"
? "bg-emerald-500/10 text-emerald-700 dark:text-emerald-300"
: aiTestStatus === "error"
? "bg-red-500/10 text-red-700 dark:text-red-300"
: ""
}
>
{aiTestStatus === "success" && <Wifi className="mr-1 size-3" />}
{aiTestStatus === "error" && <WifiOff className="mr-1 size-3" />}
{aiTestStatus === "testing" && <Loader2 className="mr-1 size-3 animate-spin" />}
{aiTestStatus === "success"
? "Connected"
: aiTestStatus === "error"
? "Error"
: aiTestStatus === "testing"
? "Testing..."
: "Not tested"}
</Badge>
</div>
</CardHeader>
<CardContent className="space-y-4">
<div>
<Label className="mb-1.5 block text-xs font-medium text-muted-foreground">Provider</Label>
<Select value={settings.aiProvider} onValueChange={handleProviderChange}>
<SelectTrigger>
<SelectValue placeholder="Select a provider" />
</SelectTrigger>
<SelectContent>
{AI_PROVIDERS.map((p) => (
<SelectItem key={p.value} value={p.value}>
{p.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label className="mb-1.5 block text-xs font-medium text-muted-foreground">Model</Label>
<Input
value={settings.aiModel}
onChange={(e) => setSettings((s) => ({ ...s, aiModel: e.target.value }))}
placeholder={AI_PROVIDERS.find((p) => p.value === settings.aiProvider)?.defaultModel || ""}
/>
<p className="mt-1 text-xs text-muted-foreground">
{AI_PROVIDERS.find((p) => p.value === settings.aiProvider)?.hint || ""}
</p>
</div>
<Tabs defaultValue="application">
<TabsList variant="line" className="mb-4">
<TabsTrigger value="application">Application</TabsTrigger>
<TabsTrigger value="preferences">Preferences</TabsTrigger>
</TabsList>
{settings.aiProvider === "ollama" && (
<div>
<Label className="mb-1.5 block text-xs font-medium text-muted-foreground">Ollama URL</Label>
<Input
value={settings.ollamaUrl}
onChange={(e) => setSettings((s) => ({ ...s, ollamaUrl: e.target.value }))}
placeholder="http://192.168.68.108:11434"
/>
</div>
)}
<TabsContent value="application">
<div className="grid gap-4 sm:gap-6 grid-cols-1 lg:grid-cols-2">
<Card variant="glass">
<CardHeader>
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<CardTitle className="flex items-center gap-2 text-base">
<Brain className="size-4 text-primary" />
AI Provider
</CardTitle>
<CardDescription>Choose the AI model for OCR processing</CardDescription>
</div>
<Badge
variant="secondary"
className={
aiTestStatus === "success"
? "bg-emerald-500/10 text-emerald-700 dark:text-emerald-300"
: aiTestStatus === "error"
? "bg-red-500/10 text-red-700 dark:text-red-300"
: ""
}
>
{aiTestStatus === "success" && <Wifi className="mr-1 size-3" />}
{aiTestStatus === "error" && <WifiOff className="mr-1 size-3" />}
{aiTestStatus === "testing" && <Loader2 className="mr-1 size-3 animate-spin" />}
{aiTestStatus === "success"
? "Connected"
: aiTestStatus === "error"
? "Error"
: aiTestStatus === "testing"
? "Testing..."
: "Not tested"}
</Badge>
</div>
</CardHeader>
<CardContent className="space-y-4">
<div>
<Label className="mb-1.5 block text-xs font-medium text-muted-foreground">Provider</Label>
<Select value={settings.aiProvider} onValueChange={handleProviderChange}>
<SelectTrigger>
<SelectValue placeholder="Select a provider" />
</SelectTrigger>
<SelectContent>
{AI_PROVIDERS.map((p) => (
<SelectItem key={p.value} value={p.value}>
{p.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label className="mb-1.5 block text-xs font-medium text-muted-foreground">Model</Label>
<Input
value={settings.aiModel}
onChange={(e) => setSettings((s) => ({ ...s, aiModel: e.target.value }))}
placeholder={AI_PROVIDERS.find((p) => p.value === settings.aiProvider)?.defaultModel || ""}
/>
<p className="mt-1 text-xs text-muted-foreground">
{AI_PROVIDERS.find((p) => p.value === settings.aiProvider)?.hint || ""}
</p>
</div>
{settings.aiProvider === "gateway" && (
<div className="rounded-xl border border-border/50 bg-muted/30 p-3">
<p className="text-xs text-muted-foreground">
Uses the <code className="rounded-md bg-muted px-1.5 py-0.5 text-foreground/80">AI_GATEWAY_API_KEY</code> env
var. Model format: <code className="rounded-md bg-muted px-1.5 py-0.5 text-foreground/80">provider/model</code>
</p>
</div>
)}
{settings.aiProvider === "ollama" && (
<div>
<Label className="mb-1.5 block text-xs font-medium text-muted-foreground">Ollama URL</Label>
<Input
value={settings.ollamaUrl}
onChange={(e) => setSettings((s) => ({ ...s, ollamaUrl: e.target.value }))}
placeholder="http://192.168.68.108:11434"
/>
</div>
)}
<Button variant="outline" size="sm" className="rounded-xl" onClick={testAiProvider} disabled={aiTestStatus === "testing"}>
{aiTestStatus === "testing" ? (
<Loader2 className="mr-2 size-3 animate-spin" />
) : (
<Wifi className="mr-2 size-3" />
)}
Test Connection
</Button>
</CardContent>
</Card>
{settings.aiProvider === "gateway" && (
<div className="rounded-xl border border-border/50 bg-muted/30 p-3">
<p className="text-xs text-muted-foreground">
Uses the <code className="rounded-md bg-muted px-1.5 py-0.5 text-foreground/80">AI_GATEWAY_API_KEY</code> env
var. Model format: <code className="rounded-md bg-muted px-1.5 py-0.5 text-foreground/80">provider/model</code>
</p>
</div>
)}
<Card variant="glass">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<FolderSearch className="size-4 text-primary" />
Folder Monitoring
</CardTitle>
<CardDescription>Automatically process new PDFs dropped into a folder</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div>
<Label className="mb-1.5 block text-xs font-medium text-muted-foreground">Watch Directory</Label>
<Input
value={settings.watchDir}
onChange={(e) => setSettings((s) => ({ ...s, watchDir: e.target.value }))}
placeholder="/data/watch"
/>
<p className="mt-1 text-xs text-muted-foreground">
Absolute path on the server. Mount a host folder into the container.
</p>
</div>
<div className="flex flex-wrap items-center gap-3">
<Button
variant={settings.watching ? "destructive" : "outline"}
size="sm"
className="rounded-xl"
onClick={toggleWatch}
disabled={!settings.watchDir}
>
{settings.watching ? "Stop Watching" : "Start Watching"}
</Button>
{settings.watching && (
<Badge className="bg-emerald-500/10 text-emerald-700 dark:text-emerald-300">
Active
</Badge>
)}
</div>
</CardContent>
</Card>
<Card variant="glass">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<HardDrive className="size-4 text-primary" />
Storage & Cleanup
</CardTitle>
<CardDescription>Auto-purge uploaded files and images to save storage</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div>
<Label className="mb-1.5 block text-xs font-medium text-muted-foreground">
Source PDF Retention (days)
</Label>
<Input
type="number"
min={1}
value={settings.sourceRetentionDays}
onChange={(e) =>
setSettings((s) => ({
...s,
sourceRetentionDays: parseInt(e.target.value) || 30,
}))
}
/>
<p className="mt-1 text-xs text-muted-foreground">
Original uploaded PDFs are deleted after this many days. Card data is kept.
</p>
</div>
<div>
<Label className="mb-1.5 block text-xs font-medium text-muted-foreground">
Image Retention (days)
</Label>
<Input
type="number"
min={1}
value={settings.imageRetentionDays}
onChange={(e) =>
setSettings((s) => ({
...s,
imageRetentionDays: parseInt(e.target.value) || 180,
}))
}
/>
<p className="mt-1 text-xs text-muted-foreground">
Scanned card images are removed after this many days. Card data is kept.
</p>
</div>
<div className="rounded-xl border border-border/50 bg-muted/30 p-3">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div className="text-sm">
{cleanupStatus ? (
<>
<span className="font-medium">{cleanupStatus.sourcesEligible}</span> source files
{" and "}
<span className="font-medium">{cleanupStatus.imagesEligible}</span> card images eligible
</>
<Button variant="outline" size="sm" className="rounded-xl" onClick={testAiProvider} disabled={aiTestStatus === "testing"}>
{aiTestStatus === "testing" ? (
<Loader2 className="mr-2 size-3 animate-spin" />
) : (
"Checking..."
<Wifi className="mr-2 size-3" />
)}
Test Connection
</Button>
</CardContent>
</Card>
<Card variant="glass">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<FolderSearch className="size-4 text-primary" />
Folder Monitoring
</CardTitle>
<CardDescription>Automatically process new PDFs dropped into a folder</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div>
<Label className="mb-1.5 block text-xs font-medium text-muted-foreground">Watch Directory</Label>
<Input
value={settings.watchDir}
onChange={(e) => setSettings((s) => ({ ...s, watchDir: e.target.value }))}
placeholder="/data/watch"
/>
<p className="mt-1 text-xs text-muted-foreground">
Absolute path on the server. Mount a host folder into the container.
</p>
</div>
<div className="flex flex-wrap items-center gap-3">
<Button
variant={settings.watching ? "destructive" : "outline"}
size="sm"
className="rounded-xl"
onClick={toggleWatch}
disabled={!settings.watchDir}
>
{settings.watching ? "Stop Watching" : "Start Watching"}
</Button>
{settings.watching && (
<Badge className="bg-emerald-500/10 text-emerald-700 dark:text-emerald-300">
Active
</Badge>
)}
</div>
<Button
variant="destructive"
size="sm"
className="shrink-0 rounded-xl"
onClick={runCleanup}
disabled={cleaning || !cleanupStatus || (cleanupStatus.sourcesEligible === 0 && cleanupStatus.imagesEligible === 0)}
>
{cleaning ? <Loader2 className="mr-2 size-3 animate-spin" /> : <Trash2 className="mr-2 size-3" />}
Run Cleanup Now
</Button>
</div>
</div>
</CardContent>
</Card>
</CardContent>
</Card>
<Card variant="glass">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<Plug className="size-4 text-primary" />
Monday.com Integration
</CardTitle>
<CardDescription>Push scanned card data to Monday.com boards (coming soon)</CardDescription>
</CardHeader>
<CardContent>
<div className="rounded-2xl border-2 border-dashed border-muted-foreground/15 p-6 sm:p-8 text-center">
<p className="text-sm text-muted-foreground">
API endpoints are ready. Configure Monday.com connection in a future update.
</p>
<p className="mt-2 text-xs text-muted-foreground">
Use the REST API at <code className="rounded-md bg-muted px-1.5 py-0.5 text-foreground/80">/api/cards</code> to
integrate with n8n, Zapier, or Monday.com directly.
</p>
</div>
</CardContent>
</Card>
</div>
<Card variant="glass">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<HardDrive className="size-4 text-primary" />
Storage & Cleanup
</CardTitle>
<CardDescription>Auto-purge uploaded files and images to save storage</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div>
<Label className="mb-1.5 block text-xs font-medium text-muted-foreground">
Source PDF Retention (days)
</Label>
<Input
type="number"
min={1}
value={settings.sourceRetentionDays}
onChange={(e) =>
setSettings((s) => ({
...s,
sourceRetentionDays: parseInt(e.target.value) || 30,
}))
}
/>
<p className="mt-1 text-xs text-muted-foreground">
Original uploaded PDFs are deleted after this many days. Card data is kept.
</p>
</div>
<div>
<Label className="mb-1.5 block text-xs font-medium text-muted-foreground">
Image Retention (days)
</Label>
<Input
type="number"
min={1}
value={settings.imageRetentionDays}
onChange={(e) =>
setSettings((s) => ({
...s,
imageRetentionDays: parseInt(e.target.value) || 180,
}))
}
/>
<p className="mt-1 text-xs text-muted-foreground">
Scanned card images are removed after this many days. Card data is kept.
</p>
</div>
<div className="rounded-xl border border-border/50 bg-muted/30 p-3">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div className="text-sm">
{cleanupStatus ? (
<>
<span className="font-medium">{cleanupStatus.sourcesEligible}</span> source files
{" and "}
<span className="font-medium">{cleanupStatus.imagesEligible}</span> card images eligible
</>
) : (
"Checking..."
)}
</div>
<Button
variant="destructive"
size="sm"
className="shrink-0 rounded-xl"
onClick={runCleanup}
disabled={cleaning || !cleanupStatus || (cleanupStatus.sourcesEligible === 0 && cleanupStatus.imagesEligible === 0)}
>
{cleaning ? <Loader2 className="mr-2 size-3 animate-spin" /> : <Trash2 className="mr-2 size-3" />}
Run Cleanup Now
</Button>
</div>
</div>
</CardContent>
</Card>
<Card variant="glass">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<Plug className="size-4 text-primary" />
Monday.com Integration
</CardTitle>
<CardDescription>Push scanned card data to Monday.com boards (coming soon)</CardDescription>
</CardHeader>
<CardContent>
<div className="rounded-2xl border-2 border-dashed border-muted-foreground/15 p-6 sm:p-8 text-center">
<p className="text-sm text-muted-foreground">
API endpoints are ready. Configure Monday.com connection in a future update.
</p>
<p className="mt-2 text-xs text-muted-foreground">
Use the REST API at <code className="rounded-md bg-muted px-1.5 py-0.5 text-foreground/80">/api/cards</code> to
integrate with n8n, Zapier, or Monday.com directly.
</p>
</div>
</CardContent>
</Card>
</div>
</TabsContent>
<TabsContent value="preferences">
<div className="grid gap-4 sm:gap-6 grid-cols-1 lg:grid-cols-2">
<Card variant="glass" className="lg:col-span-2">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<Sun className="size-4 text-primary dark:hidden" />
<Moon className="hidden size-4 text-primary dark:block" />
Appearance
</CardTitle>
<CardDescription>Choose how Echo OCR looks to you</CardDescription>
</CardHeader>
<CardContent>
<div className="grid gap-3 sm:grid-cols-3">
{themeOptions.map((opt) => {
const Icon = opt.icon;
const active = theme === opt.value;
return (
<button
key={opt.value}
onClick={() => setTheme(opt.value)}
className={`group relative flex flex-col items-center gap-2 rounded-xl border p-4 text-center transition-all ${
active
? "border-primary/40 bg-primary/5 ring-2 ring-primary/20"
: "border-border/50 bg-muted/20 hover:border-border hover:bg-muted/40"
}`}
>
<div
className={`flex size-10 items-center justify-center rounded-lg transition-colors ${
active
? "bg-primary/10 text-primary"
: "bg-muted/50 text-muted-foreground group-hover:text-foreground"
}`}
>
<Icon className="size-5" />
</div>
<div>
<p className={`text-sm font-medium ${active ? "text-primary" : "text-foreground"}`}>
{opt.label}
</p>
<p className="mt-0.5 text-xs text-muted-foreground">
{opt.description}
</p>
</div>
</button>
);
})}
</div>
</CardContent>
</Card>
<Card variant="glass" className="lg:col-span-2">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<Bell className="size-4 text-primary" />
Notifications
</CardTitle>
<CardDescription>Control which events generate toast notifications</CardDescription>
</CardHeader>
<CardContent>
<div className="divide-y divide-border/50">
{([
{ key: "processingComplete" as const, title: "Processing complete", desc: "When a PDF finishes OCR processing" },
{ key: "processingErrors" as const, title: "Processing errors", desc: "When a job fails or encounters an error" },
{ key: "folderWatchAlerts" as const, title: "Folder watch alerts", desc: "When the folder watcher starts, stops, or finds new files" },
{ key: "cleanupReminders" as const, title: "Cleanup reminders", desc: "Periodic reminders when files are eligible for cleanup" },
]).map((item) => (
<div
key={item.key}
className="flex items-center justify-between gap-4 py-3 first:pt-0 last:pb-0"
>
<div className="min-w-0">
<p className="text-sm font-medium">{item.title}</p>
<p className="text-xs text-muted-foreground">{item.desc}</p>
</div>
<Switch
checked={notifPrefs[item.key]}
onCheckedChange={(val: boolean) => updateNotifPref(item.key, val)}
/>
</div>
))}
</div>
</CardContent>
</Card>
</div>
</TabsContent>
</Tabs>
</div>
);
}

View file

@ -11,10 +11,13 @@ import {
LogOut,
ScanLine,
User,
UserCircle,
LifeBuoy,
Monitor,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
DropdownMenu,
DropdownMenuTrigger,
@ -22,15 +25,21 @@ import {
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuLabel,
DropdownMenuGroup,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
} from "@/components/ui/dropdown-menu";
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from "@/components/ui/tooltip";
import { useUserProfile } from "@/lib/user-profile";
export function TopBar() {
const { theme, setTheme } = useTheme();
const { profile, initials } = useUserProfile();
const handleUploadClick = () => {
window.dispatchEvent(new CustomEvent("open-upload-modal"));
@ -102,27 +111,77 @@ export function TopBar() {
}
>
<Avatar size="sm">
{profile.avatarUrl && <AvatarImage src={profile.avatarUrl} alt={profile.displayName} />}
<AvatarFallback>
<User className="size-3.5" />
{initials || <User className="size-3.5" />}
</AvatarFallback>
</Avatar>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" sideOffset={8} className="w-48">
<DropdownMenuLabel>My Account</DropdownMenuLabel>
<DropdownMenuContent align="end" sideOffset={8} className="w-56">
<DropdownMenuLabel className="font-normal">
<div className="flex items-center gap-3 px-0.5 py-1">
<Avatar>
{profile.avatarUrl && <AvatarImage src={profile.avatarUrl} alt={profile.displayName} />}
<AvatarFallback className="text-xs">
{initials || <User className="size-4" />}
</AvatarFallback>
</Avatar>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-foreground">
{profile.displayName || "Set up profile"}
</p>
{profile.email && (
<p className="truncate text-xs text-muted-foreground">
{profile.email}
</p>
)}
</div>
</div>
</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuItem
render={<Link href="/settings" />}
>
<Settings className="size-4" />
Settings
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
>
<Sun className="size-4 dark:hidden" />
<Moon className="hidden size-4 dark:block" />
{theme === "dark" ? "Light Mode" : "Dark Mode"}
</DropdownMenuItem>
<DropdownMenuGroup>
<DropdownMenuItem render={<Link href="/profile" />}>
<UserCircle className="size-4" />
Profile
</DropdownMenuItem>
<DropdownMenuItem render={<Link href="/settings" />}>
<Settings className="size-4" />
Settings
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
<DropdownMenuItem
onClick={() => window.open("mailto:support@echoocr.app", "_blank")}
>
<LifeBuoy className="size-4" />
Support
</DropdownMenuItem>
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<Sun className="size-4 dark:hidden" />
<Moon className="hidden size-4 dark:block" />
Theme
</DropdownMenuSubTrigger>
<DropdownMenuSubContent>
<DropdownMenuItem onClick={() => setTheme("light")}>
<Sun className="size-4" />
Light
{theme === "light" && <span className="ml-auto text-xs text-primary"></span>}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("dark")}>
<Moon className="size-4" />
Dark
{theme === "dark" && <span className="ml-auto text-xs text-primary"></span>}
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("system")}>
<Monitor className="size-4" />
System
{theme === "system" && <span className="ml-auto text-xs text-primary"></span>}
</DropdownMenuItem>
</DropdownMenuSubContent>
</DropdownMenuSub>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem variant="destructive">
<LogOut className="size-4" />

View file

@ -3,14 +3,17 @@
import { ThemeProvider } from "next-themes";
import { TooltipProvider } from "@/components/ui/tooltip";
import { Toaster } from "sonner";
import { UserProfileProvider } from "@/lib/user-profile";
export function Providers({ children }: { children: React.ReactNode }) {
return (
<ThemeProvider attribute="class" defaultTheme="system" enableSystem>
<TooltipProvider>
{children}
<Toaster richColors position="bottom-right" />
</TooltipProvider>
<UserProfileProvider>
<TooltipProvider>
{children}
<Toaster richColors position="bottom-right" />
</TooltipProvider>
</UserProfileProvider>
</ThemeProvider>
);
}

138
src/lib/user-profile.tsx Normal file
View file

@ -0,0 +1,138 @@
"use client";
import * as React from "react";
import type { AuthentikUser } from "@/app/api/auth/me/route";
export type UserProfile = {
displayName: string;
email: string;
jobTitle: string;
company: string;
bio: string;
avatarUrl: string;
};
const DEFAULT_PROFILE: UserProfile = {
displayName: "",
email: "",
jobTitle: "",
company: "",
bio: "",
avatarUrl: "",
};
const STORAGE_KEY = "echo-ocr-user-profile";
type UserProfileContextValue = {
profile: UserProfile;
updateProfile: (updates: Partial<UserProfile>) => void;
initials: string;
authentikUser: AuthentikUser | null;
isAuthenticated: boolean;
loading: boolean;
};
const UserProfileContext = React.createContext<UserProfileContextValue | null>(null);
function getInitials(name: string): string {
if (!name.trim()) return "";
const parts = name.trim().split(/\s+/);
if (parts.length === 1) return parts[0][0].toUpperCase();
return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}
function loadLocalProfile(): Partial<UserProfile> {
if (typeof window === "undefined") return {};
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (raw) return JSON.parse(raw);
} catch {}
return {};
}
function saveLocalProfile(profile: Partial<UserProfile>) {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(profile));
} catch {}
}
export function UserProfileProvider({ children }: { children: React.ReactNode }) {
const [authentikUser, setAuthentikUser] = React.useState<AuthentikUser | null>(null);
const [localOverrides, setLocalOverrides] = React.useState<Partial<UserProfile>>({});
const [loading, setLoading] = React.useState(true);
const [mounted, setMounted] = React.useState(false);
React.useEffect(() => {
setMounted(true);
setLocalOverrides(loadLocalProfile());
fetch("/api/auth/me")
.then((r) => r.json())
.then((data) => {
if (data.authenticated && data.user) {
setAuthentikUser(data.user);
}
})
.catch(() => {})
.finally(() => setLoading(false));
}, []);
const profile = React.useMemo<UserProfile>(() => {
const base: UserProfile = { ...DEFAULT_PROFILE };
if (authentikUser) {
base.displayName = authentikUser.name || authentikUser.username || "";
base.email = authentikUser.email || "";
base.avatarUrl = authentikUser.avatar || "";
}
return {
...base,
...localOverrides,
// Authentik-sourced fields take priority for name/email/avatar when present
...(authentikUser?.name ? { displayName: authentikUser.name } : {}),
...(authentikUser?.email ? { email: authentikUser.email } : {}),
...(authentikUser?.avatar ? { avatarUrl: authentikUser.avatar } : {}),
};
}, [authentikUser, localOverrides]);
const updateProfile = React.useCallback((updates: Partial<UserProfile>) => {
setLocalOverrides((prev) => {
const next = { ...prev, ...updates };
saveLocalProfile(next);
return next;
});
}, []);
const initials = React.useMemo(() => getInitials(profile.displayName), [profile.displayName]);
const isAuthenticated = !!authentikUser;
const value = React.useMemo(
() => ({ profile, updateProfile, initials, authentikUser, isAuthenticated, loading }),
[profile, updateProfile, initials, authentikUser, isAuthenticated, loading]
);
if (!mounted) return <>{children}</>;
return (
<UserProfileContext.Provider value={value}>
{children}
</UserProfileContext.Provider>
);
}
export function useUserProfile() {
const ctx = React.useContext(UserProfileContext);
if (!ctx) {
return {
profile: DEFAULT_PROFILE,
updateProfile: () => {},
initials: "",
authentikUser: null,
isAuthenticated: false,
loading: false,
};
}
return ctx;
}