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:
@@ -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>
|
||||
|
||||
90
frontend/app/login/page.tsx
Normal file
90
frontend/app/login/page.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
96
frontend/app/register/page.tsx
Normal file
96
frontend/app/register/page.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -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
|
||||
|
||||
49
frontend/components/shared/AuthGuard.tsx
Normal file
49
frontend/components/shared/AuthGuard.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import { useAuthStore } from "@/stores/authStore";
|
||||
import { Sidebar } from "./Sidebar";
|
||||
|
||||
const PUBLIC_PATHS = ["/login", "/register"];
|
||||
|
||||
export function AuthGuard({ children }: { children: React.ReactNode }) {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const token = useAuthStore((s) => s.token);
|
||||
// Zustand persist hydrates asynchronously — wait for it before rendering
|
||||
const [hydrated, setHydrated] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setHydrated(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hydrated) return;
|
||||
if (!token && !PUBLIC_PATHS.includes(pathname)) {
|
||||
router.replace("/login");
|
||||
}
|
||||
}, [hydrated, token, pathname, router]);
|
||||
|
||||
if (!hydrated) return null;
|
||||
|
||||
// Public pages (login/register) render without the app shell
|
||||
if (PUBLIC_PATHS.includes(pathname)) {
|
||||
return <>{children}</>;
|
||||
}
|
||||
|
||||
// Not logged in yet — blank while redirecting
|
||||
if (!token) return null;
|
||||
|
||||
// Authenticated: render the full app shell
|
||||
return (
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { usePathname, useRouter } from "next/navigation";
|
||||
import {
|
||||
LayoutDashboard,
|
||||
FileText,
|
||||
@@ -10,21 +10,34 @@ import {
|
||||
Heart,
|
||||
Settings,
|
||||
Landmark,
|
||||
LogOut,
|
||||
} from "lucide-react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { ThemeToggle } from "./ThemeToggle";
|
||||
import { useAuthStore } from "@/stores/authStore";
|
||||
|
||||
const NAV = [
|
||||
{ href: "/", label: "Dashboard", icon: LayoutDashboard },
|
||||
{ href: "/bills", label: "Bills", icon: FileText },
|
||||
{ href: "/members", label: "Members", icon: Users },
|
||||
{ href: "/topics", label: "Topics", icon: Tags },
|
||||
{ href: "/following", label: "Following", icon: Heart },
|
||||
{ href: "/settings", label: "Settings", icon: Settings },
|
||||
{ href: "/", label: "Dashboard", icon: LayoutDashboard, adminOnly: false },
|
||||
{ href: "/bills", label: "Bills", icon: FileText, adminOnly: false },
|
||||
{ href: "/members", label: "Members", icon: Users, adminOnly: false },
|
||||
{ href: "/topics", label: "Topics", icon: Tags, adminOnly: false },
|
||||
{ href: "/following", label: "Following", icon: Heart, adminOnly: false },
|
||||
{ href: "/settings", label: "Admin", icon: Settings, adminOnly: true },
|
||||
];
|
||||
|
||||
export function Sidebar() {
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
const qc = useQueryClient();
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const logout = useAuthStore((s) => s.logout);
|
||||
|
||||
function handleLogout() {
|
||||
logout();
|
||||
qc.clear();
|
||||
router.replace("/login");
|
||||
}
|
||||
|
||||
return (
|
||||
<aside className="w-56 shrink-0 border-r border-border bg-card flex flex-col">
|
||||
@@ -34,7 +47,7 @@ export function Sidebar() {
|
||||
</div>
|
||||
|
||||
<nav className="flex-1 p-3 space-y-1">
|
||||
{NAV.map(({ href, label, icon: Icon }) => {
|
||||
{NAV.filter(({ adminOnly }) => !adminOnly || user?.is_admin).map(({ href, label, icon: Icon }) => {
|
||||
const active = href === "/" ? pathname === "/" : pathname.startsWith(href);
|
||||
return (
|
||||
<Link
|
||||
@@ -54,9 +67,25 @@ export function Sidebar() {
|
||||
})}
|
||||
</nav>
|
||||
|
||||
<div className="p-3 border-t border-border flex items-center justify-between">
|
||||
<span className="text-xs text-muted-foreground">Theme</span>
|
||||
<ThemeToggle />
|
||||
<div className="p-3 border-t border-border space-y-2">
|
||||
{user && (
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs text-muted-foreground truncate max-w-[120px]" title={user.email}>
|
||||
{user.email}
|
||||
</span>
|
||||
<button
|
||||
onClick={handleLogout}
|
||||
className="p-1 rounded-md text-muted-foreground hover:text-foreground hover:bg-accent"
|
||||
title="Sign out"
|
||||
>
|
||||
<LogOut className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs text-muted-foreground">Theme</span>
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
|
||||
@@ -17,6 +17,48 @@ const apiClient = axios.create({
|
||||
timeout: 30000,
|
||||
});
|
||||
|
||||
// Attach JWT from localStorage on every request
|
||||
apiClient.interceptors.request.use((config) => {
|
||||
if (typeof window !== "undefined") {
|
||||
try {
|
||||
const stored = localStorage.getItem("pocketveto-auth");
|
||||
if (stored) {
|
||||
const { state } = JSON.parse(stored);
|
||||
if (state?.token) {
|
||||
config.headers.Authorization = `Bearer ${state.token}`;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// ignore parse errors
|
||||
}
|
||||
}
|
||||
return config;
|
||||
});
|
||||
|
||||
interface AuthUser {
|
||||
id: number;
|
||||
email: string;
|
||||
is_admin: boolean;
|
||||
notification_prefs: Record<string, unknown>;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
interface TokenResponse {
|
||||
access_token: string;
|
||||
token_type: string;
|
||||
user: AuthUser;
|
||||
}
|
||||
|
||||
// Auth
|
||||
export const authAPI = {
|
||||
register: (email: string, password: string) =>
|
||||
apiClient.post<TokenResponse>("/api/auth/register", { email, password }).then((r) => r.data),
|
||||
login: (email: string, password: string) =>
|
||||
apiClient.post<TokenResponse>("/api/auth/login", { email, password }).then((r) => r.data),
|
||||
me: () =>
|
||||
apiClient.get<AuthUser>("/api/auth/me").then((r) => r.data),
|
||||
};
|
||||
|
||||
// Bills
|
||||
export const billsAPI = {
|
||||
list: (params?: Record<string, unknown>) =>
|
||||
@@ -73,8 +115,24 @@ export const settingsAPI = {
|
||||
apiClient.post("/api/settings/test-llm").then((r) => r.data),
|
||||
};
|
||||
|
||||
export interface AdminUser {
|
||||
id: number;
|
||||
email: string;
|
||||
is_admin: boolean;
|
||||
follow_count: number;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
// Admin
|
||||
export const adminAPI = {
|
||||
// Users
|
||||
listUsers: () =>
|
||||
apiClient.get<AdminUser[]>("/api/admin/users").then((r) => r.data),
|
||||
deleteUser: (id: number) =>
|
||||
apiClient.delete(`/api/admin/users/${id}`),
|
||||
toggleAdmin: (id: number) =>
|
||||
apiClient.patch<AdminUser>(`/api/admin/users/${id}/toggle-admin`).then((r) => r.data),
|
||||
// Tasks
|
||||
triggerPoll: () =>
|
||||
apiClient.post("/api/admin/trigger-poll").then((r) => r.data),
|
||||
triggerMemberSync: () =>
|
||||
|
||||
27
frontend/stores/authStore.ts
Normal file
27
frontend/stores/authStore.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
|
||||
interface AuthUser {
|
||||
id: number;
|
||||
email: string;
|
||||
is_admin: boolean;
|
||||
}
|
||||
|
||||
interface AuthState {
|
||||
token: string | null;
|
||||
user: AuthUser | null;
|
||||
setAuth: (token: string, user: AuthUser) => void;
|
||||
logout: () => void;
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthState>()(
|
||||
persist(
|
||||
(set) => ({
|
||||
token: null,
|
||||
user: null,
|
||||
setAuth: (token, user) => set({ token, user }),
|
||||
logout: () => set({ token: null, user: null }),
|
||||
}),
|
||||
{ name: "pocketveto-auth" }
|
||||
)
|
||||
);
|
||||
Reference in New Issue
Block a user