Add multi-user auth system and admin panel

- User model with email/hashed_password/is_admin/notification_prefs
- JWT auth: POST /api/auth/register, /login, /me
- First registered user auto-promoted to admin
- Migration 0005: users table + user_id FK on follows (clears global follows)
- Follows, dashboard, settings, admin endpoints all require authentication
- Admin endpoints (settings writes, celery triggers) require is_admin
- Frontend: login/register pages, Zustand auth store (localStorage persist)
- AuthGuard component gates all app routes, shows app shell only when authed
- Sidebar shows user email + logout; Admin nav link visible to admins only
- Admin panel (/settings): user list with delete + promote/demote, LLM config,
  data source settings, and manual celery controls

Authored-By: Jack Levy
This commit is contained in:
Jack Levy
2026-02-28 21:40:45 -05:00
parent e418dd9ae0
commit 5b73b60d9e
26 changed files with 917 additions and 52 deletions

View File

@@ -2,7 +2,7 @@ import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import { Providers } from "./providers";
import { Sidebar } from "@/components/shared/Sidebar";
import { AuthGuard } from "@/components/shared/AuthGuard";
const inter = Inter({ subsets: ["latin"] });
@@ -20,14 +20,9 @@ export default function RootLayout({
<html lang="en" suppressHydrationWarning>
<body className={inter.className}>
<Providers>
<div className="flex h-screen bg-background">
<Sidebar />
<main className="flex-1 overflow-auto">
<div className="container mx-auto px-6 py-6 max-w-7xl">
{children}
</div>
</main>
</div>
<AuthGuard>
{children}
</AuthGuard>
</Providers>
</body>
</html>

View File

@@ -0,0 +1,90 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { authAPI } from "@/lib/api";
import { useAuthStore } from "@/stores/authStore";
export default function LoginPage() {
const router = useRouter();
const setAuth = useAuthStore((s) => s.setAuth);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError("");
setLoading(true);
try {
const { access_token, user } = await authAPI.login(email.trim(), password);
setAuth(access_token, { id: user.id, email: user.email, is_admin: user.is_admin });
router.replace("/");
} catch (err: unknown) {
const msg =
(err as { response?: { data?: { detail?: string } } })?.response?.data?.detail ||
"Login failed. Check your email and password.";
setError(msg);
} finally {
setLoading(false);
}
}
return (
<div className="min-h-screen flex items-center justify-center bg-background">
<div className="w-full max-w-sm space-y-6 p-8 border rounded-lg bg-card shadow-sm">
<div>
<h1 className="text-2xl font-bold">PocketVeto</h1>
<p className="text-muted-foreground text-sm mt-1">Sign in to your account</p>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-1">
<label className="text-sm font-medium" htmlFor="email">Email</label>
<input
id="email"
type="email"
required
autoComplete="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="w-full px-3 py-2 border rounded-md bg-background text-sm focus:outline-none focus:ring-2 focus:ring-ring"
/>
</div>
<div className="space-y-1">
<label className="text-sm font-medium" htmlFor="password">Password</label>
<input
id="password"
type="password"
required
autoComplete="current-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full px-3 py-2 border rounded-md bg-background text-sm focus:outline-none focus:ring-2 focus:ring-ring"
/>
</div>
{error && <p className="text-sm text-destructive">{error}</p>}
<button
type="submit"
disabled={loading}
className="w-full py-2 px-4 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:bg-primary/90 disabled:opacity-50"
>
{loading ? "Signing in..." : "Sign in"}
</button>
</form>
<p className="text-sm text-center text-muted-foreground">
No account?{" "}
<Link href="/register" className="text-primary hover:underline">
Register
</Link>
</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,96 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { authAPI } from "@/lib/api";
import { useAuthStore } from "@/stores/authStore";
export default function RegisterPage() {
const router = useRouter();
const setAuth = useAuthStore((s) => s.setAuth);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setError("");
if (password.length < 8) {
setError("Password must be at least 8 characters.");
return;
}
setLoading(true);
try {
const { access_token, user } = await authAPI.register(email.trim(), password);
setAuth(access_token, { id: user.id, email: user.email, is_admin: user.is_admin });
router.replace("/");
} catch (err: unknown) {
const msg =
(err as { response?: { data?: { detail?: string } } })?.response?.data?.detail ||
"Registration failed. Please try again.";
setError(msg);
} finally {
setLoading(false);
}
}
return (
<div className="min-h-screen flex items-center justify-center bg-background">
<div className="w-full max-w-sm space-y-6 p-8 border rounded-lg bg-card shadow-sm">
<div>
<h1 className="text-2xl font-bold">PocketVeto</h1>
<p className="text-muted-foreground text-sm mt-1">Create your account</p>
</div>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-1">
<label className="text-sm font-medium" htmlFor="email">Email</label>
<input
id="email"
type="email"
required
autoComplete="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="w-full px-3 py-2 border rounded-md bg-background text-sm focus:outline-none focus:ring-2 focus:ring-ring"
/>
</div>
<div className="space-y-1">
<label className="text-sm font-medium" htmlFor="password">
Password <span className="text-muted-foreground font-normal">(min 8 chars)</span>
</label>
<input
id="password"
type="password"
required
autoComplete="new-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full px-3 py-2 border rounded-md bg-background text-sm focus:outline-none focus:ring-2 focus:ring-ring"
/>
</div>
{error && <p className="text-sm text-destructive">{error}</p>}
<button
type="submit"
disabled={loading}
className="w-full py-2 px-4 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:bg-primary/90 disabled:opacity-50"
>
{loading ? "Creating account..." : "Create account"}
</button>
</form>
<p className="text-sm text-center text-muted-foreground">
Already have an account?{" "}
<Link href="/login" className="text-primary hover:underline">
Sign in
</Link>
</p>
</div>
</div>
);
}

View File

@@ -2,8 +2,20 @@
import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Settings, Cpu, RefreshCw, CheckCircle, XCircle, Play } from "lucide-react";
import { settingsAPI, adminAPI } from "@/lib/api";
import {
Settings,
Cpu,
RefreshCw,
CheckCircle,
XCircle,
Play,
Users,
Trash2,
ShieldCheck,
ShieldOff,
} from "lucide-react";
import { settingsAPI, adminAPI, type AdminUser } from "@/lib/api";
import { useAuthStore } from "@/stores/authStore";
const LLM_PROVIDERS = [
{ value: "openai", label: "OpenAI (GPT-4o)", hint: "Requires OPENAI_API_KEY in .env" },
@@ -14,19 +26,43 @@ const LLM_PROVIDERS = [
export default function SettingsPage() {
const qc = useQueryClient();
const { data: settings, isLoading } = useQuery({
const currentUser = useAuthStore((s) => s.user);
const { data: settings, isLoading: settingsLoading } = useQuery({
queryKey: ["settings"],
queryFn: () => settingsAPI.get(),
});
const { data: users, isLoading: usersLoading } = useQuery({
queryKey: ["admin-users"],
queryFn: () => adminAPI.listUsers(),
enabled: !!currentUser?.is_admin,
});
const updateSetting = useMutation({
mutationFn: ({ key, value }: { key: string; value: string }) => settingsAPI.update(key, value),
onSuccess: () => qc.invalidateQueries({ queryKey: ["settings"] }),
});
const [testResult, setTestResult] = useState<{ status: string; detail?: string; summary_preview?: string; provider?: string } | null>(null);
const deleteUser = useMutation({
mutationFn: (id: number) => adminAPI.deleteUser(id),
onSuccess: () => qc.invalidateQueries({ queryKey: ["admin-users"] }),
});
const toggleAdmin = useMutation({
mutationFn: (id: number) => adminAPI.toggleAdmin(id),
onSuccess: () => qc.invalidateQueries({ queryKey: ["admin-users"] }),
});
const [testResult, setTestResult] = useState<{
status: string;
detail?: string;
summary_preview?: string;
provider?: string;
} | null>(null);
const [testing, setTesting] = useState(false);
const [taskIds, setTaskIds] = useState<Record<string, string>>({});
const [confirmDelete, setConfirmDelete] = useState<number | null>(null);
const testLLM = async () => {
setTesting(true);
@@ -46,17 +82,102 @@ export default function SettingsPage() {
setTaskIds((prev) => ({ ...prev, [name]: result.task_id }));
};
if (isLoading) return <div className="text-center py-20 text-muted-foreground">Loading settings...</div>;
if (settingsLoading) return <div className="text-center py-20 text-muted-foreground">Loading...</div>;
if (!currentUser?.is_admin) {
return (
<div className="text-center py-20 text-muted-foreground">
Admin access required.
</div>
);
}
return (
<div className="space-y-8 max-w-2xl">
<div>
<h1 className="text-2xl font-bold flex items-center gap-2">
<Settings className="w-5 h-5" /> Settings
<Settings className="w-5 h-5" /> Admin
</h1>
<p className="text-muted-foreground text-sm mt-1">Configure LLM provider and system settings</p>
<p className="text-muted-foreground text-sm mt-1">Manage users, LLM provider, and system settings</p>
</div>
{/* User Management */}
<section className="bg-card border border-border rounded-lg p-6 space-y-4">
<h2 className="font-semibold flex items-center gap-2">
<Users className="w-4 h-4" /> Users
</h2>
{usersLoading ? (
<p className="text-sm text-muted-foreground">Loading users...</p>
) : (
<div className="divide-y divide-border">
{(users ?? []).map((u: AdminUser) => (
<div key={u.id} className="flex items-center justify-between py-3 gap-4">
<div className="min-w-0">
<div className="flex items-center gap-2">
<span className="text-sm font-medium truncate">{u.email}</span>
{u.is_admin && (
<span className="text-xs bg-primary/10 text-primary px-1.5 py-0.5 rounded font-medium">
admin
</span>
)}
{u.id === currentUser.id && (
<span className="text-xs text-muted-foreground">(you)</span>
)}
</div>
<div className="text-xs text-muted-foreground mt-0.5">
{u.follow_count} follow{u.follow_count !== 1 ? "s" : ""} ·{" "}
joined {new Date(u.created_at).toLocaleDateString()}
</div>
</div>
{u.id !== currentUser.id && (
<div className="flex items-center gap-2 shrink-0">
<button
onClick={() => toggleAdmin.mutate(u.id)}
disabled={toggleAdmin.isPending}
title={u.is_admin ? "Remove admin" : "Make admin"}
className="p-1.5 rounded-md text-muted-foreground hover:text-foreground hover:bg-accent transition-colors"
>
{u.is_admin ? (
<ShieldOff className="w-4 h-4" />
) : (
<ShieldCheck className="w-4 h-4" />
)}
</button>
{confirmDelete === u.id ? (
<div className="flex items-center gap-1">
<button
onClick={() => {
deleteUser.mutate(u.id);
setConfirmDelete(null);
}}
className="text-xs px-2 py-1 bg-destructive text-destructive-foreground rounded hover:bg-destructive/90"
>
Confirm
</button>
<button
onClick={() => setConfirmDelete(null)}
className="text-xs px-2 py-1 bg-muted rounded hover:bg-accent"
>
Cancel
</button>
</div>
) : (
<button
onClick={() => setConfirmDelete(u.id)}
title="Delete user"
className="p-1.5 rounded-md text-muted-foreground hover:text-destructive hover:bg-accent transition-colors"
>
<Trash2 className="w-4 h-4" />
</button>
)}
</div>
)}
</div>
))}
</div>
)}
</section>
{/* LLM Provider */}
<section className="bg-card border border-border rounded-lg p-6 space-y-4">
<h2 className="font-semibold flex items-center gap-2">
@@ -99,7 +220,7 @@ export default function SettingsPage() {
<>
<CheckCircle className="w-4 h-4 text-green-500" />
<span className="text-green-600 dark:text-green-400">
{testResult.provider}/{testResult.summary_preview?.slice(0, 50)}...
{testResult.provider} {testResult.summary_preview?.slice(0, 60)}...
</span>
</>
) : (
@@ -113,7 +234,7 @@ export default function SettingsPage() {
</div>
</section>
{/* Polling Settings */}
{/* Data Sources */}
<section className="bg-card border border-border rounded-lg p-6 space-y-4">
<h2 className="font-semibold flex items-center gap-2">
<RefreshCw className="w-4 h-4" /> Data Sources