Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: send only verification code

Marc Seitz5df8016ac94e
diff --git a/app/(auth)/auth/email/[[...params]]/page-client.tsx b/app/(auth)/auth/email/[[...params]]/page-client.tsx
index 3d9dcf01..0875edcf 100644
--- a/app/(auth)/auth/email/[[...params]]/page-client.tsx
+++ b/app/(auth)/auth/email/[[...params]]/page-client.tsx
@@ -3,78 +3,43 @@
import Link from "next/link";
import { useRouter } from "next/navigation";
-import { useCallback, useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { LogoCloud } from "@/components/shared/logo-cloud";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
-interface EmailVerificationClientProps {
- email?: string;
- code?: string;
- uuid?: string;
- autoVerify?: boolean;
-}
-
-export default function EmailVerificationClient({
- email: initialEmail,
- code: initialCode,
- uuid,
- autoVerify = false,
-}: EmailVerificationClientProps) {
+export default function EmailVerificationClient() {
const router = useRouter();
- const [email, setEmail] = useState(initialEmail || "");
+ const codeInputRef = useRef<HTMLInputElement>(null);
+ const [email, setEmail] = useState("");
+ const [emailLocked, setEmailLocked] = useState(false);
const [code, setCode] = useState("");
- const [isLoading, setIsLoading] = useState(autoVerify);
+ const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [isExpired, setIsExpired] = useState(false);
- // Auto-verify when coming from email link
- const verifyWithLink = useCallback(async () => {
- if (!uuid || !initialCode || !initialEmail) return;
-
- setIsLoading(true);
- setError(null);
-
+ // Check sessionStorage for pending verification email on mount
+ useEffect(() => {
try {
- const response = await fetch(
- `/api/auth/verify-code?uuid=${encodeURIComponent(uuid)}`,
- );
- const data = await response.json();
-
- if (!response.ok) {
- if (response.status === 410 || data.error?.includes("expired")) {
- setIsExpired(true);
- setError("This code has expired or is invalid.");
- } else if (response.status === 429) {
- setError(
- data.error || "Too many attempts. Please wait before trying again.",
- );
- } else {
- setError(data.error || "Verification failed. Please try again.");
- }
- setIsLoading(false);
- return;
- }
-
- // Redirect to the callback URL
- if (data.callbackUrl) {
- router.push(data.callbackUrl);
+ const pendingEmail = sessionStorage.getItem("pendingVerificationEmail");
+ if (pendingEmail) {
+ setEmail(pendingEmail);
+ setEmailLocked(true);
+ // Clear the stored email after reading
+ sessionStorage.removeItem("pendingVerificationEmail");
+ // Focus the code input
+ setTimeout(() => {
+ codeInputRef.current?.focus();
+ }, 100);
}
- } catch (err) {
- setError("An error occurred. Please try again.");
- setIsLoading(false);
- }
- }, [uuid, initialCode, initialEmail, router]);
-
- useEffect(() => {
- if (autoVerify) {
- verifyWithLink();
+ } catch {
+ // sessionStorage not available, user will need to enter email manually
}
- }, [autoVerify, verifyWithLink]);
+ }, []);
- // Manual code verification
+ // Code verification
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsLoading(true);
@@ -169,33 +134,27 @@ export default function EmailVerificationClient({
/>
<Link href="/">
<span className="text-balance text-3xl font-semibold text-gray-900">
- {autoVerify && isLoading
- ? "Verifying..."
- : "Enter verification code"}
+ Check your email
</span>
</Link>
<h3 className="text-balance text-sm text-gray-800">
- {autoVerify && isLoading
- ? "Please wait while we verify your login."
- : "Enter the code sent to your email."}
+ {emailLocked ? (
+ <>
+ We sent a login code to{" "}
+ <span className="font-medium">{email}</span>
+ </>
+ ) : (
+ "Enter your email and the code we sent you"
+ )}
</h3>
</div>
- {/* Loading state for auto-verify */}
- {autoVerify && isLoading && (
- <div className="flex flex-col gap-4 px-4 pt-8 sm:px-12">
- <div className="flex items-center justify-center py-8">
- <div className="h-8 w-8 animate-spin rounded-full border-b-2 border-gray-800"></div>
- </div>
- </div>
- )}
-
- {/* Manual entry form */}
- {(!autoVerify || !isLoading) && (
- <form
- className="flex flex-col gap-4 px-4 pt-8 sm:px-12"
- onSubmit={handleSubmit}
- >
+ <form
+ className="flex flex-col gap-4 px-4 pt-8 sm:px-12"
+ onSubmit={handleSubmit}
+ >
+ {/* Only show email field if not locked from sessionStorage */}
+ {!emailLocked && (
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input
@@ -205,45 +164,46 @@ export default function EmailVerificationClient({
autoCapitalize="none"
autoComplete="email"
autoCorrect="off"
- disabled={isLoading || !!initialEmail}
+ disabled={isLoading}
value={email}
onChange={(e) => setEmail(e.target.value)}
className="flex h-10 w-full rounded-md border-0 bg-background bg-white px-3 py-2 text-sm text-gray-900 ring-1 ring-gray-200 transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
/>
</div>
- <div className="space-y-2">
- <Label htmlFor="code">Verification Code</Label>
- <Input
- id="code"
- placeholder="Enter 10-character code"
- type="text"
- autoCapitalize="characters"
- autoComplete="one-time-code"
- autoCorrect="off"
- disabled={isLoading}
- value={code}
- onChange={(e) => setCode(e.target.value.toUpperCase())}
- maxLength={10}
- className="flex h-10 w-full rounded-md border-0 bg-background bg-white px-3 py-2 font-mono text-lg tracking-widest text-gray-900 ring-1 ring-gray-200 transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground placeholder:font-sans placeholder:text-sm placeholder:tracking-normal focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
- />
- </div>
+ )}
+ <div className="space-y-2">
+ <Label htmlFor="code">Verification Code</Label>
+ <Input
+ ref={codeInputRef}
+ id="code"
+ placeholder="Enter 10-character code"
+ type="text"
+ autoCapitalize="characters"
+ autoComplete="one-time-code"
+ autoCorrect="off"
+ disabled={isLoading}
+ value={code}
+ onChange={(e) => setCode(e.target.value.toUpperCase())}
+ maxLength={10}
+ className="flex h-10 w-full rounded-md border-0 bg-background bg-white px-3 py-2 font-mono text-lg tracking-widest text-gray-900 ring-1 ring-gray-200 transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground placeholder:font-sans placeholder:text-sm placeholder:tracking-normal focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"
+ />
+ </div>
- {error && (
- <p className="text-sm text-red-600" role="alert">
- {error}
- </p>
- )}
+ {error && (
+ <p className="text-sm text-red-600" role="alert">
+ {error}
+ </p>
+ )}
- <Button
- type="submit"
- loading={isLoading}
- disabled={isLoading || !email || code.length < 10}
- className="focus:shadow-outline w-full transform rounded bg-gray-800 px-4 py-2 text-white transition-colors duration-300 ease-in-out hover:bg-gray-900 focus:outline-none"
- >
- Verify
- </Button>
- </form>
- )}
+ <Button
+ type="submit"
+ loading={isLoading}
+ disabled={isLoading || !email || code.length < 10}
+ className="focus:shadow-outline w-full transform rounded bg-gray-800 px-4 py-2 text-white transition-colors duration-300 ease-in-out hover:bg-gray-900 focus:outline-none"
+ >
+ Verify
+ </Button>
+ </form>
<p className="mt-6 px-4 text-center text-sm text-muted-foreground sm:px-12">
Didn&apos;t receive a code?{" "}
diff --git a/app/(auth)/auth/email/[[...params]]/page.tsx b/app/(auth)/auth/email/[[...params]]/page.tsx
index b0661791..5a8b8bb1 100644
--- a/app/(auth)/auth/email/[[...params]]/page.tsx
+++ b/app/(auth)/auth/email/[[...params]]/page.tsx
@@ -36,22 +36,6 @@ export const metadata: Metadata = {
},
};
-export default async function EmailVerificationPage({
- params,
-}: {
- params: { params?: string[] };
-}) {
- // Extract email, code, and uuid from params
- // URL format: /auth/email/{email}/{code}/{uuid}
- const [encodedEmail, code, uuid] = params.params || [];
- const email = encodedEmail ? decodeURIComponent(encodedEmail) : undefined;
-
- return (
- <EmailVerificationClient
- email={email}
- code={code}
- uuid={uuid}
- autoVerify={!!(email && code && uuid)}
- />
- );
+export default async function EmailVerificationPage() {
+ return <EmailVerificationClient />;
}
diff --git a/app/(auth)/login/page-client.tsx b/app/(auth)/login/page-client.tsx
index 28eca7bb..973aaa02 100644
--- a/app/(auth)/login/page-client.tsx
+++ b/app/(auth)/login/page-client.tsx
@@ -1,7 +1,7 @@
"use client";
import Link from "next/link";
-import { useParams } from "next/navigation";
+import { useParams, useRouter } from "next/navigation";
import { useState } from "react";
@@ -23,6 +23,7 @@ import { Label } from "@/components/ui/label";
export default function Login() {
const { next } = useParams as { next?: string };
+ const router = useRouter();
const [lastUsed, setLastUsed] = useLastUsed();
const authMethods = ["google", "email", "linkedin", "passkey"] as const;
@@ -84,15 +85,22 @@ export default function Login() {
...(next && next.length > 0 ? { callbackUrl: next } : {}),
}).then((res) => {
if (res?.ok && !res?.error) {
- setEmail("");
setLastUsed("credentials");
- setEmailButtonText("Email sent - check your inbox!");
- toast.success("Email sent - check your inbox!");
+ // Store email in sessionStorage for the verification page
+ try {
+ sessionStorage.setItem(
+ "pendingVerificationEmail",
+ emailValidation.data,
+ );
+ } catch {
+ // sessionStorage not available, verification page will show email input
+ }
+ router.push("/auth/email");
} else {
setEmailButtonText("Error sending email - try again?");
toast.error("Error sending email - try again?");
+ setClickedMethod(undefined);
}
- setClickedMethod(undefined);
});
}}
>
diff --git a/app/(auth)/verify/page.tsx b/app/(auth)/verify/page.tsx
index b2e0b6c3..ffb6b30c 100644
--- a/app/(auth)/verify/page.tsx
+++ b/app/(auth)/verify/page.tsx
@@ -1,286 +1,6 @@
-import { Metadata } from "next";
-import Link from "next/link";
import { redirect } from "next/navigation";
-import { getMagicLinkData } from "@/lib/emails/send-verification-request";
-import { generateChecksum } from "@/lib/utils/generate-checksum";
-
-import { LogoCloud } from "@/components/shared/logo-cloud";
-import { Button } from "@/components/ui/button";
-
-const data = {
- description: "Verify login to Papermark",
- title: "Verify | Papermark",
- url: "/verify",
-};
-
-export const metadata: Metadata = {
- metadataBase: new URL("https://www.papermark.com"),
- title: data.title,
- description: data.description,
- openGraph: {
- title: data.title,
- description: data.description,
- url: data.url,
- siteName: "Papermark",
- images: [
- {
- url: "/_static/meta-image.png",
- width: 800,
- height: 600,
- },
- ],
- locale: "en_US",
- type: "website",
- },
- twitter: {
- card: "summary_large_image",
- title: data.title,
- description: data.description,
- creator: "@papermarkio",
- images: ["/_static/meta-image.png"],
- },
-};
-
-// Validate legacy verification URL with checksum
-const isValidVerificationUrl = (url: string, checksum: string): boolean => {
- try {
- const urlObj = new URL(url);
- if (urlObj.origin !== process.env.NEXTAUTH_URL) return false;
- const expectedChecksum = generateChecksum(url);
- return checksum === expectedChecksum;
- } catch {
- return false;
- }
-};
-
-export default async function VerifyPage({
- searchParams,
-}: {
- searchParams: {
- token?: string;
- verification_url?: string;
- checksum?: string;
- };
-}) {
- const { token, verification_url, checksum } = searchParams;
-
- // If no params at all, redirect to the new auth email page for manual code entry
- if (!token && !verification_url && !checksum) {
- redirect("/auth/email");
- }
-
- let verifyUrl: string | null = null;
- let isExpired = false;
-
- // New flow: token-based verification (now UUID-based, stored in Redis)
- if (token) {
- const magicLinkData = await getMagicLinkData(token);
- if (magicLinkData) {
- // Redirect to the new verify-code API
- verifyUrl = `/api/auth/verify-code?uuid=${token}`;
- } else {
- // Token not found or expired (Redis TTL handles expiration automatically)
- isExpired = true;
- }
- }
- // Legacy flow: verification_url with checksum (backward compatibility)
- else if (verification_url && checksum) {
- if (isValidVerificationUrl(verification_url, checksum)) {
- verifyUrl = verification_url;
- }
- }
-
- // If expired, show expired page with option to request new code
- if (isExpired) {
- return (
- <div className="flex h-screen w-full flex-wrap">
- <div className="flex w-full justify-center bg-gray-50 md:w-1/2 lg:w-1/2">
- <div className="z-10 mx-5 mt-[calc(1vh)] h-fit w-full max-w-md overflow-hidden rounded-lg sm:mx-0 sm:mt-[calc(2vh)] md:mt-[calc(3vh)]">
- <div className="items-left flex flex-col space-y-3 px-4 py-6 pt-8 sm:px-12">
- <img
- src="/_static/papermark-logo.svg"
- alt="Papermark Logo"
- className="-mt-8 mb-36 h-7 w-auto self-start sm:mb-32 md:mb-48"
- />
- <span className="text-balance text-3xl font-semibold text-gray-900">
- Link Expired
- </span>
- <h3 className="text-balance text-sm text-gray-800">
- This login link has expired or has already been used.
- </h3>
- </div>
- <div className="flex flex-col gap-4 px-4 pt-8 sm:px-12">
- <div className="relative">
- <Link href="/login">
- <Button className="focus:shadow-outline w-full transform rounded bg-gray-800 px-4 py-2 text-white transition-colors duration-300 ease-in-out hover:bg-gray-900 focus:outline-none">
- Request a new link
- </Button>
- </Link>
- </div>
- </div>
- </div>
- </div>
- <div className="relative hidden w-full justify-center overflow-hidden bg-black md:flex md:w-1/2 lg:w-1/2">
- <div className="relative m-0 flex h-full min-h-[700px] w-full p-0">
- <div
- className="relative flex h-full w-full flex-col justify-between"
- id="features"
- >
- <div
- className="flex w-full flex-col items-center justify-center"
- style={{ height: "66.6666%" }}
- >
- <div className="mb-4 h-64 w-80">
- <img
- className="h-full w-full rounded-2xl object-cover shadow-2xl"
- src="/_static/testimonials/backtrace.jpeg"
- alt="Backtrace Capital"
- />
- </div>
- <div className="max-w-xl text-center">
- <blockquote className="text-balance font-normal leading-8 text-white sm:text-xl sm:leading-9">
- <p>
- &quot;We raised our €30M Fund with Papermark Data Rooms.
- Love the customization, security and ease of use.&quot;
- </p>
- </blockquote>
- <figcaption className="mt-4">
- <div className="text-balance font-normal text-white">
- Michael Münnix
- </div>
- <div className="text-balance font-light text-gray-400">
- Partner, Backtrace Capital
- </div>
- </figcaption>
- </div>
- </div>
- <div
- className="absolute bottom-0 left-0 flex w-full flex-col items-center justify-center bg-white"
- style={{ height: "33.3333%" }}
- >
- <div className="mb-4 max-w-xl text-balance text-center font-semibold text-gray-900">
- Trusted by teams at
- </div>
- <LogoCloud />
- </div>
- </div>
- </div>
- </div>
- </div>
- );
- }
-
- // If no valid verify URL found, redirect to auth email page for manual entry
- if (!verifyUrl) {
- redirect("/auth/email");
- }
-
- return (
- <div className="flex h-screen w-full flex-wrap">
- {/* Left part */}
- <div className="flex w-full justify-center bg-gray-50 md:w-1/2 lg:w-1/2">
- <div
- className="absolute inset-x-0 top-10 -z-10 flex transform-gpu justify-center overflow-hidden blur-3xl"
- aria-hidden="true"
- ></div>
- <div className="z-10 mx-5 mt-[calc(1vh)] h-fit w-full max-w-md overflow-hidden rounded-lg sm:mx-0 sm:mt-[calc(2vh)] md:mt-[calc(3vh)]">
- <div className="items-left flex flex-col space-y-3 px-4 py-6 pt-8 sm:px-12">
- <img
- src="/_static/papermark-logo.svg"
- alt="Papermark Logo"
- className="-mt-8 mb-36 h-7 w-auto self-start sm:mb-32 md:mb-48"
- />
- <Link href="/">
- <span className="text-balance text-3xl font-semibold text-gray-900">
- Verify your login
- </span>
- </Link>
- <h3 className="text-balance text-sm text-gray-800">
- Share documents. Not attachments.
- </h3>
- </div>
- <div className="flex flex-col gap-4 px-4 pt-8 sm:px-12">
- <div className="relative">
- <Link href={verifyUrl}>
- <Button className="focus:shadow-outline w-full transform rounded bg-gray-800 px-4 py-2 text-white transition-colors duration-300 ease-in-out hover:bg-gray-900 focus:outline-none">
- Verify email
- </Button>
- </Link>
- </div>
- </div>
- <p className="mt-10 w-full max-w-md px-4 text-xs text-muted-foreground sm:px-12">
- By clicking continue, you acknowledge that you have read and agree
- to Papermark&apos;s{" "}
- <a
- href={`${process.env.NEXT_PUBLIC_MARKETING_URL}/terms`}
- target="_blank"
- className="underline"
- >
- Terms of Service
- </a>{" "}
- and{" "}
- <a
- href={`${process.env.NEXT_PUBLIC_MARKETING_URL}/privacy`}
- target="_blank"
- className="underline"
- >
- Privacy Policy
- </a>
- .
- </p>
- </div>
- </div>
- <div className="relative hidden w-full justify-center overflow-hidden bg-black md:flex md:w-1/2 lg:w-1/2">
- <div className="relative m-0 flex h-full min-h-[700px] w-full p-0">
- <div
- className="relative flex h-full w-full flex-col justify-between"
- id="features"
- >
- {/* Testimonial top 2/3 */}
- <div
- className="flex w-full flex-col items-center justify-center"
- style={{ height: "66.6666%" }}
- >
- {/* Image container */}
- <div className="mb-4 h-64 w-80">
- <img
- className="h-full w-full rounded-2xl object-cover shadow-2xl"
- src="/_static/testimonials/backtrace.jpeg"
- alt="Backtrace Capital"
- />
- </div>
- {/* Text content */}
- <div className="max-w-xl text-center">
- <blockquote className="text-balance font-normal leading-8 text-white sm:text-xl sm:leading-9">
- <p>
- &quot;We raised our €30M Fund with Papermark Data Rooms.
- Love the customization, security and ease of use.&quot;
- </p>
- </blockquote>
- <figcaption className="mt-4">
- <div className="text-balance font-normal text-white">
- Michael Münnix
- </div>
- <div className="text-balance font-light text-gray-400">
- Partner, Backtrace Capital
- </div>
- </figcaption>
- </div>
- </div>
- {/* White block with logos bottom 1/3, full width/height */}
- <div
- className="absolute bottom-0 left-0 flex w-full flex-col items-center justify-center bg-white"
- style={{ height: "33.3333%" }}
- >
- <div className="mb-4 max-w-xl text-balance text-center font-semibold text-gray-900">
- Trusted by teams at
- </div>
- <LogoCloud />
- </div>
- </div>
- </div>
- </div>
- </div>
- );
+// Legacy verify page - redirect to new auth email flow
+export default async function VerifyPage() {
+ redirect("/auth/email");
}
diff --git a/app/api/auth/verify-code/route.ts b/app/api/auth/verify-code/route.ts
index e7ad365c..30c1090b 100644
--- a/app/api/auth/verify-code/route.ts
+++ b/app/api/auth/verify-code/route.ts
@@ -1,9 +1,8 @@
import { NextRequest, NextResponse } from "next/server";
import {
- deleteMagicLinkData,
- getMagicLinkData,
- getMagicLinkDataByCode,
+ deleteLoginCodeData,
+ getLoginCodeData,
} from "@/lib/emails/send-verification-request";
import { ratelimit } from "@/lib/redis";
@@ -17,55 +16,7 @@ function getClientIp(request: NextRequest): string {
return forwarded?.split(",")[0]?.trim() || realIp || "unknown";
}
-// GET: Verify via UUID (from email link)
-export async function GET(request: NextRequest) {
- const searchParams = request.nextUrl.searchParams;
- const uuid = searchParams.get("uuid");
-
- if (!uuid) {
- return NextResponse.json({ error: "Missing UUID parameter" }, { status: 400 });
- }
-
- const ip = getClientIp(request);
-
- // Check IP rate limit
- const ipLimit = await ipRateLimit.limit(`verify_code:ip:${ip}`);
- if (!ipLimit.success) {
- return NextResponse.json(
- {
- error: "Too many attempts. Please wait before trying again.",
- retryAfter: Math.ceil((ipLimit.reset - Date.now()) / 1000),
- },
- { status: 429 },
- );
- }
-
- try {
- const magicLinkData = await getMagicLinkData(uuid);
-
- if (!magicLinkData) {
- return NextResponse.json(
- { error: "This code has expired or is invalid." },
- { status: 410 },
- );
- }
-
- const { callbackUrl, email, code } = magicLinkData;
-
- // Delete both Redis keys to prevent reuse
- await deleteMagicLinkData(uuid, email, code);
-
- return NextResponse.json({ callbackUrl });
- } catch (error) {
- console.error("Error verifying code:", error);
- return NextResponse.json(
- { error: "Verification failed. Please try again." },
- { status: 500 },
- );
- }
-}
-
-// POST: Verify via email + code (manual entry)
+// POST: Verify via email + code
export async function POST(request: NextRequest) {
try {
const body = await request.json();
@@ -111,12 +62,12 @@ export async function POST(request: NextRequest) {
);
}
- const magicLinkData = await getMagicLinkDataByCode(
+ const loginCodeData = await getLoginCodeData(
normalizedEmail,
normalizedCode,
);
- if (!magicLinkData) {
+ if (!loginCodeData) {
return NextResponse.json(
{
error: "Invalid code. Please check your email and try again.",
@@ -126,10 +77,10 @@ export async function POST(request: NextRequest) {
);
}
- const { callbackUrl, uuid } = magicLinkData;
+ const { callbackUrl } = loginCodeData;
- // Delete both Redis keys to prevent reuse
- await deleteMagicLinkData(uuid, normalizedEmail, normalizedCode);
+ // Delete the Redis key to prevent reuse
+ await deleteLoginCodeData(normalizedEmail, normalizedCode);
return NextResponse.json({ callbackUrl });
} catch (error) {
diff --git a/app/api/verify/login-link/route.ts b/app/api/verify/login-link/route.ts
index e94f66d8..3a1ca2ee 100644
--- a/app/api/verify/login-link/route.ts
+++ b/app/api/verify/login-link/route.ts
@@ -1,43 +1,6 @@
import { NextRequest, NextResponse } from "next/server";
-import {
- deleteMagicLinkData,
- getMagicLinkData,
-} from "@/lib/emails/send-verification-request";
-
+// Legacy magic link route - redirect to new code-based flow
export async function GET(request: NextRequest) {
- const searchParams = request.nextUrl.searchParams;
- const token = searchParams.get("token");
-
- if (!token) {
- return NextResponse.redirect(
- new URL("/login?error=InvalidToken", request.url),
- );
- }
-
- try {
- // Get the magic link data from Redis (token is now a UUID)
- const magicLinkData = await getMagicLinkData(token);
-
- if (!magicLinkData) {
- // Token not found or expired - redirect back to verify page to show error
- return NextResponse.redirect(
- new URL(`/verify?token=${token}`, request.url),
- );
- }
-
- const { callbackUrl, email, code } = magicLinkData;
-
- // Delete the token from Redis to prevent reuse
- // Pass email and code for the new dual-key system
- await deleteMagicLinkData(token, email, code);
-
- // Redirect to the callback URL (NextAuth verification URL)
- return NextResponse.redirect(callbackUrl);
- } catch (error) {
- console.error("Error verifying magic link:", error);
- return NextResponse.redirect(
- new URL("/login?error=VerificationError", request.url),
- );
- }
+ return NextResponse.redirect(new URL("/auth/email", request.url));
}
diff --git a/components/emails/verification-link.tsx b/components/emails/verification-link.tsx
index a9de9f28..3b74086d 100644
--- a/components/emails/verification-link.tsx
+++ b/components/emails/verification-link.tsx
@@ -7,28 +7,23 @@ import {
Heading,
Hr,
Html,
- Link,
Preview,
Section,
Tailwind,
Text,
} from "@react-email/components";
-import { Footer } from "./shared/footer";
-
-const VerificationLinkEmail = ({
- url = "https://app.papermark.com/auth/email/[email protected]/45PFSNUDYW/abc-123",
+const VerificationCodeEmail = ({
email = "[email protected]",
code = "45PFSNUDYW",
}: {
- url: string;
email?: string;
code?: string;
}) => {
return (
<Html>
<Head />
- <Preview>To login to Papermark, follow this link {url}</Preview>
+ <Preview>Your login code for Papermark: {code}</Preview>
<Tailwind>
<Body className="mx-auto my-auto bg-white font-sans">
<Container className="mx-auto my-10 max-w-[600px] rounded border border-solid border-neutral-200 px-10 py-5">
@@ -38,34 +33,27 @@ const VerificationLinkEmail = ({
</Text>
</Section>
<Heading className="mx-0 my-7 p-0 text-xl font-semibold text-black">
- Your login code for Papermark
+ Your login code
</Heading>
- <Section className="my-8">
- <Link
- className="rounded-lg bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline"
- href={url}
- >
- Login to Papermark
- </Link>
- </Section>
<Text className="text-sm leading-6 text-neutral-600">
- This link and code will only be valid for the next 15 minutes. If
- the link does not work, you can use the login verification code
- directly:
+ Enter this code to sign in to your Papermark account:
</Text>
- <Section className="my-4">
+ <Section className="my-6">
<Text
- className="m-0 w-fit rounded-lg bg-neutral-100 px-2 py-1 text-base font-bold tracking-wider text-black"
- style={{ fontFamily: "monospace" }}
+ className="m-0 rounded-lg bg-neutral-100 px-4 py-3 text-center text-2xl font-bold tracking-[0.3em] text-black"
+ style={{ fontFamily: "monospace", letterSpacing: "0.3em" }}
>
{code}
</Text>
</Section>
- <Text className="text-sm leading-5 text-neutral-500">
- If you didn&apos;t try to log in, you can safely ignore this
+ <Text className="text-sm leading-6 text-neutral-600">
+ This code will expire in 15 minutes.
+ </Text>
+ <Text className="mt-4 text-sm leading-5 text-neutral-500">
+ If you didn&apos;t request this code, you can safely ignore this
email.
</Text>
- <Hr />
+ <Hr className="my-6" />
<Section className="text-gray-400">
<Text className="text-xs text-neutral-500">
Papermark, Inc.
@@ -82,4 +70,4 @@ const VerificationLinkEmail = ({
);
};
-export default VerificationLinkEmail;
+export default VerificationCodeEmail;
diff --git a/lib/emails/send-verification-request.ts b/lib/emails/send-verification-request.ts
index b2216679..a0297a96 100644
--- a/lib/emails/send-verification-request.ts
+++ b/lib/emails/send-verification-request.ts
@@ -1,9 +1,10 @@
+import { waitUntil } from "@vercel/functions";
import { customAlphabet } from "nanoid";
import { redis } from "@/lib/redis";
import { sendEmail } from "@/lib/resend";
-import LoginLink from "@/components/emails/verification-link";
+import VerificationCodeEmail from "@/components/emails/verification-link";
// Generate a 10-character uppercase alphanumeric verification code (like Linear's style)
const generateVerificationCode = customAlphabet(
@@ -17,10 +18,9 @@ const LOGIN_CODE_EMAIL_PREFIX = "login_code:email:";
// Token expiration time in seconds (15 minutes)
const TOKEN_EXPIRATION_SECONDS = 15 * 60;
-export interface MagicLinkData {
+export interface LoginCodeData {
email: string;
code: string;
- uuid: string;
callbackUrl: string;
createdAt: number;
}
@@ -31,124 +31,84 @@ export const sendVerificationRequestEmail = async (params: {
}) => {
const { url, email } = params;
- // Generate verification code and UUID
+ // Generate verification code
const code = generateVerificationCode();
- const uuid = crypto.randomUUID();
// Store the login data in Redis with 15-minute TTL
- const magicLinkData: MagicLinkData = {
+ const loginCodeData: LoginCodeData = {
email,
code,
- uuid,
callbackUrl: url,
createdAt: Date.now(),
};
- // Store with UUID as primary key
- await redis.set(
- `${LOGIN_CODE_PREFIX}${uuid}`,
- JSON.stringify(magicLinkData),
- { ex: TOKEN_EXPIRATION_SECONDS },
- );
-
- // Store secondary key for code lookup: email:code -> uuid
+ // Store with email:code as key for lookup (must complete before redirecting)
await redis.set(
`${LOGIN_CODE_EMAIL_PREFIX}${email.toLowerCase()}:${code}`,
- uuid,
+ JSON.stringify(loginCodeData),
{ ex: TOKEN_EXPIRATION_SECONDS },
);
- // Create verification URL with email, code, and uuid
- const encodedEmail = encodeURIComponent(email);
- const verificationUrl = `${process.env.NEXTAUTH_URL}/auth/email/${encodedEmail}/${code}/${uuid}`;
-
- const emailTemplate = LoginLink({
- url: verificationUrl,
+ const emailTemplate = VerificationCodeEmail({
email,
code,
});
- try {
- await sendEmail({
+ // Use waitUntil to send email in background after response is sent
+ // This keeps the serverless function alive until the email is sent
+ waitUntil(
+ sendEmail({
to: email as string,
system: true,
subject: "Login for Papermark",
react: emailTemplate,
test: process.env.NODE_ENV === "development",
- });
- } catch (e) {
- console.error(e);
- }
+ }).catch((e) => {
+ console.error("Failed to send verification email:", e);
+ }),
+ );
};
/**
- * Retrieve magic link data from Redis by UUID
- * Returns null if UUID doesn't exist or has expired (Redis handles TTL automatically)
+ * Retrieve login code data from Redis by email and code
+ * Returns null if not found or expired
*/
-export const getMagicLinkData = async (
- uuid: string,
-): Promise<MagicLinkData | null> => {
+export const getLoginCodeData = async (
+ email: string,
+ code: string,
+): Promise<LoginCodeData | null> => {
try {
- const data = await redis.get(`${LOGIN_CODE_PREFIX}${uuid}`);
+ const data = await redis.get(
+ `${LOGIN_CODE_EMAIL_PREFIX}${email.toLowerCase()}:${code.toUpperCase()}`,
+ );
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 JSON.parse(data) as LoginCodeData;
}
- return data as MagicLinkData;
+ return data as LoginCodeData;
} catch (error) {
- console.error("Error fetching magic link data:", error);
+ console.error("Error fetching login code data:", error);
return null;
}
};
/**
- * Retrieve magic link data from Redis by email and code
- * Returns null if not found or expired
+ * Delete login code data from Redis after successful use
+ * This prevents the code from being reused
*/
-export const getMagicLinkDataByCode = async (
+export const deleteLoginCodeData = async (
email: string,
code: string,
-): Promise<MagicLinkData | null> => {
+): Promise<boolean> => {
try {
- // Look up UUID from email:code key
- const uuid = await redis.get(
+ const result = await redis.del(
`${LOGIN_CODE_EMAIL_PREFIX}${email.toLowerCase()}:${code.toUpperCase()}`,
);
- if (!uuid || typeof uuid !== "string") return null;
-
- // Get the full data using the UUID
- return getMagicLinkData(uuid);
- } catch (error) {
- console.error("Error fetching magic link data by code:", error);
- return null;
- }
-};
-
-/**
- * Delete magic link data from Redis after successful use
- * This prevents the link from being reused
- */
-export const deleteMagicLinkData = async (
- uuid: string,
- email?: string,
- code?: string,
-): Promise<boolean> => {
- try {
- // Delete primary key
- const result = await redis.del(`${LOGIN_CODE_PREFIX}${uuid}`);
-
- // Delete secondary key if email and code are provided
- if (email && code) {
- await redis.del(
- `${LOGIN_CODE_EMAIL_PREFIX}${email.toLowerCase()}:${code.toUpperCase()}`,
- );
- }
-
return result === 1;
} catch (error) {
- console.error("Error deleting magic link data:", error);
+ console.error("Error deleting login code data:", error);
return false;
}
};