Add magic link sign-in and harden auth query fallbacks
This commit is contained in:
@@ -10,7 +10,9 @@ export default function SignInPage() {
|
|||||||
const [email, setEmail] = useState("");
|
const [email, setEmail] = useState("");
|
||||||
const [password, setPassword] = useState("");
|
const [password, setPassword] = useState("");
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
|
const [magicLinkMessage, setMagicLinkMessage] = useState("");
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [magicLinkLoading, setMagicLinkLoading] = useState(false);
|
||||||
|
|
||||||
const handleSignIn = async (e: React.FormEvent) => {
|
const handleSignIn = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
@@ -35,6 +37,35 @@ export default function SignInPage() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const handleMagicLink = async () => {
|
||||||
|
setError("");
|
||||||
|
setMagicLinkMessage("");
|
||||||
|
|
||||||
|
if (!email) {
|
||||||
|
setError("Bitte gib deine E-Mail-Adresse ein");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setMagicLinkLoading(true);
|
||||||
|
try {
|
||||||
|
const result = await authClient.signIn.magicLink({
|
||||||
|
email,
|
||||||
|
callbackURL: "/dashboard",
|
||||||
|
errorCallbackURL: "/auth/sign-in",
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.error) {
|
||||||
|
setError(result.error.message ?? "Magic Link konnte nicht gesendet werden");
|
||||||
|
} else {
|
||||||
|
setMagicLinkMessage("Magic Link gesendet. Prüfe dein Postfach.");
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
setError("Ein unerwarteter Fehler ist aufgetreten");
|
||||||
|
} finally {
|
||||||
|
setMagicLinkLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-screen items-center justify-center bg-background">
|
<div className="flex min-h-screen items-center justify-center bg-background">
|
||||||
<div className="w-full max-w-sm space-y-6 rounded-xl border bg-card p-8 shadow-sm">
|
<div className="w-full max-w-sm space-y-6 rounded-xl border bg-card p-8 shadow-sm">
|
||||||
@@ -87,6 +118,18 @@ export default function SignInPage() {
|
|||||||
>
|
>
|
||||||
{loading ? "Wird angemeldet…" : "Anmelden"}
|
{loading ? "Wird angemeldet…" : "Anmelden"}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
disabled={magicLinkLoading}
|
||||||
|
onClick={handleMagicLink}
|
||||||
|
className="w-full rounded-lg border bg-background px-4 py-2.5 text-sm font-medium hover:bg-muted disabled:opacity-50 transition-colors"
|
||||||
|
>
|
||||||
|
{magicLinkLoading ? "Wird gesendet…" : "Magic Link senden"}
|
||||||
|
</button>
|
||||||
|
{magicLinkMessage && (
|
||||||
|
<p className="text-sm text-emerald-600">{magicLinkMessage}</p>
|
||||||
|
)}
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<p className="text-center text-sm text-muted-foreground">
|
<p className="text-center text-sm text-muted-foreground">
|
||||||
|
|||||||
@@ -119,7 +119,11 @@ Wirft bei unauthentifiziertem Zugriff. Wird von allen Queries und Mutations genu
|
|||||||
### Auth-Race-Härtung
|
### Auth-Race-Härtung
|
||||||
|
|
||||||
- `canvases.get` nutzt optionalen Auth-Check und gibt bei fehlender Session `null` zurück (statt Throw), damit SSR/Client-Hydration bei kurzem Token-Race nicht in `404` kippt.
|
- `canvases.get` nutzt optionalen Auth-Check und gibt bei fehlender Session `null` zurück (statt Throw), damit SSR/Client-Hydration bei kurzem Token-Race nicht in `404` kippt.
|
||||||
|
- `canvases.list` gibt bei fehlender Session eine leere Liste zurück (statt Throw), damit Dashboard-Subscriptions beim Logout keinen Error-Spam erzeugen.
|
||||||
- `credits.getBalance` gibt bei fehlender Session einen Default-Stand (`0`-Werte) zurück (statt Throw), damit UI-Widgets nicht mit `Unauthenticated` fehlschlagen.
|
- `credits.getBalance` gibt bei fehlender Session einen Default-Stand (`0`-Werte) zurück (statt Throw), damit UI-Widgets nicht mit `Unauthenticated` fehlschlagen.
|
||||||
|
- `credits.getSubscription` fällt bei fehlender Session auf Free/Active zurück (statt Throw), damit Tier-UI stabil bleibt.
|
||||||
|
- `credits.getRecentTransactions` gibt bei fehlender Session `[]` zurück (statt Throw), damit Aktivitätslisten beim Logout sauber leeren.
|
||||||
|
- `credits.getUsageStats` gibt bei fehlender Session `0`-Statistiken zurück (statt Throw), damit Verbrauchsanzeigen ohne Fehler ausrendern.
|
||||||
|
|
||||||
### Idempotente Canvas-Mutations
|
### Idempotente Canvas-Mutations
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { internal } from "./_generated/api";
|
|||||||
import { DataModel } from "./_generated/dataModel";
|
import { DataModel } from "./_generated/dataModel";
|
||||||
import { query } from "./_generated/server";
|
import { query } from "./_generated/server";
|
||||||
import { betterAuth } from "better-auth/minimal";
|
import { betterAuth } from "better-auth/minimal";
|
||||||
|
import { magicLink } from "better-auth/plugins";
|
||||||
import { Resend } from "resend";
|
import { Resend } from "resend";
|
||||||
import authConfig from "./auth.config";
|
import authConfig from "./auth.config";
|
||||||
|
|
||||||
@@ -26,6 +27,9 @@ export const authComponent = createClient<DataModel>(components.betterAuth);
|
|||||||
|
|
||||||
// Auth Factory — wird pro Request aufgerufen (Convex ist request-scoped)
|
// Auth Factory — wird pro Request aufgerufen (Convex ist request-scoped)
|
||||||
export const createAuth = (ctx: GenericCtx<DataModel>) => {
|
export const createAuth = (ctx: GenericCtx<DataModel>) => {
|
||||||
|
const authAppUrl = appUrl ?? siteUrl;
|
||||||
|
const signInRedirectUrl = `${authAppUrl}/dashboard`;
|
||||||
|
|
||||||
return betterAuth({
|
return betterAuth({
|
||||||
baseURL: siteUrl,
|
baseURL: siteUrl,
|
||||||
trustedOrigins: [siteUrl, lemonspaceAppOrigin, "http://localhost:3000"],
|
trustedOrigins: [siteUrl, lemonspaceAppOrigin, "http://localhost:3000"],
|
||||||
@@ -78,6 +82,46 @@ export const createAuth = (ctx: GenericCtx<DataModel>) => {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
plugins: [
|
plugins: [
|
||||||
|
magicLink({
|
||||||
|
disableSignUp: true,
|
||||||
|
expiresIn: 60 * 10, // 10 Minuten
|
||||||
|
sendMagicLink: async ({ email, url }) => {
|
||||||
|
const apiKey = process.env.RESEND_API_KEY;
|
||||||
|
if (!apiKey) {
|
||||||
|
console.error("RESEND_API_KEY is not set — skipping magic link email");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const magicLinkUrl = new URL(url);
|
||||||
|
magicLinkUrl.searchParams.set("callbackURL", signInRedirectUrl);
|
||||||
|
magicLinkUrl.searchParams.set("errorCallbackURL", `${authAppUrl}/auth/sign-in`);
|
||||||
|
|
||||||
|
const resend = new Resend(apiKey);
|
||||||
|
const { error } = await resend.emails.send({
|
||||||
|
from: "LemonSpace <noreply@lemonspace.io>",
|
||||||
|
to: email,
|
||||||
|
subject: "Dein LemonSpace Magic Link",
|
||||||
|
html: `
|
||||||
|
<div style="font-family: sans-serif; max-width: 480px; margin: 0 auto;">
|
||||||
|
<h2>Dein Login-Link für LemonSpace 🍋</h2>
|
||||||
|
<p>Klicke auf den Button, um dich anzumelden:</p>
|
||||||
|
<a href="${magicLinkUrl.toString()}"
|
||||||
|
style="display: inline-block; background: #facc15; color: #1a1a1a; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: 600; margin: 16px 0;">
|
||||||
|
Jetzt anmelden
|
||||||
|
</a>
|
||||||
|
<p style="color: #666; font-size: 13px;">
|
||||||
|
Der Link ist 10 Minuten gültig. Falls der Button nicht funktioniert, kopiere diesen Link:<br/>
|
||||||
|
<a href="${magicLinkUrl.toString()}">${magicLinkUrl.toString()}</a>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
`,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (error) {
|
||||||
|
console.error("Failed to send magic link email:", error);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}),
|
||||||
convex({ authConfig }),
|
convex({ authConfig }),
|
||||||
polar({
|
polar({
|
||||||
client: polarClient,
|
client: polarClient,
|
||||||
|
|||||||
@@ -12,7 +12,10 @@ import { optionalAuth, requireAuth } from "./helpers";
|
|||||||
export const list = query({
|
export const list = query({
|
||||||
args: {},
|
args: {},
|
||||||
handler: async (ctx) => {
|
handler: async (ctx) => {
|
||||||
const user = await requireAuth(ctx);
|
const user = await optionalAuth(ctx);
|
||||||
|
if (!user) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
return await ctx.db
|
return await ctx.db
|
||||||
.query("canvases")
|
.query("canvases")
|
||||||
.withIndex("by_owner_updated", (q) => q.eq("ownerId", user.userId))
|
.withIndex("by_owner_updated", (q) => q.eq("ownerId", user.userId))
|
||||||
|
|||||||
@@ -101,7 +101,13 @@ export const listTransactions = query({
|
|||||||
export const getSubscription = query({
|
export const getSubscription = query({
|
||||||
args: {},
|
args: {},
|
||||||
handler: async (ctx) => {
|
handler: async (ctx) => {
|
||||||
const user = await requireAuth(ctx);
|
const user = await optionalAuth(ctx);
|
||||||
|
if (!user) {
|
||||||
|
return {
|
||||||
|
tier: "free" as const,
|
||||||
|
status: "active" as const,
|
||||||
|
};
|
||||||
|
}
|
||||||
const row = await ctx.db
|
const row = await ctx.db
|
||||||
.query("subscriptions")
|
.query("subscriptions")
|
||||||
.withIndex("by_user", (q) => q.eq("userId", user.userId))
|
.withIndex("by_user", (q) => q.eq("userId", user.userId))
|
||||||
@@ -152,7 +158,10 @@ export const getRecentTransactions = query({
|
|||||||
limit: v.optional(v.number()),
|
limit: v.optional(v.number()),
|
||||||
},
|
},
|
||||||
handler: async (ctx, args) => {
|
handler: async (ctx, args) => {
|
||||||
const user = await requireAuth(ctx);
|
const user = await optionalAuth(ctx);
|
||||||
|
if (!user) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
const limit = args.limit ?? 10;
|
const limit = args.limit ?? 10;
|
||||||
|
|
||||||
return await ctx.db
|
return await ctx.db
|
||||||
@@ -170,7 +179,13 @@ export const getRecentTransactions = query({
|
|||||||
export const getUsageStats = query({
|
export const getUsageStats = query({
|
||||||
args: {},
|
args: {},
|
||||||
handler: async (ctx) => {
|
handler: async (ctx) => {
|
||||||
const user = await requireAuth(ctx);
|
const user = await optionalAuth(ctx);
|
||||||
|
if (!user) {
|
||||||
|
return {
|
||||||
|
monthlyUsage: 0,
|
||||||
|
totalGenerations: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const monthStart = new Date(now.getFullYear(), now.getMonth(), 1).getTime();
|
const monthStart = new Date(now.getFullYear(), now.getMonth(), 1).getTime();
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import { createAuthClient } from "better-auth/react";
|
import { createAuthClient } from "better-auth/react";
|
||||||
|
import { magicLinkClient } from "better-auth/client/plugins";
|
||||||
import { convexClient } from "@convex-dev/better-auth/client/plugins";
|
import { convexClient } from "@convex-dev/better-auth/client/plugins";
|
||||||
import { polarClient } from "@polar-sh/better-auth/client";
|
import { polarClient } from "@polar-sh/better-auth/client";
|
||||||
|
|
||||||
// Next.js: kein crossDomainClient nötig (same-origin via API Route Proxy)
|
// Next.js: kein crossDomainClient nötig (same-origin via API Route Proxy)
|
||||||
export const authClient = createAuthClient({
|
export const authClient = createAuthClient({
|
||||||
plugins: [convexClient(), polarClient()],
|
plugins: [magicLinkClient(), convexClient(), polarClient()],
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user