Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
refactor: Use Redis instead of database for magic link tokens
Cursor Agentad02242fb4c4
diff --git a/app/(auth)/verify/page.tsx b/app/(auth)/verify/page.tsxindex 42204d94..8c2378d0 100644--- a/app/(auth)/verify/page.tsx+++ b/app/(auth)/verify/page.tsx@@ -3,7 +3,7 @@ import Link from "next/link";import NotFound from "@/pages/404";-import prisma from "@/lib/prisma";+import { getMagicLinkData } from "@/lib/emails/send-verification-request";import { generateChecksum } from "@/lib/utils/generate-checksum";import { LogoCloud } from "@/components/shared/logo-cloud";@@ -55,33 +55,6 @@ const isValidVerificationUrl = (url: string, checksum: string): boolean => {}};-// Look up magic link token from database-async function getMagicLinkToken(token: string) {- try {- const magicLinkToken = await prisma.magicLinkToken.findUnique({- where: { token },- });-- if (!magicLinkToken) {- return null;- }-- // Check if token has expired- if (new Date() > magicLinkToken.expires) {- // Clean up expired token- await prisma.magicLinkToken.delete({- where: { token },- });- return null;- }-- return magicLinkToken;- } catch (error) {- console.error("Error fetching magic link token:", error);- return null;- }-}-export default async function VerifyPage({searchParams,}: {@@ -96,13 +69,13 @@ export default async function VerifyPage({let callbackUrl: string | null = null;let isExpired = false;- // New flow: token-based verification+ // New flow: token-based verification (stored in Redis)if (token) {- const magicLinkToken = await getMagicLinkToken(token);- if (magicLinkToken) {- callbackUrl = magicLinkToken.callbackUrl;+ const magicLinkData = await getMagicLinkData(token);+ if (magicLinkData) {+ callbackUrl = magicLinkData.callbackUrl;} else {- // Token not found or expired+ // Token not found or expired (Redis TTL handles expiration automatically)isExpired = true;}}diff --git a/app/api/cron/cleanup-magic-link-tokens/route.ts b/app/api/cron/cleanup-magic-link-tokens/route.tsdeleted file mode 100644index 902f938c..00000000--- a/app/api/cron/cleanup-magic-link-tokens/route.ts+++ /dev/null@@ -1,53 +0,0 @@-import { NextResponse } from "next/server";--import { receiver } from "@/lib/cron";-import prisma from "@/lib/prisma";-import { log } from "@/lib/utils";--/**- * Cron job to clean up expired magic link tokens.- * Runs daily to remove tokens that have passed their expiration date.- * This complements the lazy cleanup that happens when tokens are accessed.- */--export const maxDuration = 60; // 1 minute should be plenty--export async function POST(req: Request) {- const body = await req.json();-- if (process.env.VERCEL === "1") {- const isValid = await receiver.verify({- signature: req.headers.get("Upstash-Signature") || "",- body: JSON.stringify(body),- });- if (!isValid) {- return new Response("Unauthorized", { status: 401 });- }- }-- try {- // Delete all expired magic link tokens- const result = await prisma.magicLinkToken.deleteMany({- where: {- expires: {- lt: new Date(),- },- },- });-- console.log(- `[Cleanup] Deleted ${result.count} expired magic link tokens`,- );-- return NextResponse.json({- success: true,- deletedCount: result.count,- });- } catch (error) {- await log({- message: `Magic link token cleanup cron failed. \n\nError: ${(error as Error).message}`,- type: "cron",- });- return NextResponse.json({ error: (error as Error).message });- }-}diff --git a/lib/emails/send-verification-request.ts b/lib/emails/send-verification-request.tsindex 2804b772..2d1bcbdd 100644--- a/lib/emails/send-verification-request.ts+++ b/lib/emails/send-verification-request.ts@@ -1,6 +1,6 @@import { customAlphabet } from "nanoid";-import prisma from "@/lib/prisma";+import { redis } from "@/lib/redis";import { sendEmail } from "@/lib/resend";import LoginLink from "@/components/emails/verification-link";@@ -11,6 +11,17 @@ const generateMagicLinkToken = customAlphabet(20,);+// Redis key prefix for magic link tokens+const MAGIC_LINK_PREFIX = "magic_link:";+// Token expiration time in seconds (24 hours)+const TOKEN_EXPIRATION_SECONDS = 24 * 60 * 60;++export interface MagicLinkData {+ email: string;+ callbackUrl: string;+ createdAt: number;+}+export const sendVerificationRequestEmail = async (params: {email: string;url: string;@@ -20,21 +31,25 @@ export const sendVerificationRequestEmail = async (params: {// Generate a short, unique tokenconst token = generateMagicLinkToken();- // Store the callback URL server-side with 24-hour expiration- const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24 hours+ // Store the callback URL in Redis with 24-hour TTL+ const magicLinkData: MagicLinkData = {+ email,+ callbackUrl: url,+ createdAt: Date.now(),+ };- await prisma.magicLinkToken.create({- data: {- token,- email,- callbackUrl: url,- expires: expiresAt,- },- });+ await redis.set(+ `${MAGIC_LINK_PREFIX}${token}`,+ JSON.stringify(magicLinkData),+ { ex: TOKEN_EXPIRATION_SECONDS },+ );// Create simplified verification URL (under 100 characters)const verificationUrl = `${process.env.NEXTAUTH_URL}/verify?token=${token}`;+ // Calculate expiration time for the email+ const expiresAt = new Date(Date.now() + TOKEN_EXPIRATION_SECONDS * 1000);+const emailTemplate = LoginLink({url: verificationUrl,email,@@ -53,3 +68,25 @@ export const sendVerificationRequestEmail = async (params: {console.error(e);}};++/**+ * Retrieve magic link data from Redis+ * Returns null if token doesn't exist or has expired (Redis handles TTL automatically)+ */+export const getMagicLinkData = async (+ token: string,+): Promise<MagicLinkData | null> => {+ try {+ const data = await redis.get(`${MAGIC_LINK_PREFIX}${token}`);+ if (!data) return null;++ // Handle both string and already-parsed object (Redis client behavior)+ if (typeof data === "string") {+ return JSON.parse(data) as MagicLinkData;+ }+ return data as MagicLinkData;+ } catch (error) {+ console.error("Error fetching magic link data:", error);+ return null;+ }+};diff --git a/prisma/migrations/20260121000000_add_magic_link_token/migration.sql b/prisma/migrations/20260121000000_add_magic_link_token/migration.sqldeleted file mode 100644index 8e7ed409..00000000--- a/prisma/migrations/20260121000000_add_magic_link_token/migration.sql+++ /dev/null@@ -1,23 +0,0 @@--- CreateTable-CREATE TABLE "MagicLinkToken" (- "id" TEXT NOT NULL,- "token" TEXT NOT NULL,- "email" TEXT NOT NULL,- "callbackUrl" TEXT NOT NULL,- "expires" TIMESTAMP(3) NOT NULL,- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,-- CONSTRAINT "MagicLinkToken_pkey" PRIMARY KEY ("id")-);---- CreateIndex-CREATE UNIQUE INDEX "MagicLinkToken_token_key" ON "MagicLinkToken"("token");---- CreateIndex-CREATE INDEX "MagicLinkToken_token_idx" ON "MagicLinkToken"("token");---- CreateIndex-CREATE INDEX "MagicLinkToken_expires_idx" ON "MagicLinkToken"("expires");---- CreateIndex-CREATE INDEX "MagicLinkToken_email_idx" ON "MagicLinkToken"("email");diff --git a/prisma/schema/schema.prisma b/prisma/schema/schema.prismaindex 28783061..785c95c1 100644--- a/prisma/schema/schema.prisma+++ b/prisma/schema/schema.prisma@@ -92,19 +92,6 @@ model VerificationToken {@@unique([identifier, token])}-model MagicLinkToken {- id String @id @default(cuid())- token String @unique // Short unique token for the simplified URL- email String // The user's email address- callbackUrl String @db.Text // The original NextAuth callback URL- expires DateTime- createdAt DateTime @default(now())-- @@index([token])- @@index([expires])- @@index([email])-}-model Domain {id String @id @default(cuid())slug String @unique