Add magic link sign-in and harden auth query fallbacks

This commit is contained in:
Matthias
2026-04-01 11:59:47 +02:00
parent d117d6f80c
commit 4065d0ce1c
6 changed files with 115 additions and 5 deletions

View File

@@ -119,7 +119,11 @@ Wirft bei unauthentifiziertem Zugriff. Wird von allen Queries und Mutations genu
### 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.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.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

View File

@@ -8,6 +8,7 @@ import { internal } from "./_generated/api";
import { DataModel } from "./_generated/dataModel";
import { query } from "./_generated/server";
import { betterAuth } from "better-auth/minimal";
import { magicLink } from "better-auth/plugins";
import { Resend } from "resend";
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)
export const createAuth = (ctx: GenericCtx<DataModel>) => {
const authAppUrl = appUrl ?? siteUrl;
const signInRedirectUrl = `${authAppUrl}/dashboard`;
return betterAuth({
baseURL: siteUrl,
trustedOrigins: [siteUrl, lemonspaceAppOrigin, "http://localhost:3000"],
@@ -78,6 +82,46 @@ export const createAuth = (ctx: GenericCtx<DataModel>) => {
},
},
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 }),
polar({
client: polarClient,

View File

@@ -12,7 +12,10 @@ import { optionalAuth, requireAuth } from "./helpers";
export const list = query({
args: {},
handler: async (ctx) => {
const user = await requireAuth(ctx);
const user = await optionalAuth(ctx);
if (!user) {
return [];
}
return await ctx.db
.query("canvases")
.withIndex("by_owner_updated", (q) => q.eq("ownerId", user.userId))

View File

@@ -101,7 +101,13 @@ export const listTransactions = query({
export const getSubscription = query({
args: {},
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
.query("subscriptions")
.withIndex("by_user", (q) => q.eq("userId", user.userId))
@@ -152,7 +158,10 @@ export const getRecentTransactions = query({
limit: v.optional(v.number()),
},
handler: async (ctx, args) => {
const user = await requireAuth(ctx);
const user = await optionalAuth(ctx);
if (!user) {
return [];
}
const limit = args.limit ?? 10;
return await ctx.db
@@ -170,7 +179,13 @@ export const getRecentTransactions = query({
export const getUsageStats = query({
args: {},
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 monthStart = new Date(now.getFullYear(), now.getMonth(), 1).getTime();