Skip to content

Open AI UGC — free, open-source alternative to Arcads and MakeUGC. Generate AI UGC video ads with realistic AI actors using Veo 3.1, Seedance 2, Grok Video, and Happy Horse 1. Self-host on Next.js + Stripe + MUAPI.

feat: add API key login method and custom API key credit bypass support

jaiprasad04dcc04fb51f91
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index edc3bd6..7380875 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -40,6 +40,7 @@ model User {
emailVerified DateTime?
image String?
credits Int @default(10)
+ customApiKey String? @db.Text
accounts Account[]
sessions Session[]
creations Creation[]
diff --git a/src/app/api/generate/route.js b/src/app/api/generate/route.js
index b7c08b5..3ce3763 100644
--- a/src/app/api/generate/route.js
+++ b/src/app/api/generate/route.js
@@ -18,9 +18,14 @@ export async function POST(req) {
return new NextResponse("Unauthorized", { status: 401 });
}
- const { modelId, prompt, settings, images } = await req.json();
+ const body = await req.json();
+ const { modelId, prompt, settings, images } = body;
- const apiKey = process.env.UGC_API_KEY;
+ const headerApiKey = req.headers.get("x-custom-api-key");
+ const customApiKey = headerApiKey || body.customApiKey || session.user.customApiKey || null;
+ const isUsingCustomKey = Boolean(customApiKey && customApiKey.trim().length > 0);
+
+ const apiKey = isUsingCustomKey ? customApiKey.trim() : process.env.UGC_API_KEY;
if (!apiKey) {
return new NextResponse("API Key not configured", { status: 500 });
}
@@ -51,14 +56,20 @@ export async function POST(req) {
requiredCredits = duration * 50;
}
- // Check credits
- const user = await prisma.user.findUnique({
- where: { id: session.user.id },
- select: { credits: true }
- });
+ if (isUsingCustomKey) {
+ requiredCredits = 0;
+ }
+
+ // Check credits if not using custom key
+ if (!isUsingCustomKey) {
+ const user = await prisma.user.findUnique({
+ where: { id: session.user.id },
+ select: { credits: true }
+ });
- if (!user || user.credits < requiredCredits) {
- return NextResponse.json({ error: `Insufficient credits. This requires ${requiredCredits} credits but you only have ${user?.credits || 0}.` }, { status: 403 });
+ if (!user || user.credits < requiredCredits) {
+ return NextResponse.json({ error: `Insufficient credits. This requires ${requiredCredits} credits but you only have ${user?.credits || 0}.` }, { status: 403 });
+ }
}
// Prepare payload based on MUAPI specs
@@ -105,11 +116,13 @@ export async function POST(req) {
}
});
- // Deduct required credits
- await prisma.user.update({
- where: { id: session.user.id },
- data: { credits: { decrement: requiredCredits } }
- });
+ // Deduct required credits if not using custom key
+ if (!isUsingCustomKey && requiredCredits > 0) {
+ await prisma.user.update({
+ where: { id: session.user.id },
+ data: { credits: { decrement: requiredCredits } }
+ });
+ }
return NextResponse.json({
success: true,
diff --git a/src/app/api/user/apikey/route.js b/src/app/api/user/apikey/route.js
new file mode 100644
index 0000000..7ec26a5
--- /dev/null
+++ b/src/app/api/user/apikey/route.js
@@ -0,0 +1,49 @@
+import { NextResponse } from "next/server";
+import { getServerSession } from "next-auth/next";
+import { authOptions } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
+
+export async function POST(req) {
+ try {
+ const session = await getServerSession(authOptions);
+ if (!session || !session.user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ const body = await req.json();
+ const apiKey = body.apiKey ? String(body.apiKey).trim() : null;
+
+ const updatedUser = await prisma.user.update({
+ where: { id: session.user.id },
+ data: { customApiKey: apiKey },
+ select: { id: true, credits: true, customApiKey: true }
+ });
+
+ return NextResponse.json({
+ success: true,
+ customApiKey: updatedUser.customApiKey,
+ });
+ } catch (error) {
+ console.error("Error updating custom API key:", error);
+ return NextResponse.json({ error: error.message || "Failed to update API key" }, { status: 500 });
+ }
+}
+
+export async function DELETE(req) {
+ try {
+ const session = await getServerSession(authOptions);
+ if (!session || !session.user) {
+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
+ }
+
+ await prisma.user.update({
+ where: { id: session.user.id },
+ data: { customApiKey: null }
+ });
+
+ return NextResponse.json({ success: true, customApiKey: null });
+ } catch (error) {
+ console.error("Error clearing custom API key:", error);
+ return NextResponse.json({ error: error.message || "Failed to remove API key" }, { status: 500 });
+ }
+}
diff --git a/src/app/login/page.js b/src/app/login/page.js
index fc8732e..c22d12e 100644
--- a/src/app/login/page.js
+++ b/src/app/login/page.js
@@ -1,9 +1,10 @@
"use client";
import { signIn, useSession } from "next-auth/react";
-import { useEffect, Suspense } from "react";
+import { useEffect, useState, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
-import { FaGoogle, FaInfoCircle } from "react-icons/fa";
+import { FaGoogle, FaKey, FaInfoCircle, FaArrowRight } from "react-icons/fa";
+import toast, { Toaster } from "react-hot-toast";
function LoginContent() {
const { data: session, status } = useSession();
@@ -11,39 +12,153 @@ function LoginContent() {
const searchParams = useSearchParams();
const next = searchParams.get("callbackUrl") || searchParams.get("next") || "/";
+ const [activeTab, setActiveTab] = useState("google"); // "google" | "apikey"
+ const [apiKeyInput, setApiKeyInput] = useState("");
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
useEffect(() => {
if (status === "authenticated") {
router.push(next);
}
}, [status, router, next]);
+ const handleApiKeyLogin = async (e) => {
+ e.preventDefault();
+ const key = apiKeyInput.trim();
+ if (!key) {
+ toast.error("Please enter a valid MuAPI key");
+ return;
+ }
+ if (key.length < 5) {
+ toast.error("API Key appears too short");
+ return;
+ }
+
+ setIsSubmitting(true);
+ try {
+ const res = await signIn("credentials", {
+ apiKey: key,
+ redirect: false,
+ callbackUrl: next,
+ });
+
+ if (res?.error) {
+ toast.error(res.error || "Failed to sign in with API key");
+ } else {
+ toast.success("Signed in with API Key successfully!");
+ router.push(next);
+ }
+ } catch (err) {
+ console.error(err);
+ toast.error("An error occurred during API key authentication");
+ } finally {
+ setIsSubmitting(false);
+ }
+ };
+
return (
<div className="min-h-dvh flex items-center justify-center bg-bg-page px-6 text-primary-text select-none">
- <div className="relative bg-bg-card border border-divider w-full max-w-md rounded-lg p-8 space-y-8 shadow-2xl animate-scale-up">
- <div className="flex flex-col items-center text-center space-y-4">
+ <Toaster position="top-right" />
+ <div className="relative bg-bg-card border border-divider w-full max-w-md rounded-xl p-8 space-y-6 shadow-2xl animate-scale-up">
+ <div className="flex flex-col items-center text-center space-y-3">
<div className="w-14 h-14 rounded-full bg-primary/10 flex items-center justify-center text-2xl text-primary font-black shadow-md shadow-primary/15">
- A
+ 📹
</div>
- <h2 className="text-2xl font-black uppercase tracking-tight">Sign In to Studio</h2>
- <p className="text-xs font-semibold text-secondary-text leading-relaxed px-4">
- Sign in with Google to enable predictions, save generation history, and top up credits packages.
+ <h2 className="text-2xl font-black uppercase tracking-tight">Sign In to UGC Creator</h2>
+ <p className="text-xs font-semibold text-secondary-text leading-relaxed px-2">
+ Choose your preferred sign-in method: Google Account or custom MuAPI Key.
</p>
</div>
- <div className="space-y-4">
+ {/* Auth Method Selector Tabs */}
+ <div className="flex bg-bg-page p-1 rounded-lg border border-divider/60">
<button
- onClick={() => signIn("google", { callbackUrl: next })}
- className="w-full py-3.5 bg-white text-neutral-900 rounded-full text-xs font-bold flex items-center justify-center gap-3 hover:opacity-90 transition-all shadow-md active:scale-[0.98] cursor-pointer"
+ type="button"
+ onClick={() => setActiveTab("google")}
+ className={`flex-1 py-2 rounded-md text-xs font-bold transition-all flex items-center justify-center gap-2 ${
+ activeTab === "google"
+ ? "bg-bg-card text-white shadow-sm border border-divider/40"
+ : "text-secondary-text hover:text-white"
+ }`}
>
- <FaGoogle className="text-sm text-red-500" />
- <span>Continue with Google</span>
+ <FaGoogle className="text-red-400" />
+ <span>Google Account</span>
+ </button>
+
+ <button
+ type="button"
+ onClick={() => setActiveTab("apikey")}
+ className={`flex-1 py-2 rounded-md text-xs font-bold transition-all flex items-center justify-center gap-2 ${
+ activeTab === "apikey"
+ ? "bg-bg-card text-white shadow-sm border border-divider/40"
+ : "text-secondary-text hover:text-white"
+ }`}
+ >
+ <FaKey className="text-amber-400" />
+ <span>Use API Key</span>
</button>
</div>
+ {/* Tab Content */}
+ {activeTab === "google" ? (
+ <div className="space-y-4 pt-2">
+ <button
+ onClick={() => signIn("google", { callbackUrl: next })}
+ className="w-full py-3.5 bg-white text-neutral-900 rounded-full text-xs font-bold flex items-center justify-center gap-3 hover:opacity-90 transition-all shadow-md active:scale-[0.98] cursor-pointer"
+ >
+ <FaGoogle className="text-sm text-red-500" />
+ <span>Continue with Google</span>
+ </button>
+ <p className="text-[11px] text-center text-secondary-text">
+ Uses system credit balance. Ideal for credit pack purchases.
+ </p>
+ </div>
+ ) : (
+ <form onSubmit={handleApiKeyLogin} className="space-y-4 pt-2">
+ <div className="space-y-1.5">
+ <label className="block text-[11px] uppercase font-bold text-secondary-text tracking-wider">
+ MuAPI Key
+ </label>
+ <div className="relative">
+ <input
+ type="password"
+ value={apiKeyInput}
+ onChange={(e) => setApiKeyInput(e.target.value)}
+ placeholder="Enter your mu_... key"
+ className="w-full bg-bg-page border border-divider rounded-lg px-3.5 py-2.5 text-xs text-white placeholder-secondary-text/50 focus:outline-none focus:border-primary transition-colors"
+ />
+ </div>
+ <div className="flex justify-end">
+ <a
+ href="https://muapi.ai"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-[10px] text-primary hover:underline font-semibold"
+ >
+ Get API Key from MuAPI →
+ </a>
+ </div>
+ </div>
+
+ <button
+ type="submit"
+ disabled={isSubmitting || !apiKeyInput.trim()}
+ className="w-full py-3 bg-primary hover:bg-primary/90 text-white rounded-full text-xs font-bold flex items-center justify-center gap-2 transition-all shadow-md active:scale-[0.98] disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
+ >
+ <span>{isSubmitting ? "Authenticating..." : "Sign In with API Key"}</span>
+ <FaArrowRight className="text-xs" />
+ </button>
+
+ <p className="text-[11px] text-center text-amber-400/90 font-medium">
+ ⚡ Generate UGC videos using your API key. 0 website credits required!
+ </p>
+ </form>
+ )}
+
<div className="flex items-start gap-2.5 bg-primary/5 border border-primary/10 p-3.5 rounded text-[11px] leading-relaxed text-secondary-text">
<FaInfoCircle className="text-primary text-xs shrink-0 mt-0.5" />
<span>
- By signing in, you agree to our Terms of Service. Purchases are stripe-secured and credit balance addition is automated.
+ By signing in, you agree to our Terms of Service. API keys are kept secure and encrypted for generation calls.
</span>
</div>
</div>
@@ -53,11 +168,13 @@ function LoginContent() {
export default function Login() {
return (
- <Suspense fallback={
- <div className="min-h-dvh flex items-center justify-center bg-bg-page text-primary-text">
- <div className="w-8 h-8 border-2 border-primary border-t-transparent rounded-full animate-spin" />
- </div>
- }>
+ <Suspense
+ fallback={
+ <div className="min-h-dvh flex items-center justify-center bg-bg-page text-primary-text">
+ <div className="w-8 h-8 border-2 border-primary border-t-transparent rounded-full animate-spin" />
+ </div>
+ }
+ >
<LoginContent />
</Suspense>
);
diff --git a/src/components/Navbar.js b/src/components/Navbar.js
index 4b69bc7..5b111d2 100644
--- a/src/components/Navbar.js
+++ b/src/components/Navbar.js
@@ -5,23 +5,30 @@ import { useSession, signOut } from "next-auth/react";
import { useState, useEffect } from "react";
import { usePathname } from "next/navigation";
import { IoClose, IoMenu } from "react-icons/io5";
-import { FiMoon, FiSun, FiLogOut, FiDollarSign, FiPlus, FiUser } from "react-icons/fi";
+import { FiMoon, FiSun, FiLogOut, FiDollarSign, FiPlus, FiUser, FiKey, FiCheck, FiX, FiTrash2 } from "react-icons/fi";
import { SiVercel } from "react-icons/si";
import config from "@/lib/config";
+import toast from "react-hot-toast";
export default function Navbar() {
- const { data: session, status } = useSession();
+ const { data: session, status, update: updateSession } = useSession();
const pathname = usePathname();
const [isOpen, setIsOpen] = useState(false);
const [isProfileOpen, setIsProfileOpen] = useState(false);
+ const [isApiKeyModalOpen, setIsApiKeyModalOpen] = useState(false);
+ const [apiKeyInput, setApiKeyInput] = useState("");
+ const [savingKey, setSavingKey] = useState(false);
const appName = config?.appName || "AI SaaS";
const logoLetter = appName.trim().charAt(0).toUpperCase();
- // Eagerly prefetch workspace/gallery routes for fast tabs
+ const isApiKeyActive = Boolean(session?.user?.customApiKey);
+
useEffect(() => {
- // Prefetch common routes
- }, []);
+ if (session?.user?.customApiKey) {
+ setApiKeyInput(session.user.customApiKey);
+ }
+ }, [session?.user?.customApiKey]);
const appMatch = pathname ? pathname.match(/^\/app\/([^\/]+)/) : null;
const currentAppId = appMatch ? appMatch[1] : null;
@@ -38,11 +45,58 @@ export default function Navbar() {
{ name: "Pricing", path: "/pricing" },
];
+ const handleSaveApiKey = async (e) => {
+ e.preventDefault();
+ const key = apiKeyInput.trim();
+ if (!key) {
+ toast.error("Please enter a valid API Key");
+ return;
+ }
+ setSavingKey(true);
+ try {
+ const res = await fetch("/api/user/apikey", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ apiKey: key }),
+ });
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.error || "Failed to save API key");
+
+ await updateSession({ customApiKey: key });
+ toast.success("Custom API Key updated!");
+ setIsApiKeyModalOpen(false);
+ window.location.reload();
+ } catch (err) {
+ toast.error(err.message || "Failed to save API Key");
+ } finally {
+ setSavingKey(false);
+ }
+ };
+
+ const handleRemoveApiKey = async () => {
+ setSavingKey(true);
+ try {
+ const res = await fetch("/api/user/apikey", { method: "DELETE" });
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.error || "Failed to remove API key");
+
+ await updateSession({ customApiKey: null });
+ setApiKeyInput("");
+ toast.success("Custom API Key removed");
+ setIsApiKeyModalOpen(false);
+ window.location.reload();
+ } catch (err) {
+ toast.error(err.message || "Failed to remove API Key");
+ } finally {
+ setSavingKey(false);
+ }
+ };
+
return (
<header className="sticky top-0 z-50 w-full glass-panel border-b border-divider/50 shadow-md">
<div className="mx-auto flex max-w-7xl items-center justify-between px-4 py-4 sm:px-6 lg:px-8">
- {/* Logo and Brand Title (Visible at all times) */}
+ {/* Logo and Brand Title */}
<Link href="/" className="flex items-center gap-2 transition-transform hover:scale-[1.02] active:scale-95">
<div className="flex h-9 w-9 items-center justify-center rounded-lg bg-primary text-white font-extrabold text-lg shadow-md shadow-primary/30">
{logoLetter}
@@ -74,7 +128,7 @@ export default function Navbar() {
</nav>
{/* Desktop Actions Section */}
- <div className="hidden md:flex items-center gap-4">
+ <div className="hidden md:flex items-center gap-3">
{/* Vercel Deploy Button */}
<a
@@ -87,20 +141,36 @@ export default function Navbar() {
<span>Deploy</span>
</a>
+ {status === "authenticated" && (
+ <button
+ onClick={() => setIsApiKeyModalOpen(true)}
+ className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-bold border transition-all cursor-pointer ${
+ isApiKeyActive
+ ? "bg-amber-500/10 border-amber-500/30 text-amber-400 hover:bg-amber-500/20"
+ : "bg-bg-page/50 border-divider text-secondary-text hover:text-white hover:border-primary/40"
+ }`}
+ >
+ <FiKey className={isApiKeyActive ? "text-amber-400" : "text-secondary-text"} />
+ <span>{isApiKeyActive ? "Custom API Key" : "Add API Key"}</span>
+ </button>
+ )}
+
{status === "authenticated" ? (
<div className="flex items-center">
{/* Credit Balance indicator */}
<div className="flex items-center h-9 border border-divider rounded-l bg-bg-page/30 overflow-hidden pr-2">
<span className="font-bold text-[13px] px-3 flex items-center text-primary-text gap-1">
<FiDollarSign className="text-emerald-500 text-xs" />
- {session.user.credits !== undefined ? session.user.credits : 0}
+ {isApiKeyActive ? "∞ (API Key)" : session.user.credits !== undefined ? session.user.credits : 0}
</span>
- <Link
- href="/pricing"
- className="flex items-center justify-center w-5 h-5 rounded hover:bg-bg-card text-secondary-text transition-colors"
- >
- <FiPlus size={14} />
- </Link>
+ {!isApiKeyActive && (
+ <Link
+ href="/pricing"
+ className="flex items-center justify-center w-5 h-5 rounded hover:bg-bg-card text-secondary-text transition-colors"
+ >
+ <FiPlus size={14} />
+ </Link>
+ )}
</div>
{/* Profile Menu Toggle */}
@@ -123,13 +193,20 @@ export default function Navbar() {
{/* Profile Dropdown */}
{isProfileOpen && (
- <div className="absolute right-0 top-11 w-48 rounded border border-divider bg-bg-card p-1 shadow-lg z-[100] animate-scale-up">
+ <div className="absolute right-0 top-11 w-52 rounded border border-divider bg-bg-card p-1 shadow-lg z-[100] animate-scale-up">
<div className="px-3 py-2 text-xs text-secondary-text border-b border-divider/50 mb-1 truncate">
{session.user.email}
</div>
+ <button
+ onClick={() => setIsApiKeyModalOpen(true)}
+ className="flex w-full items-center gap-2 rounded px-3 py-2 text-left text-xs font-semibold text-primary-text hover:bg-primary/10 transition-colors"
+ >
+ <FiKey size={14} className="text-amber-400" />
+ <span>{isApiKeyActive ? "Manage API Key" : "Add API Key"}</span>
+ </button>
<button
onClick={() => signOut({ callbackUrl: "/login" })}
- className="flex w-full items-center gap-2 rounded px-3 py-2 text-left text-sm font-semibold text-red-500 hover:bg-red-500/10 transition-colors"
+ className="flex w-full items-center gap-2 rounded px-3 py-2 text-left text-xs font-semibold text-red-500 hover:bg-red-500/10 transition-colors"
>
<FiLogOut size={14} />
<span>Sign Out</span>
@@ -148,12 +225,12 @@ export default function Navbar() {
)}
</div>
- {/* Mobile Navbar Hamburger Menu Controls */}
+ {/* Mobile Navbar Controls */}
<div className="flex md:hidden items-center gap-2">
{status === "authenticated" && (
<div className="flex items-center h-8 border border-divider rounded bg-bg-page/30 px-2.5 text-xs font-bold text-primary-text gap-0.5">
<FiDollarSign className="text-emerald-500 text-[10px]" />
- {session.user.credits !== undefined ? session.user.credits : 0}
+ {isApiKeyActive ? "∞ Key" : session.user.credits !== undefined ? session.user.credits : 0}
</div>
)}
@@ -167,7 +244,7 @@ export default function Navbar() {
</div>
</div>
- {/* Absolutely Positioned Mobile Menu Dropdown (Backdrop blur + matches layout) */}
+ {/* Mobile Menu Dropdown */}
{isOpen && (
<div className="absolute top-full left-0 right-0 z-[200] glass-dropdown border-b border-divider shadow-2xl py-4 px-6 md:hidden animate-fade-in">
<nav className="flex flex-col gap-3">
@@ -185,6 +262,21 @@ export default function Navbar() {
</Link>
))}
+ {status === "authenticated" && (
+ <button
+ onClick={() => {
+ setIsOpen(false);
+ setIsApiKeyModalOpen(true);
+ }}
+ className="flex w-full items-center justify-between rounded border border-amber-500/30 bg-amber-500/10 px-3 py-2.5 text-xs font-bold text-amber-400"
+ >
+ <div className="flex items-center gap-2">
+ <FiKey />
+ <span>{isApiKeyActive ? "Manage Custom API Key" : "Add API Key"}</span>
+ </div>
+ </button>
+ )}
+
<div className="h-px bg-divider/50 my-2" />
{/* Vercel Deploy in Mobile menu */}
@@ -221,6 +313,77 @@ export default function Navbar() {
</nav>
</div>
)}
+
+ {/* API Key Modal */}
+ {isApiKeyModalOpen && (
+ <div className="fixed inset-0 z-[300] flex items-center justify-center bg-black/70 backdrop-blur-sm p-4">
+ <div className="bg-bg-card border border-divider w-full max-w-md rounded-xl p-6 space-y-5 shadow-2xl animate-scale-up">
+ <div className="flex items-center justify-between border-b border-divider/60 pb-3">
+ <div className="flex items-center gap-2 text-amber-400 font-black text-sm uppercase">
+ <FiKey className="text-base" />
+ <span>Custom API Key Settings</span>
+ </div>
+ <button
+ onClick={() => setIsApiKeyModalOpen(false)}
+ className="text-secondary-text hover:text-white transition-colors cursor-pointer"
+ >
+ <FiX size={18} />
+ </button>
+ </div>
+
+ <p className="text-xs text-secondary-text leading-relaxed">
+ Use your own <strong>MuAPI Key</strong> to generate UGC videos directly without consuming or purchasing website credits.
+ </p>
+
+ <form onSubmit={handleSaveApiKey} className="space-y-4">
+ <div className="space-y-1.5">
+ <label className="block text-[11px] uppercase font-bold text-secondary-text tracking-wider">
+ MuAPI Secret Key
+ </label>
+ <input
+ type="password"
+ value={apiKeyInput}
+ onChange={(e) => setApiKeyInput(e.target.value)}
+ placeholder="mu_..."
+ className="w-full bg-bg-page border border-divider rounded-lg px-3.5 py-2.5 text-xs text-white placeholder-secondary-text/50 focus:outline-none focus:border-amber-400 transition-colors"
+ />
+ </div>
+
+ <div className="flex items-center justify-between gap-3 pt-2">
+ {isApiKeyActive && (
+ <button
+ type="button"
+ onClick={handleRemoveApiKey}
+ disabled={savingKey}
+ className="flex items-center gap-1.5 px-3 py-2 rounded-lg bg-red-500/10 hover:bg-red-500/20 text-red-500 text-xs font-bold border border-red-500/20 transition-all cursor-pointer"
+ >
+ <FiTrash2 />
+ <span>Remove Key</span>
+ </button>
+ )}
+
+ <div className="flex items-center gap-2 ml-auto">
+ <button
+ type="button"
+ onClick={() => setIsApiKeyModalOpen(false)}
+ className="px-4 py-2 rounded-lg bg-bg-page border border-divider text-xs font-semibold text-secondary-text hover:text-white cursor-pointer"
+ >
+ Cancel
+ </button>
+ <button
+ type="submit"
+ disabled={savingKey || !apiKeyInput.trim()}
+ className="flex items-center gap-1.5 px-4 py-2 rounded-lg bg-amber-500 hover:bg-amber-400 text-neutral-950 text-xs font-bold transition-all disabled:opacity-50 cursor-pointer shadow-md shadow-amber-500/20"
+ >
+ <FiCheck />
+ <span>{savingKey ? "Saving..." : "Save Key"}</span>
+ </button>
+ </div>
+ </div>
+ </form>
+ </div>
+ </div>
+ )}
</header>
);
}
diff --git a/src/lib/auth.js b/src/lib/auth.js
index f4b2c3a..b4554c0 100644
--- a/src/lib/auth.js
+++ b/src/lib/auth.js
@@ -1,20 +1,105 @@
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import GoogleProvider from "next-auth/providers/google";
+import CredentialsProvider from "next-auth/providers/credentials";
import { prisma } from "./prisma";
export const authOptions = {
adapter: PrismaAdapter(prisma),
+ session: {
+ strategy: "jwt",
+ },
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
}),
+ CredentialsProvider({
+ id: "credentials",
+ name: "API Key",
+ credentials: {
+ apiKey: { label: "MuAPI Key", type: "password" },
+ },
+ async authorize(credentials) {
+ if (!credentials?.apiKey) {
+ throw new Error("API Key is required");
+ }
+ const apiKey = credentials.apiKey.trim();
+ if (apiKey.length < 5) {
+ throw new Error("Invalid API key format");
+ }
+
+ const dummyEmail = `apikey_${apiKey.slice(-8)}@muapi.local`;
+ let dbUser = await prisma.user.findFirst({
+ where: {
+ OR: [
+ { customApiKey: apiKey },
+ { email: dummyEmail }
+ ]
+ }
+ });
+
+ if (!dbUser) {
+ dbUser = await prisma.user.create({
+ data: {
+ name: "API Key User",
+ email: dummyEmail,
+ customApiKey: apiKey,
+ credits: 0,
+ }
+ });
+ } else if (!dbUser.customApiKey) {
+ dbUser = await prisma.user.update({
+ where: { id: dbUser.id },
+ data: { customApiKey: apiKey }
+ });
+ }
+
+ return {
+ id: dbUser.id,
+ name: dbUser.name,
+ email: dbUser.email,
+ image: dbUser.image || null,
+ credits: dbUser.credits,
+ customApiKey: dbUser.customApiKey || apiKey,
+ isApiKeyUser: true,
+ };
+ }
+ }),
],
callbacks: {
- async session({ session, user }) {
- if (session.user) {
- session.user.id = user.id;
- session.user.credits = user.credits;
+ async jwt({ token, user, trigger, session }) {
+ if (user) {
+ token.id = user.id;
+ token.credits = user.credits;
+ token.customApiKey = user.customApiKey;
+ token.isApiKeyUser = user.isApiKeyUser || false;
+ }
+ if (trigger === "update" && session) {
+ if (session.customApiKey !== undefined) token.customApiKey = session.customApiKey;
+ if (session.credits !== undefined) token.credits = session.credits;
+ }
+ const userId = token.id || token.sub;
+ if (userId) {
+ token.id = userId;
+ try {
+ const dbUser = await prisma.user.findUnique({
+ where: { id: userId },
+ select: { credits: true, customApiKey: true }
+ });
+ if (dbUser) {
+ token.credits = dbUser.credits;
+ token.customApiKey = dbUser.customApiKey;
+ }
+ } catch (err) {}
+ }
+ return token;
+ },
+ async session({ session, token }) {
+ if (session.user && token) {
+ session.user.id = token.id || token.sub;
+ session.user.credits = token.credits;
+ session.user.customApiKey = token.customApiKey;
+ session.user.isApiKeyUser = Boolean(token.customApiKey);
}
return session;
},
@@ -26,4 +111,3 @@ export const authOptions = {
};
export default authOptions;
-