Add auto-close registration and admin settings page

First user to register automatically becomes admin and registration
closes. Admins can re-open registration from a new settings page.
Uses Better Auth admin plugin for role management and a new appSettings
table for the registration flag. Mobile tab bar now links to settings
instead of inline logout.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-01 13:51:20 -05:00
co-authored by Claude Opus 4.6
parent c0ba717a93
commit db3a6cc3d4
13 changed files with 2076 additions and 20 deletions
+60
View File
@@ -1,6 +1,66 @@
"use client";
import { IconLock } from "@tabler/icons-react";
import { motion } from "motion/react";
import Link from "next/link";
import { useEffect, useState } from "react";
import { AuthForm } from "@/components/auth-form"; import { AuthForm } from "@/components/auth-form";
export default function RegisterPage() { export default function RegisterPage() {
const [registrationOpen, setRegistrationOpen] = useState<boolean | null>(
null,
);
useEffect(() => {
fetch("/api/registration/status")
.then((res) => res.json())
.then((data) => setRegistrationOpen(data.registrationOpen))
.catch(() => setRegistrationOpen(false));
}, []);
if (registrationOpen === null) {
return <div className="flex min-h-[80vh] items-center justify-center" />;
}
if (!registrationOpen) {
return (
<div className="flex min-h-[80vh] items-center justify-center px-4">
<div className="relative mx-auto w-full max-w-sm">
<div className="absolute -inset-4 rounded-2xl bg-primary/3 blur-2xl" />
<motion.div
className="relative space-y-6 rounded-xl border border-border/50 bg-card/80 p-8 text-center backdrop-blur-sm"
initial={{ opacity: 0, y: 20, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
transition={{
type: "spring" as const,
stiffness: 200,
damping: 20,
}}
>
<div className="mx-auto flex h-12 w-12 items-center justify-center rounded-full bg-primary/10">
<IconLock size={24} className="text-primary" />
</div>
<div className="space-y-2">
<h1 className="font-display text-xl tracking-tight">
Registration Closed
</h1>
<p className="text-sm text-muted-foreground">
New accounts are not being accepted right now. Contact the admin
if you need access.
</p>
</div>
<Link
href="/login"
className="inline-flex h-10 items-center rounded-lg bg-primary px-6 text-sm font-medium text-primary-foreground transition-all hover:shadow-md hover:shadow-primary/20"
>
Sign in instead
</Link>
</motion.div>
</div>
</div>
);
}
return ( return (
<div className="flex min-h-[80vh] items-center justify-center px-4"> <div className="flex min-h-[80vh] items-center justify-center px-4">
<AuthForm mode="register" /> <AuthForm mode="register" />
+190
View File
@@ -0,0 +1,190 @@
"use client";
import {
IconLogout,
IconSettings,
IconShieldLock,
IconUser,
IconUserPlus,
} from "@tabler/icons-react";
import { motion } from "motion/react";
import { useRouter } from "next/navigation";
import { useCallback, useEffect, useState } from "react";
import {
Card,
CardContent,
CardDescription,
CardTitle,
} from "@/components/ui/card";
import { Switch } from "@/components/ui/switch";
import { signOut, useSession } from "@/lib/auth/client";
const sectionVariants = {
hidden: { opacity: 0, y: 20 },
visible: {
opacity: 1,
y: 0,
transition: { type: "spring" as const, stiffness: 200, damping: 24 },
},
};
export default function SettingsPage() {
const { data: session, isPending } = useSession();
const router = useRouter();
const [registrationOpen, setRegistrationOpen] = useState(false);
const [loadingSettings, setLoadingSettings] = useState(true);
const [toggling, setToggling] = useState(false);
const isAdmin = session?.user?.role === "admin";
const fetchSettings = useCallback(async () => {
try {
const res = await fetch("/api/admin/settings");
if (res.ok) {
const data = await res.json();
setRegistrationOpen(data.registrationOpen);
}
} finally {
setLoadingSettings(false);
}
}, []);
useEffect(() => {
if (isPending) return;
if (!session?.user) {
router.replace("/login");
return;
}
if (session.user.role === "admin") {
fetchSettings();
} else {
setLoadingSettings(false);
}
}, [session, isPending, router, fetchSettings]);
async function handleToggleRegistration(checked: boolean) {
setToggling(true);
try {
const res = await fetch("/api/admin/settings", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ registrationOpen: checked }),
});
if (res.ok) {
setRegistrationOpen(checked);
}
} finally {
setToggling(false);
}
}
if (isPending || loadingSettings) {
return <div className="min-h-[60vh]" />;
}
if (!session?.user) return null;
const memberSince = new Date(session.user.createdAt).toLocaleDateString(
undefined,
{ year: "numeric", month: "long" },
);
const initial = session.user.name?.charAt(0).toUpperCase() ?? "?";
return (
<motion.div
className="mx-auto max-w-2xl space-y-8"
initial="hidden"
animate="visible"
variants={{
hidden: {},
visible: { transition: { staggerChildren: 0.15 } },
}}
>
<motion.div variants={sectionVariants}>
<div className="flex items-center gap-2">
<IconSettings size={20} className="text-primary" />
<h1 className="font-display text-3xl tracking-tight">Settings</h1>
</div>
<p className="mt-1 text-sm text-muted-foreground">
Manage your account and preferences
</p>
</motion.div>
{/* Account section */}
<motion.div variants={sectionVariants}>
<div className="mb-3 flex items-center gap-2">
<IconUser size={16} className="text-muted-foreground" />
<h2 className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
Account
</h2>
</div>
<Card>
<CardContent className="flex items-center gap-4">
<div className="flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-primary/10 font-display text-lg text-primary">
{initial}
</div>
<div className="min-w-0 flex-1">
<CardTitle>{session.user.name}</CardTitle>
<CardDescription>{session.user.email}</CardDescription>
<p className="mt-0.5 text-xs text-muted-foreground/60">
Member since {memberSince}
</p>
</div>
</CardContent>
<CardContent className="pt-0">
<button
type="button"
onClick={async () => {
await signOut();
router.push("/");
router.refresh();
}}
className="inline-flex h-9 items-center gap-2 rounded-lg border border-border/50 px-4 text-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<IconLogout size={14} />
Sign out
</button>
</CardContent>
</Card>
</motion.div>
{/* Administration section — admin only */}
{isAdmin && (
<motion.div variants={sectionVariants}>
<div className="mb-3 flex items-center gap-2">
<IconShieldLock size={16} className="text-muted-foreground" />
<h2 className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
Administration
</h2>
<span className="rounded-md bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary">
Admin
</span>
</div>
<Card className="border-l-2 border-l-primary/30">
<CardContent>
<div className="flex items-center justify-between gap-4">
<div className="flex items-start gap-3">
<div className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10">
<IconUserPlus size={16} className="text-primary" />
</div>
<div>
<CardTitle>Open registration</CardTitle>
<CardDescription>
Allow new users to create accounts. Useful for adding
household members.
</CardDescription>
</div>
</div>
<Switch
checked={registrationOpen}
onCheckedChange={handleToggleRegistration}
disabled={toggling}
/>
</div>
</CardContent>
</Card>
</motion.div>
)}
</motion.div>
);
}
+30
View File
@@ -0,0 +1,30 @@
import { headers } from "next/headers";
import { NextResponse } from "next/server";
import { auth } from "@/lib/auth/server";
import { getSetting, setSetting } from "@/lib/services/settings";
export async function GET() {
const session = await auth.api.getSession({ headers: await headers() });
if (!session)
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (session.user.role !== "admin")
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const registrationOpen = (await getSetting("registrationOpen")) === "true";
return NextResponse.json({ registrationOpen });
}
export async function POST(request: Request) {
const session = await auth.api.getSession({ headers: await headers() });
if (!session)
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
if (session.user.role !== "admin")
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
const body = await request.json();
if (typeof body.registrationOpen === "boolean") {
await setSetting("registrationOpen", String(body.registrationOpen));
}
return NextResponse.json({ success: true });
}
+7
View File
@@ -0,0 +1,7 @@
import { NextResponse } from "next/server";
import { isRegistrationOpen } from "@/lib/services/settings";
export async function GET() {
const registrationOpen = await isRegistrationOpen();
return NextResponse.json({ registrationOpen });
}
+4 -18
View File
@@ -1,20 +1,20 @@
"use client"; "use client";
import { IconHome, IconSearch, IconUser } from "@tabler/icons-react"; import { IconHome, IconSearch, IconSettings } from "@tabler/icons-react";
import { motion } from "motion/react"; import { motion } from "motion/react";
import Link from "next/link"; import Link from "next/link";
import { usePathname, useRouter } from "next/navigation"; import { usePathname } from "next/navigation";
import { signOut, useSession } from "@/lib/auth/client"; import { useSession } from "@/lib/auth/client";
const tabs = [ const tabs = [
{ href: "/dashboard", label: "Home", icon: IconHome }, { href: "/dashboard", label: "Home", icon: IconHome },
{ href: "/search", label: "Search", icon: IconSearch }, { href: "/search", label: "Search", icon: IconSearch },
{ href: "/settings", label: "Settings", icon: IconSettings },
] as const; ] as const;
export function MobileTabBar() { export function MobileTabBar() {
const { data: session } = useSession(); const { data: session } = useSession();
const pathname = usePathname(); const pathname = usePathname();
const router = useRouter();
if (!session?.user) return null; if (!session?.user) return null;
@@ -56,20 +56,6 @@ export function MobileTabBar() {
</Link> </Link>
); );
})} })}
<button
type="button"
onClick={async () => {
await signOut();
router.push("/");
router.refresh();
}}
className="flex flex-1 flex-col items-center justify-center gap-0.5"
>
<IconUser size={20} className="text-muted-foreground" />
<span className="text-[10px] font-medium text-muted-foreground">
{session.user.name?.split(" ")[0] ?? "Account"}
</span>
</button>
</div> </div>
{/* Safe area for devices with home indicator */} {/* Safe area for devices with home indicator */}
<div className="h-[env(safe-area-inset-bottom)]" /> <div className="h-[env(safe-area-inset-bottom)]" />
+7 -1
View File
@@ -1,6 +1,6 @@
"use client"; "use client";
import { IconLogout, IconSearch } from "@tabler/icons-react"; import { IconLogout, IconSearch, IconSettings } from "@tabler/icons-react";
import { motion } from "motion/react"; import { motion } from "motion/react";
import Link from "next/link"; import Link from "next/link";
import { usePathname, useRouter } from "next/navigation"; import { usePathname, useRouter } from "next/navigation";
@@ -78,6 +78,12 @@ export function NavBar() {
<span className="hidden text-sm text-muted-foreground sm:inline"> <span className="hidden text-sm text-muted-foreground sm:inline">
{session.user.name} {session.user.name}
</span> </span>
<Link
href="/settings"
className="inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<IconSettings size={14} />
</Link>
<button <button
type="button" type="button"
onClick={async () => { onClick={async () => {
View File
@@ -0,0 +1,10 @@
CREATE TABLE `appSettings` (
`key` text PRIMARY KEY,
`value` text
);
--> statement-breakpoint
ALTER TABLE `session` ADD `impersonatedBy` text;--> statement-breakpoint
ALTER TABLE `user` ADD `role` text DEFAULT 'user';--> statement-breakpoint
ALTER TABLE `user` ADD `banned` integer DEFAULT false;--> statement-breakpoint
ALTER TABLE `user` ADD `banReason` text;--> statement-breakpoint
ALTER TABLE `user` ADD `banExpires` integer;
File diff suppressed because it is too large Load Diff
+4 -1
View File
@@ -1,7 +1,10 @@
"use client"; "use client";
import { adminClient } from "better-auth/client/plugins";
import { createAuthClient } from "better-auth/react"; import { createAuthClient } from "better-auth/react";
export const authClient = createAuthClient(); export const authClient = createAuthClient({
plugins: [adminClient()],
});
export const { signIn, signUp, signOut, useSession } = authClient; export const { signIn, signUp, signOut, useSession } = authClient;
+38
View File
@@ -1,7 +1,14 @@
import { betterAuth } from "better-auth"; import { betterAuth } from "better-auth";
import { drizzleAdapter } from "better-auth/adapters/drizzle"; import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { APIError } from "better-auth/api";
import { admin } from "better-auth/plugins";
import { v4 as uuid } from "uuid"; import { v4 as uuid } from "uuid";
import { db } from "@/lib/db/client"; import { db } from "@/lib/db/client";
import {
getUserCount,
isRegistrationOpen,
setSetting,
} from "@/lib/services/settings";
export const auth = betterAuth({ export const auth = betterAuth({
database: drizzleAdapter(db, { database: drizzleAdapter(db, {
@@ -10,9 +17,40 @@ export const auth = betterAuth({
emailAndPassword: { emailAndPassword: {
enabled: true, enabled: true,
}, },
plugins: [admin()],
advanced: { advanced: {
database: { database: {
generateId: () => uuid(), generateId: () => uuid(),
}, },
}, },
databaseHooks: {
user: {
create: {
before: async (userData) => {
const userCount = await getUserCount();
if (userCount === 0) {
return {
data: {
...userData,
role: "admin",
},
};
}
const open = await isRegistrationOpen();
if (!open) {
throw new APIError("FORBIDDEN", {
message: "Registration is currently closed",
});
}
return { data: userData };
},
after: async () => {
const userCount = await getUserCount();
if (userCount === 1) {
await setSetting("registrationOpen", "false");
}
},
},
},
},
}); });
+12
View File
@@ -24,6 +24,10 @@ export const user = sqliteTable("user", {
.notNull() .notNull()
.default(false), .default(false),
image: text("image"), image: text("image"),
role: text("role").default("user"),
banned: int("banned", { mode: "boolean" }).default(false),
banReason: text("banReason"),
banExpires: int("banExpires", { mode: "timestamp" }),
createdAt: int("createdAt", { mode: "timestamp" }).notNull(), createdAt: int("createdAt", { mode: "timestamp" }).notNull(),
updatedAt: int("updatedAt", { mode: "timestamp" }).notNull(), updatedAt: int("updatedAt", { mode: "timestamp" }).notNull(),
}); });
@@ -37,6 +41,7 @@ export const session = sqliteTable("session", {
expiresAt: int("expiresAt", { mode: "timestamp" }).notNull(), expiresAt: int("expiresAt", { mode: "timestamp" }).notNull(),
ipAddress: text("ipAddress"), ipAddress: text("ipAddress"),
userAgent: text("userAgent"), userAgent: text("userAgent"),
impersonatedBy: text("impersonatedBy"),
createdAt: int("createdAt", { mode: "timestamp" }).notNull(), createdAt: int("createdAt", { mode: "timestamp" }).notNull(),
updatedAt: int("updatedAt", { mode: "timestamp" }).notNull(), updatedAt: int("updatedAt", { mode: "timestamp" }).notNull(),
}); });
@@ -277,3 +282,10 @@ export const titleRecommendations = sqliteTable(
), ),
], ],
); );
// ─── App Settings ───────────────────────────────────────────────────
export const appSettings = sqliteTable("appSettings", {
key: text("key").primaryKey(),
value: text("value"),
});
+32
View File
@@ -0,0 +1,32 @@
import { count, eq } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { appSettings, user } from "@/lib/db/schema";
export async function getSetting(key: string): Promise<string | null> {
const row = await db
.select()
.from(appSettings)
.where(eq(appSettings.key, key))
.get();
return row?.value ?? null;
}
export async function setSetting(key: string, value: string): Promise<void> {
await db
.insert(appSettings)
.values({ key, value })
.onConflictDoUpdate({ target: appSettings.key, set: { value } });
}
export async function getUserCount(): Promise<number> {
const result = await db.select({ count: count() }).from(user).get();
return result?.count ?? 0;
}
export async function isRegistrationOpen(): Promise<boolean> {
const userCount = await getUserCount();
if (userCount === 0) return true;
const setting = await getSetting("registrationOpen");
return setting === "true";
}