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:
@@ -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} />;
|
||||
}
|
||||
|
||||
@@ -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't accepting new accounts right now. You'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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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 },
|
||||
|
||||
@@ -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} />
|
||||
))}
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
Reference in New Issue
Block a user