feat: signup toggle, invite links, admin-created users

- New invites table: token-gated signup, optional email lock,
  role/tier override, single-use, expiry.
- SIGNUPS_DISABLED site setting toggle at /admin/settings.
- databaseHooks.user.create gate in auth/server.ts blocks new account
  creation (email + Google OAuth) when disabled unless a valid invite
  cookie is present; applies invite role/tier and marks it consumed.
- /admin/invites: create/list/revoke shareable invite links.
- /admin/users: "Create user" dialog — admin sets email/role/tier,
  account is pre-verified, user gets a set-password email (admin
  never sees a password).
- Signup page reads ?invite=, validates via public
  /api/v1/invites/[token], locks the form when signups are closed
  and no valid invite is present.
- proxy.ts: allowlist /api/v1/invites/ for anonymous invite checks.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Arnaud
2026-07-03 21:36:40 +02:00
parent c5bc2e1470
commit e0e1ac49d9
22 changed files with 4483 additions and 90 deletions
+10 -83
View File
@@ -1,86 +1,13 @@
"use client";
import { isSignupsDisabled } from "@/lib/site-settings";
import { SignupForm } from "./signup-form";
import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { authClient } from "@/lib/auth/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
export default async function SignupPage({
searchParams,
}: {
searchParams: Promise<{ invite?: string }>;
}) {
const { invite } = await searchParams;
const signupsDisabled = await isSignupsDisabled();
export default function SignupPage() {
const router = useRouter();
const t = useTranslations("auth");
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [loading, setLoading] = useState(false);
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
setLoading(true);
const { error } = await authClient.signUp.email({
name,
email,
password,
callbackURL: "/recipes",
});
setLoading(false);
if (error) {
toast.error(error.message ?? "Sign up failed");
} else {
toast.success("Account created — check your email to verify");
router.push("/login");
}
}
async function handleGoogle() {
await authClient.signIn.social({ provider: "google", callbackURL: "/recipes" });
}
return (
<Card>
<CardHeader className="space-y-1">
<CardTitle className="text-2xl font-semibold tracking-tight">{t("signUpTitle")}</CardTitle>
<CardDescription>{t("signUpSubtitle")}</CardDescription>
</CardHeader>
<form onSubmit={handleSubmit}>
<CardContent className="space-y-4">
<Button variant="outline" className="w-full" type="button" onClick={handleGoogle}>
{t("continueWithGoogle")}
</Button>
<div className="flex items-center gap-2">
<Separator className="flex-1" />
<span className="text-xs text-muted-foreground">{t("or")}</span>
<Separator className="flex-1" />
</div>
<div className="space-y-2">
<Label htmlFor="name">{t("name")}</Label>
<Input id="name" type="text" placeholder={t("namePlaceholder")} value={name} onChange={(e) => setName(e.target.value)} required />
</div>
<div className="space-y-2">
<Label htmlFor="email">{t("email")}</Label>
<Input id="email" type="email" placeholder={t("emailPlaceholder")} value={email} onChange={(e) => setEmail(e.target.value)} required />
</div>
<div className="space-y-2">
<Label htmlFor="password">{t("password")}</Label>
<Input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required minLength={8} />
</div>
<Button className="w-full" type="submit" disabled={loading}>
{loading ? t("signUpLoading") : t("signUpTitle")}
</Button>
</CardContent>
</form>
<CardFooter className="flex justify-center">
<p className="text-sm text-muted-foreground">
{t("alreadyHaveAccount")}{" "}
<Link href="/login" className="underline underline-offset-4 hover:text-foreground">{t("signIn")}</Link>
</p>
</CardFooter>
</Card>
);
return <SignupForm signupsDisabled={signupsDisabled} inviteToken={invite ?? null} />;
}
+164
View File
@@ -0,0 +1,164 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { useTranslations } from "next-intl";
import { authClient } from "@/lib/auth/client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
const INVITE_COOKIE = "epicure_invite";
export function SignupForm({ signupsDisabled, inviteToken }: { signupsDisabled: boolean; inviteToken: string | null }) {
const router = useRouter();
const t = useTranslations("auth");
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [loading, setLoading] = useState(false);
const [inviteState, setInviteState] = useState<"checking" | "valid" | "invalid" | "none">(
inviteToken ? "checking" : "none"
);
const [inviteEmail, setInviteEmail] = useState<string | null>(null);
useEffect(() => {
if (!inviteToken) return;
fetch(`/api/v1/invites/${inviteToken}`)
.then((res) => res.json())
.then((data: { valid: boolean; email: string | null }) => {
setInviteState(data.valid ? "valid" : "invalid");
if (data.valid && data.email) {
setInviteEmail(data.email);
setEmail(data.email);
}
})
.catch(() => setInviteState("invalid"));
}, [inviteToken]);
function setInviteCookie() {
if (inviteToken && inviteState === "valid") {
document.cookie = `${INVITE_COOKIE}=${inviteToken}; path=/; max-age=600; samesite=lax`;
}
}
const locked = signupsDisabled && inviteState !== "valid";
async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault();
setLoading(true);
setInviteCookie();
const { error } = await authClient.signUp.email({
name,
email,
password,
callbackURL: "/recipes",
});
setLoading(false);
if (error) {
toast.error(error.message ?? "Sign up failed");
} else {
toast.success("Account created — check your email to verify");
router.push("/login");
}
}
async function handleGoogle() {
setInviteCookie();
await authClient.signIn.social({ provider: "google", callbackURL: "/recipes" });
}
if (signupsDisabled && inviteState === "checking") {
return (
<Card>
<CardContent className="py-10 text-center text-muted-foreground">Checking invite</CardContent>
</Card>
);
}
if (signupsDisabled && inviteState === "none") {
return (
<Card>
<CardHeader className="space-y-1">
<CardTitle className="text-2xl font-semibold tracking-tight">Signups are closed</CardTitle>
<CardDescription>Epicure isn&apos;t accepting new accounts right now. You&apos;ll need an invite link.</CardDescription>
</CardHeader>
<CardFooter className="flex justify-center">
<Link href="/login" className="text-sm underline underline-offset-4 hover:text-foreground">
Back to login
</Link>
</CardFooter>
</Card>
);
}
if (signupsDisabled && inviteState === "invalid") {
return (
<Card>
<CardHeader className="space-y-1">
<CardTitle className="text-2xl font-semibold tracking-tight">Invite invalid or expired</CardTitle>
<CardDescription>This invite link no longer works. Ask whoever sent it for a new one.</CardDescription>
</CardHeader>
<CardFooter className="flex justify-center">
<Link href="/login" className="text-sm underline underline-offset-4 hover:text-foreground">
Back to login
</Link>
</CardFooter>
</Card>
);
}
return (
<Card>
<CardHeader className="space-y-1">
<CardTitle className="text-2xl font-semibold tracking-tight">{t("signUpTitle")}</CardTitle>
<CardDescription>{t("signUpSubtitle")}</CardDescription>
</CardHeader>
<form onSubmit={handleSubmit}>
<CardContent className="space-y-4">
<Button variant="outline" className="w-full" type="button" onClick={() => { void handleGoogle(); }} disabled={locked}>
{t("continueWithGoogle")}
</Button>
<div className="flex items-center gap-2">
<Separator className="flex-1" />
<span className="text-xs text-muted-foreground">{t("or")}</span>
<Separator className="flex-1" />
</div>
<div className="space-y-2">
<Label htmlFor="name">{t("name")}</Label>
<Input id="name" type="text" placeholder={t("namePlaceholder")} value={name} onChange={(e) => setName(e.target.value)} required />
</div>
<div className="space-y-2">
<Label htmlFor="email">{t("email")}</Label>
<Input
id="email"
type="email"
placeholder={t("emailPlaceholder")}
value={email}
onChange={(e) => setEmail(e.target.value)}
readOnly={!!inviteEmail}
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="password">{t("password")}</Label>
<Input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required minLength={8} />
</div>
<Button className="w-full" type="submit" disabled={loading || locked}>
{loading ? t("signUpLoading") : t("signUpTitle")}
</Button>
</CardContent>
</form>
<CardFooter className="flex justify-center">
<p className="text-sm text-muted-foreground">
{t("alreadyHaveAccount")}{" "}
<Link href="/login" className="underline underline-offset-4 hover:text-foreground">{t("signIn")}</Link>
</p>
</CardFooter>
</Card>
);
}
+34
View File
@@ -0,0 +1,34 @@
import type { Metadata } from "next";
import { listInvites } from "@/lib/invites";
import { InvitesManager } from "@/components/admin/invites-manager";
export const metadata: Metadata = { title: "Invites Admin" };
export default async function AdminInvitesPage() {
const invites = await listInvites();
const appUrl = process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000";
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-bold tracking-tight">Invites</h1>
<p className="text-muted-foreground text-sm mt-1">
Generate shareable signup links. Required when signups are disabled in{" "}
<span className="font-medium">Settings</span>.
</p>
</div>
<InvitesManager
invites={invites.map((i) => ({
id: i.id,
token: i.token,
email: i.email,
role: i.role,
tier: i.tier,
createdAt: i.createdAt.toISOString(),
expiresAt: i.expiresAt?.toISOString() ?? null,
}))}
appUrl={appUrl}
/>
</div>
);
}
+2 -1
View File
@@ -3,12 +3,13 @@ import { headers } from "next/headers";
import { auth } from "@/lib/auth/server";
import { db, users, eq } from "@epicure/db";
import Link from "next/link";
import { Shield, Users, BookOpen, Settings, BarChart3, ClipboardList, HardDrive, Bot, ArrowLeft, Gauge } from "lucide-react";
import { Shield, Users, BookOpen, Settings, BarChart3, ClipboardList, HardDrive, Bot, ArrowLeft, Gauge, Mail } from "lucide-react";
import { cn } from "@/lib/utils";
const adminNav = [
{ href: "/admin", label: "Overview", icon: BarChart3 },
{ href: "/admin/users", label: "Users", icon: Users },
{ href: "/admin/invites", label: "Invites", icon: Mail },
{ href: "/admin/recipes", label: "Recipes", icon: BookOpen },
{ href: "/admin/tiers", label: "Tier Limits", icon: Gauge },
{ href: "/admin/audit-logs", label: "Audit Logs", icon: ClipboardList },
+5 -1
View File
@@ -1,6 +1,7 @@
import type { Metadata } from "next";
import { getAllSiteSettings } from "@/lib/site-settings";
import { getAllSiteSettings, isSignupsDisabled } from "@/lib/site-settings";
import { AdminSettingsForm } from "@/components/admin/admin-settings-form";
import { SignupsToggle } from "@/components/admin/signups-toggle";
export const metadata: Metadata = { title: "Site Settings Admin" };
@@ -24,6 +25,7 @@ const SETTING_GROUPS = [
export default async function AdminSettingsPage() {
const settings = await getAllSiteSettings();
const signupsDisabled = await isSignupsDisabled();
return (
<div className="space-y-8">
@@ -35,6 +37,8 @@ export default async function AdminSettingsPage() {
</p>
</div>
<SignupsToggle initialDisabled={signupsDisabled} />
{SETTING_GROUPS.map((group) => (
<AdminSettingsForm key={group.title} group={group} settings={settings} />
))}
+5 -1
View File
@@ -4,6 +4,7 @@ import { users } from "@epicure/db";
import { desc } from "@epicure/db";
import { Badge } from "@/components/ui/badge";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { CreateUserDialog } from "@/components/admin/create-user-dialog";
import Link from "next/link";
export const metadata: Metadata = { title: "User Management" };
@@ -28,7 +29,10 @@ export default async function AdminUsersPage() {
return (
<div className="space-y-6">
<h1 className="text-2xl font-bold tracking-tight">Users</h1>
<div className="flex items-center justify-between">
<h1 className="text-2xl font-bold tracking-tight">Users</h1>
<CreateUserDialog />
</div>
<div className="rounded-md border">
<table className="w-full text-sm">
<thead className="border-b bg-muted/50">
@@ -0,0 +1,30 @@
import { NextRequest, NextResponse } from "next/server";
import { requireAdmin } from "@/lib/api-auth";
import { db, invites, auditLogs, eq } from "@epicure/db";
import { randomUUID } from "crypto";
interface RouteContext {
params: Promise<{ id: string }>;
}
export async function DELETE(_req: NextRequest, { params }: RouteContext) {
const { session, response } = await requireAdmin();
if (response) return response;
const { id } = await params;
const [deleted] = await db.delete(invites).where(eq(invites.id, id)).returning();
if (!deleted) {
return NextResponse.json({ error: "Invite not found" }, { status: 404 });
}
await db.insert(auditLogs).values({
id: randomUUID(),
userId: session!.user.id,
action: "admin.invite.revoke",
targetType: "invite",
targetId: id,
createdAt: new Date(),
});
return NextResponse.json({ ok: true });
}
@@ -0,0 +1,57 @@
import { NextRequest, NextResponse } from "next/server";
import { requireAdmin } from "@/lib/api-auth";
import { db, auditLogs } from "@epicure/db";
import { createInvite, listInvites } from "@/lib/invites";
import { randomUUID } from "crypto";
const VALID_ROLES = ["user", "moderator", "admin"] as const;
const VALID_TIERS = ["free", "pro"] as const;
export async function GET() {
const { response } = await requireAdmin();
if (response) return response;
const invites = await listInvites();
return NextResponse.json({ invites });
}
export async function POST(req: NextRequest) {
const { session, response } = await requireAdmin();
if (response) return response;
const body = (await req.json()) as {
email?: string;
role?: string;
tier?: string;
expiresInDays?: number;
};
const role = body.role ?? "user";
const tier = body.tier ?? "free";
if (!VALID_ROLES.includes(role as (typeof VALID_ROLES)[number])) {
return NextResponse.json({ error: "Invalid role" }, { status: 400 });
}
if (!VALID_TIERS.includes(tier as (typeof VALID_TIERS)[number])) {
return NextResponse.json({ error: "Invalid tier" }, { status: 400 });
}
const invite = await createInvite({
createdById: session!.user.id,
email: body.email,
role: role as (typeof VALID_ROLES)[number],
tier: tier as (typeof VALID_TIERS)[number],
expiresInDays: body.expiresInDays ?? 7,
});
await db.insert(auditLogs).values({
id: randomUUID(),
userId: session!.user.id,
action: "admin.invite.create",
targetType: "invite",
targetId: invite!.id,
metadata: JSON.stringify({ email: body.email, role, tier }),
createdAt: new Date(),
});
return NextResponse.json({ invite });
}
@@ -13,6 +13,7 @@ const ALLOWED_KEYS: SiteSettingKey[] = [
"OLLAMA_BASE_URL",
"NEXT_PUBLIC_VAPID_PUBLIC_KEY",
"VAPID_PRIVATE_KEY",
"SIGNUPS_DISABLED",
];
async function requireAdmin() {
+100
View File
@@ -0,0 +1,100 @@
import { NextRequest, NextResponse } from "next/server";
import { requireAdmin } from "@/lib/api-auth";
import { auth } from "@/lib/auth/server";
import { db, users, auditLogs, eq } from "@epicure/db";
import { createInvite, consumeInvite, INVITE_COOKIE } from "@/lib/invites";
import { randomBytes, randomUUID } from "crypto";
import { APIError } from "better-auth";
const VALID_ROLES = ["user", "moderator", "admin"] as const;
const VALID_TIERS = ["free", "pro"] as const;
export async function POST(req: NextRequest) {
const { session, response } = await requireAdmin();
if (response) return response;
const body = (await req.json()) as {
email?: string;
name?: string;
role?: string;
tier?: string;
};
const email = body.email?.trim().toLowerCase();
const name = body.name?.trim();
const role = body.role ?? "user";
const tier = body.tier ?? "free";
if (!email || !name) {
return NextResponse.json({ error: "email and name are required" }, { status: 400 });
}
if (!VALID_ROLES.includes(role as (typeof VALID_ROLES)[number])) {
return NextResponse.json({ error: "Invalid role" }, { status: 400 });
}
if (!VALID_TIERS.includes(tier as (typeof VALID_TIERS)[number])) {
return NextResponse.json({ error: "Invalid tier" }, { status: 400 });
}
const [existing] = await db.select({ id: users.id }).from(users).where(eq(users.email, email));
if (existing) {
return NextResponse.json({ error: "A user with this email already exists" }, { status: 409 });
}
// Route creation through the same invite gate the public signup flow uses,
// so it works identically whether signups are currently open or closed —
// and so role/tier assignment goes through the one audited code path.
const invite = await createInvite({
createdById: session!.user.id,
email,
role: role as (typeof VALID_ROLES)[number],
tier: tier as (typeof VALID_TIERS)[number],
expiresInDays: 1,
});
const temporaryPassword = randomBytes(24).toString("base64url");
try {
await auth.api.signUpEmail({
body: { email, name, password: temporaryPassword },
headers: new Headers({ cookie: `${INVITE_COOKIE}=${invite!.token}` }),
});
} catch (err) {
if (err instanceof APIError) {
return NextResponse.json({ error: err.message }, { status: err.statusCode ?? 400 });
}
throw err;
}
const [created] = await db
.update(users)
.set({ emailVerified: true })
.where(eq(users.email, email))
.returning();
if (!created) {
return NextResponse.json({ error: "User creation failed" }, { status: 500 });
}
// The invite gate only consumes on the databaseHooks "after" path when a
// cookie is present on a real request; belt-and-suspenders it here too.
await consumeInvite(invite!.id, created.id);
// Let the new user set their own password instead of the admin knowing it.
await auth.api.requestPasswordReset({
body: { email, redirectTo: "/reset-password" },
});
await db.insert(auditLogs).values({
id: randomUUID(),
userId: session!.user.id,
action: "admin.user.create",
targetType: "user",
targetId: created.id,
metadata: JSON.stringify({ email, role, tier }),
createdAt: new Date(),
});
return NextResponse.json({
user: { id: created.id, email: created.email, name: created.name, role: created.role, tier: created.tier },
});
}
@@ -0,0 +1,15 @@
import { NextRequest, NextResponse } from "next/server";
import { findValidInvite } from "@/lib/invites";
interface RouteContext {
params: Promise<{ token: string }>;
}
export async function GET(_req: NextRequest, { params }: RouteContext) {
const { token } = await params;
const invite = await findValidInvite(token);
if (!invite) {
return NextResponse.json({ valid: false });
}
return NextResponse.json({ valid: true, email: invite.email });
}
@@ -0,0 +1,100 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Plus } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
export function CreateUserDialog() {
const router = useRouter();
const [open, setOpen] = useState(false);
const [email, setEmail] = useState("");
const [name, setName] = useState("");
const [role, setRole] = useState<"user" | "moderator" | "admin">("user");
const [tier, setTier] = useState<"free" | "pro">("free");
const [saving, setSaving] = useState(false);
async function handleCreate() {
if (!email.trim() || !name.trim()) {
toast.error("Email and name are required");
return;
}
setSaving(true);
try {
const res = await fetch("/api/v1/admin/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: email.trim(), name: name.trim(), role, tier }),
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error((data as { error?: string }).error ?? "Failed to create user");
}
toast.success("User created — they'll receive an email to set their password");
setOpen(false);
setEmail("");
setName("");
setRole("user");
setTier("free");
router.refresh();
} catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to create user");
} finally {
setSaving(false);
}
}
return (
<>
<Button size="sm" onClick={() => setOpen(true)}>
<Plus className="h-4 w-4" /> Create user
</Button>
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent className="max-w-md">
<DialogHeader><DialogTitle>Create user</DialogTitle></DialogHeader>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="new-user-email">Email</Label>
<Input id="new-user-email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
</div>
<div className="space-y-2">
<Label htmlFor="new-user-name">Name</Label>
<Input id="new-user-name" value={name} onChange={(e) => setName(e.target.value)} />
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label>Role</Label>
<Select value={role} onValueChange={(v) => setRole(v as typeof role)}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="user">User</SelectItem>
<SelectItem value="moderator">Moderator</SelectItem>
<SelectItem value="admin">Admin</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label>Tier</Label>
<Select value={tier} onValueChange={(v) => setTier(v as typeof tier)}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="free">Free</SelectItem>
<SelectItem value="pro">Pro</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<Button onClick={() => { void handleCreate(); }} disabled={saving} className="w-full">
{saving ? "Creating…" : "Create user"}
</Button>
</div>
</DialogContent>
</Dialog>
</>
);
}
@@ -0,0 +1,157 @@
"use client";
import { useState } from "react";
import { toast } from "sonner";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Copy, Trash2 } from "lucide-react";
type Invite = {
id: string;
token: string;
email: string | null;
role: "user" | "moderator" | "admin";
tier: "free" | "pro";
createdAt: string;
expiresAt: string | null;
};
export function InvitesManager({ invites, appUrl }: { invites: Invite[]; appUrl: string }) {
const router = useRouter();
const [email, setEmail] = useState("");
const [role, setRole] = useState<"user" | "moderator" | "admin">("user");
const [tier, setTier] = useState<"free" | "pro">("free");
const [creating, setCreating] = useState(false);
async function handleCreate() {
setCreating(true);
try {
const res = await fetch("/api/v1/admin/invites", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email: email || undefined, role, tier }),
});
if (!res.ok) throw new Error("Failed to create invite");
setEmail("");
toast.success("Invite created");
router.refresh();
} catch {
toast.error("Failed to create invite");
} finally {
setCreating(false);
}
}
async function handleRevoke(id: string) {
if (!confirm("Revoke this invite? The link will stop working.")) return;
try {
const res = await fetch(`/api/v1/admin/invites/${id}`, { method: "DELETE" });
if (!res.ok) throw new Error("Failed to revoke");
toast.success("Invite revoked");
router.refresh();
} catch {
toast.error("Failed to revoke invite");
}
}
function copyLink(token: string) {
const url = `${appUrl}/signup?invite=${token}`;
void navigator.clipboard.writeText(url);
toast.success("Link copied");
}
return (
<div className="space-y-6">
<section className="rounded-xl border p-6 space-y-4">
<h2 className="font-semibold text-lg">New invite</h2>
<div className="grid grid-cols-1 sm:grid-cols-4 gap-4">
<div className="space-y-1.5 sm:col-span-2">
<Label htmlFor="invite-email">Email (optional)</Label>
<Input
id="invite-email"
type="email"
placeholder="Leave blank for anyone with the link"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
</div>
<div className="space-y-1.5">
<Label>Role</Label>
<Select value={role} onValueChange={(v) => setRole(v as typeof role)}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="user">User</SelectItem>
<SelectItem value="moderator">Moderator</SelectItem>
<SelectItem value="admin">Admin</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1.5">
<Label>Tier</Label>
<Select value={tier} onValueChange={(v) => setTier(v as typeof tier)}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="free">Free</SelectItem>
<SelectItem value="pro">Pro</SelectItem>
</SelectContent>
</Select>
</div>
</div>
<Button onClick={() => { void handleCreate(); }} disabled={creating} size="sm">
{creating ? "Creating…" : "Create invite"}
</Button>
</section>
<div className="rounded-md border">
<table className="w-full text-sm">
<thead className="border-b bg-muted/50">
<tr>
<th className="px-4 py-3 text-left font-medium">Email</th>
<th className="px-4 py-3 text-left font-medium">Role</th>
<th className="px-4 py-3 text-left font-medium">Tier</th>
<th className="px-4 py-3 text-left font-medium">Expires</th>
<th className="px-4 py-3 text-left font-medium"></th>
</tr>
</thead>
<tbody>
{invites.length === 0 && (
<tr>
<td colSpan={5} className="px-4 py-6 text-center text-muted-foreground">
No active invites.
</td>
</tr>
)}
{invites.map((invite) => (
<tr key={invite.id} className="border-b last:border-0">
<td className="px-4 py-3">{invite.email ?? <span className="text-muted-foreground">Anyone</span>}</td>
<td className="px-4 py-3">{invite.role}</td>
<td className="px-4 py-3">{invite.tier}</td>
<td className="px-4 py-3 text-muted-foreground">
{invite.expiresAt ? new Date(invite.expiresAt).toLocaleDateString() : "Never"}
</td>
<td className="px-4 py-3">
<div className="flex justify-end gap-2">
<Button variant="outline" size="icon-sm" onClick={() => copyLink(invite.token)}>
<Copy className="h-3.5 w-3.5" />
</Button>
<Button
variant="outline"
size="icon-sm"
className="text-destructive hover:text-destructive"
onClick={() => { void handleRevoke(invite.id); }}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
@@ -0,0 +1,55 @@
"use client";
import { useState } from "react";
import { toast } from "sonner";
import { Label } from "@/components/ui/label";
import { Switch } from "@/components/ui/switch";
export function SignupsToggle({ initialDisabled }: { initialDisabled: boolean }) {
const [disabled, setDisabled] = useState(initialDisabled);
const [saving, setSaving] = useState(false);
async function handleChange(checked: boolean) {
setSaving(true);
const previous = disabled;
setDisabled(checked);
try {
const res = await fetch("/api/v1/admin/settings", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ SIGNUPS_DISABLED: checked ? "true" : null }),
});
if (!res.ok) throw new Error("Save failed");
toast.success(checked ? "Signups disabled" : "Signups enabled");
} catch {
setDisabled(previous);
toast.error("Failed to update");
} finally {
setSaving(false);
}
}
return (
<section className="rounded-xl border p-6 space-y-1">
<div className="flex items-center justify-between">
<div>
<h2 className="font-semibold text-lg">Signups</h2>
<p className="text-sm text-muted-foreground mt-1">
When disabled, only people with a valid invite link can create an account.
</p>
</div>
<div className="flex items-center gap-2 shrink-0">
<Label htmlFor="signups-disabled" className="text-sm">
{disabled ? "Disabled" : "Open"}
</Label>
<Switch
id="signups-disabled"
checked={disabled}
disabled={saving}
onCheckedChange={(checked) => { void handleChange(checked); }}
/>
</div>
</div>
</section>
);
}
+19 -1
View File
@@ -3,6 +3,8 @@ import { genericOAuth } from "better-auth/plugins";
import { drizzleAdapter } from "better-auth/adapters/drizzle";
import { db, users, sessions, accounts, verifications, eq, count } from "@epicure/db";
import { sendEmail, verifyEmailHtml, resetPasswordHtml, welcomeHtml } from "@/lib/email";
import { isSignupsDisabled } from "@/lib/site-settings";
import { findValidInvite, consumeInvite, INVITE_COOKIE } from "@/lib/invites";
export const auth = betterAuth({
trustedOrigins: [process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000"],
@@ -82,12 +84,28 @@ export const auth = betterAuth({
databaseHooks: {
user: {
create: {
after: async (user) => {
before: async (user, context) => {
if (!(await isSignupsDisabled())) return;
const token = context?.getCookie(INVITE_COOKIE);
const invite = token ? await findValidInvite(token, user.email) : null;
if (!invite) return false;
return { data: { ...user, role: invite.role, tier: invite.tier } };
},
after: async (user, context) => {
// First registered user becomes admin
const result = await db.select({ total: count() }).from(users);
if ((result[0]?.total ?? 0) === 1) {
await db.update(users).set({ role: "admin" }).where(eq(users.id, user.id));
}
// Consume the invite that gated this signup, if any (regardless of
// whether signups have since been re-enabled/disabled).
const token = context?.getCookie(INVITE_COOKIE);
const invite = token ? await findValidInvite(token, user.email) : null;
if (invite) await consumeInvite(invite.id, user.id);
// Welcome email (fire and forget)
sendEmail({
to: user.email,
+53
View File
@@ -0,0 +1,53 @@
import { db, invites, eq, isNull } from "@epicure/db";
import { randomUUID, randomBytes } from "crypto";
export const INVITE_COOKIE = "epicure_invite";
export function generateInviteToken(): string {
return randomBytes(24).toString("base64url");
}
export async function findValidInvite(token: string, email?: string | null) {
const [invite] = await db.select().from(invites).where(eq(invites.token, token));
if (!invite) return null;
if (invite.usedAt) return null;
if (invite.expiresAt && invite.expiresAt < new Date()) return null;
if (invite.email && email && invite.email.toLowerCase() !== email.toLowerCase()) return null;
return invite;
}
export async function consumeInvite(inviteId: string, userId: string): Promise<void> {
await db
.update(invites)
.set({ usedAt: new Date(), usedById: userId })
.where(eq(invites.id, inviteId));
}
export async function createInvite(opts: {
createdById: string;
email?: string | null;
role?: "user" | "moderator" | "admin";
tier?: "free" | "pro";
expiresInDays?: number | null;
}) {
const [invite] = await db
.insert(invites)
.values({
id: randomUUID(),
token: generateInviteToken(),
email: opts.email || null,
role: opts.role ?? "user",
tier: opts.tier ?? "free",
createdById: opts.createdById,
expiresAt: opts.expiresInDays ? new Date(Date.now() + opts.expiresInDays * 86400_000) : null,
})
.returning();
return invite;
}
export async function listInvites() {
return db.query.invites.findMany({
where: isNull(invites.usedAt),
orderBy: (i, { desc }) => [desc(i.createdAt)],
});
}
+6 -1
View File
@@ -8,7 +8,8 @@ export type SiteSettingKey =
| "OPENROUTER_DEFAULT_MODEL"
| "OLLAMA_BASE_URL"
| "NEXT_PUBLIC_VAPID_PUBLIC_KEY"
| "VAPID_PRIVATE_KEY";
| "VAPID_PRIVATE_KEY"
| "SIGNUPS_DISABLED";
const SECRET_KEYS: SiteSettingKey[] = [
"OPENAI_API_KEY",
@@ -69,6 +70,10 @@ export async function getAllSiteSettings(): Promise<Record<string, { value: stri
return result;
}
export async function isSignupsDisabled(): Promise<boolean> {
return (await getSiteSetting("SIGNUPS_DISABLED")) === "true";
}
export async function setSiteSetting(
key: SiteSettingKey,
value: string | null,
+1 -1
View File
@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { getSessionCookie } from "better-auth/cookies";
const PUBLIC_PATHS = ["/login", "/signup", "/verify-email", "/forgot-password", "/reset-password", "/api/auth", "/r/", "/u/", "/docs", "/api/v1/openapi.json", "/api/webhooks"];
const PUBLIC_PATHS = ["/login", "/signup", "/verify-email", "/forgot-password", "/reset-password", "/api/auth", "/r/", "/u/", "/docs", "/api/v1/openapi.json", "/api/webhooks", "/api/v1/invites/"];
const ADMIN_PATHS = ["/admin"];
export async function proxy(request: NextRequest) {
@@ -0,0 +1,16 @@
CREATE TABLE "invites" (
"id" text PRIMARY KEY NOT NULL,
"token" text NOT NULL,
"email" text,
"role" "user_role" DEFAULT 'user' NOT NULL,
"tier" "tier" DEFAULT 'free' NOT NULL,
"created_by_id" text NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"expires_at" timestamp,
"used_at" timestamp,
"used_by_id" text,
CONSTRAINT "invites_token_uniq" UNIQUE("token")
);
--> statement-breakpoint
ALTER TABLE "invites" ADD CONSTRAINT "invites_created_by_id_users_id_fk" FOREIGN KEY ("created_by_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE "invites" ADD CONSTRAINT "invites_used_by_id_users_id_fk" FOREIGN KEY ("used_by_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;
File diff suppressed because it is too large Load Diff
@@ -106,6 +106,13 @@
"when": 1782984288632,
"tag": "0014_late_marvex",
"breakpoints": true
},
{
"idx": 15,
"version": "7",
"when": 1783105214683,
"tag": "0015_aromatic_lester",
"breakpoints": true
}
]
}
+21 -1
View File
@@ -8,7 +8,7 @@ import {
unique,
} from "drizzle-orm/pg-core";
import { relations } from "drizzle-orm";
import { users, tierEnum } from "./users";
import { users, tierEnum, userRoleEnum } from "./users";
export const tierDefinitions = pgTable("tier_definitions", {
tier: tierEnum("tier").primaryKey(),
@@ -50,6 +50,26 @@ export const siteSettings = pgTable("site_settings", {
updatedById: text("updated_by_id").references(() => users.id, { onDelete: "set null" }),
});
export const invites = pgTable("invites", {
id: text("id").primaryKey(),
token: text("token").notNull(),
email: text("email"),
role: userRoleEnum("role").notNull().default("user"),
tier: tierEnum("tier").notNull().default("free"),
createdById: text("created_by_id").notNull().references(() => users.id, { onDelete: "cascade" }),
createdAt: timestamp("created_at").notNull().defaultNow(),
expiresAt: timestamp("expires_at"),
usedAt: timestamp("used_at"),
usedById: text("used_by_id").references(() => users.id, { onDelete: "set null" }),
}, (t) => [
unique("invites_token_uniq").on(t.token),
]);
export const userUsageRelations = relations(userUsage, ({ one }) => ({
user: one(users, { fields: [userUsage.userId], references: [users.id] }),
}));
export const invitesRelations = relations(invites, ({ one }) => ({
createdBy: one(users, { fields: [invites.createdById], references: [users.id] }),
usedBy: one(users, { fields: [invites.usedById], references: [users.id] }),
}));