feat: password reset flow and email verification
- Add forgot-password and reset-password pages and API routes - Add email verification with token generation on registration - Add resend-verification endpoint with 60s rate limit - Add shared email utility (nodemailer, Migadu SMTP) - Add VerificationBanner in dashboard layout - Add PasswordResetToken and EmailVerificationToken models - Add emailVerified field to User model - Extend NextAuth session with isEmailVerified - Add forgot-password link to login page - Wire EMAIL_PASSWORD env var in docker-compose
This commit is contained in:
158
apps/web/src/app/(auth)/forgot-password/page.tsx
Normal file
158
apps/web/src/app/(auth)/forgot-password/page.tsx
Normal file
@@ -0,0 +1,158 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Activity, Loader2 } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export default function ForgotPasswordPage() {
|
||||
const [email, setEmail] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [submitted, setSubmitted] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
|
||||
if (!emailValid) {
|
||||
setError("Please enter a valid email address");
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/auth/forgot-password", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data: { error?: string } = await res.json();
|
||||
setError(data.error ?? "Something went wrong");
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setSubmitted(true);
|
||||
} catch {
|
||||
setError("Something went wrong. Please try again.");
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (submitted) {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<div className="w-12 h-12 rounded-xl bg-gradient-to-br from-emerald-400 to-emerald-600 flex items-center justify-center shadow-lg shadow-emerald-500/20">
|
||||
<Activity className="w-6 h-6 text-white" />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h1 className="text-2xl font-bold text-neutral-100">
|
||||
Check your email
|
||||
</h1>
|
||||
<p className="mt-1 text-sm text-neutral-400">
|
||||
If an account exists for that email, we sent a password reset
|
||||
link. It expires in 1 hour.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-center text-sm text-neutral-400">
|
||||
<Link
|
||||
href="/login"
|
||||
className="text-emerald-400 hover:text-emerald-300 font-medium transition-colors"
|
||||
>
|
||||
Back to sign in
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<div className="w-12 h-12 rounded-xl bg-gradient-to-br from-emerald-400 to-emerald-600 flex items-center justify-center shadow-lg shadow-emerald-500/20">
|
||||
<Activity className="w-6 h-6 text-white" />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h1 className="text-2xl font-bold text-neutral-100">
|
||||
Reset your password
|
||||
</h1>
|
||||
<p className="mt-1 text-sm text-neutral-400">
|
||||
Enter your email and we'll send you a reset link
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
<div className="rounded-xl bg-neutral-900 border border-neutral-800 p-6 space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="email"
|
||||
className="block text-sm font-medium text-neutral-300"
|
||||
>
|
||||
Email
|
||||
</label>
|
||||
<input
|
||||
id="email"
|
||||
type="email"
|
||||
autoComplete="email"
|
||||
required
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="you@example.com"
|
||||
className={cn(
|
||||
"w-full px-3 py-2.5 bg-neutral-950 border rounded-lg text-sm text-neutral-100 placeholder-neutral-500 outline-none transition-colors",
|
||||
email && !emailValid
|
||||
? "border-red-500/50 focus:border-red-500"
|
||||
: "border-neutral-800 focus:border-emerald-500"
|
||||
)}
|
||||
/>
|
||||
{email && !emailValid && (
|
||||
<p className="text-xs text-red-400">
|
||||
Please enter a valid email address
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="rounded-lg bg-red-500/10 border border-red-500/20 px-4 py-3">
|
||||
<p className="text-sm text-red-400">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className={cn(
|
||||
"w-full flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-semibold transition-colors",
|
||||
loading
|
||||
? "bg-emerald-500/50 text-neutral-950/50 cursor-not-allowed"
|
||||
: "bg-emerald-500 hover:bg-emerald-400 text-neutral-950"
|
||||
)}
|
||||
>
|
||||
{loading && <Loader2 className="w-4 h-4 animate-spin" />}
|
||||
{loading ? "Sending..." : "Send reset link"}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p className="text-center text-sm text-neutral-400">
|
||||
Remember your password?{" "}
|
||||
<Link
|
||||
href="/login"
|
||||
className="text-emerald-400 hover:text-emerald-300 font-medium transition-colors"
|
||||
>
|
||||
Sign in
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,14 +1,24 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Suspense, useState } from "react";
|
||||
import { signIn } from "next-auth/react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { Activity, Loader2 } from "lucide-react";
|
||||
import { Activity, CheckCircle, Loader2 } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export default function LoginPage() {
|
||||
return (
|
||||
<Suspense>
|
||||
<LoginForm />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
function LoginForm() {
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const verified = searchParams.get("verified") === "true";
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
@@ -62,6 +72,15 @@ export default function LoginPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{verified && (
|
||||
<div className="rounded-lg bg-emerald-500/10 border border-emerald-500/20 px-4 py-3 flex items-center gap-2">
|
||||
<CheckCircle className="w-4 h-4 text-emerald-400 shrink-0" />
|
||||
<p className="text-sm text-emerald-400">
|
||||
Email verified! You can now sign in.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
<div className="rounded-xl bg-neutral-900 border border-neutral-800 p-6 space-y-4">
|
||||
<div className="space-y-2">
|
||||
@@ -123,6 +142,15 @@ export default function LoginPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Link
|
||||
href="/forgot-password"
|
||||
className="text-sm text-neutral-500 hover:text-emerald-400 transition-colors"
|
||||
>
|
||||
Forgot password?
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="rounded-lg bg-red-500/10 border border-red-500/20 px-4 py-3">
|
||||
<p className="text-sm text-red-400">{error}</p>
|
||||
|
||||
235
apps/web/src/app/(auth)/reset-password/page.tsx
Normal file
235
apps/web/src/app/(auth)/reset-password/page.tsx
Normal file
@@ -0,0 +1,235 @@
|
||||
"use client";
|
||||
|
||||
import { Suspense, useState } from "react";
|
||||
import { useSearchParams } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { Activity, Loader2 } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export default function ResetPasswordPage() {
|
||||
return (
|
||||
<Suspense>
|
||||
<ResetPasswordForm />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
function ResetPasswordForm() {
|
||||
const searchParams = useSearchParams();
|
||||
const token = searchParams.get("token");
|
||||
|
||||
const [password, setPassword] = useState("");
|
||||
const [confirmPassword, setConfirmPassword] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [success, setSuccess] = useState(false);
|
||||
|
||||
const passwordValid = password.length >= 8;
|
||||
const passwordsMatch = password === confirmPassword;
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
|
||||
if (!passwordValid) {
|
||||
setError("Password must be at least 8 characters");
|
||||
return;
|
||||
}
|
||||
if (!passwordsMatch) {
|
||||
setError("Passwords do not match");
|
||||
return;
|
||||
}
|
||||
if (!token) {
|
||||
setError("Invalid reset link");
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/auth/reset-password", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ token, password }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data: { error?: string } = await res.json();
|
||||
setError(data.error ?? "Something went wrong");
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setSuccess(true);
|
||||
} catch {
|
||||
setError("Something went wrong. Please try again.");
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<div className="w-12 h-12 rounded-xl bg-gradient-to-br from-emerald-400 to-emerald-600 flex items-center justify-center shadow-lg shadow-emerald-500/20">
|
||||
<Activity className="w-6 h-6 text-white" />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h1 className="text-2xl font-bold text-neutral-100">
|
||||
Invalid reset link
|
||||
</h1>
|
||||
<p className="mt-1 text-sm text-neutral-400">
|
||||
This password reset link is invalid or has expired.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-center text-sm text-neutral-400">
|
||||
<Link
|
||||
href="/forgot-password"
|
||||
className="text-emerald-400 hover:text-emerald-300 font-medium transition-colors"
|
||||
>
|
||||
Request a new reset link
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (success) {
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<div className="w-12 h-12 rounded-xl bg-gradient-to-br from-emerald-400 to-emerald-600 flex items-center justify-center shadow-lg shadow-emerald-500/20">
|
||||
<Activity className="w-6 h-6 text-white" />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h1 className="text-2xl font-bold text-neutral-100">
|
||||
Password reset
|
||||
</h1>
|
||||
<p className="mt-1 text-sm text-neutral-400">
|
||||
Your password has been successfully reset.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-center text-sm text-neutral-400">
|
||||
<Link
|
||||
href="/login"
|
||||
className="text-emerald-400 hover:text-emerald-300 font-medium transition-colors"
|
||||
>
|
||||
Sign in with your new password
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<div className="w-12 h-12 rounded-xl bg-gradient-to-br from-emerald-400 to-emerald-600 flex items-center justify-center shadow-lg shadow-emerald-500/20">
|
||||
<Activity className="w-6 h-6 text-white" />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h1 className="text-2xl font-bold text-neutral-100">
|
||||
Set new password
|
||||
</h1>
|
||||
<p className="mt-1 text-sm text-neutral-400">
|
||||
Enter your new password below
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-5">
|
||||
<div className="rounded-xl bg-neutral-900 border border-neutral-800 p-6 space-y-4">
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="password"
|
||||
className="block text-sm font-medium text-neutral-300"
|
||||
>
|
||||
New password
|
||||
</label>
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
required
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="••••••••"
|
||||
className={cn(
|
||||
"w-full px-3 py-2.5 bg-neutral-950 border rounded-lg text-sm text-neutral-100 placeholder-neutral-500 outline-none transition-colors",
|
||||
password && !passwordValid
|
||||
? "border-red-500/50 focus:border-red-500"
|
||||
: "border-neutral-800 focus:border-emerald-500"
|
||||
)}
|
||||
/>
|
||||
{password && !passwordValid && (
|
||||
<p className="text-xs text-red-400">
|
||||
Password must be at least 8 characters
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<label
|
||||
htmlFor="confirmPassword"
|
||||
className="block text-sm font-medium text-neutral-300"
|
||||
>
|
||||
Confirm password
|
||||
</label>
|
||||
<input
|
||||
id="confirmPassword"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
required
|
||||
value={confirmPassword}
|
||||
onChange={(e) => setConfirmPassword(e.target.value)}
|
||||
placeholder="••••••••"
|
||||
className={cn(
|
||||
"w-full px-3 py-2.5 bg-neutral-950 border rounded-lg text-sm text-neutral-100 placeholder-neutral-500 outline-none transition-colors",
|
||||
confirmPassword && !passwordsMatch
|
||||
? "border-red-500/50 focus:border-red-500"
|
||||
: "border-neutral-800 focus:border-emerald-500"
|
||||
)}
|
||||
/>
|
||||
{confirmPassword && !passwordsMatch && (
|
||||
<p className="text-xs text-red-400">Passwords do not match</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="rounded-lg bg-red-500/10 border border-red-500/20 px-4 py-3">
|
||||
<p className="text-sm text-red-400">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className={cn(
|
||||
"w-full flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-semibold transition-colors",
|
||||
loading
|
||||
? "bg-emerald-500/50 text-neutral-950/50 cursor-not-allowed"
|
||||
: "bg-emerald-500 hover:bg-emerald-400 text-neutral-950"
|
||||
)}
|
||||
>
|
||||
{loading && <Loader2 className="w-4 h-4 animate-spin" />}
|
||||
{loading ? "Resetting..." : "Reset password"}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p className="text-center text-sm text-neutral-400">
|
||||
Remember your password?{" "}
|
||||
<Link
|
||||
href="/login"
|
||||
className="text-emerald-400 hover:text-emerald-300 font-medium transition-colors"
|
||||
>
|
||||
Sign in
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
103
apps/web/src/app/(auth)/verify-email/page.tsx
Normal file
103
apps/web/src/app/(auth)/verify-email/page.tsx
Normal file
@@ -0,0 +1,103 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { Activity, Loader2, Mail } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export default function VerifyEmailPage() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [message, setMessage] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
|
||||
async function handleResend() {
|
||||
setLoading(true);
|
||||
setMessage("");
|
||||
setError("");
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/auth/resend-verification", {
|
||||
method: "POST",
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const data: { error?: string } = await res.json();
|
||||
setError(data.error ?? "Failed to resend email");
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setMessage("Verification email sent! Check your inbox.");
|
||||
} catch {
|
||||
setError("Something went wrong. Please try again.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
<div className="flex flex-col items-center gap-4">
|
||||
<div className="w-12 h-12 rounded-xl bg-gradient-to-br from-emerald-400 to-emerald-600 flex items-center justify-center shadow-lg shadow-emerald-500/20">
|
||||
<Activity className="w-6 h-6 text-white" />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<h1 className="text-2xl font-bold text-neutral-100">
|
||||
Check your email
|
||||
</h1>
|
||||
<p className="mt-1 text-sm text-neutral-400">
|
||||
We sent a verification link to your inbox
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="rounded-xl bg-neutral-900 border border-neutral-800 p-6 space-y-4">
|
||||
<div className="flex items-center justify-center">
|
||||
<div className="w-16 h-16 rounded-full bg-emerald-500/10 border border-emerald-500/20 flex items-center justify-center">
|
||||
<Mail className="w-8 h-8 text-emerald-400" />
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-sm text-neutral-400 text-center leading-relaxed">
|
||||
Click the link in the email to verify your account. The link expires
|
||||
in 24 hours.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{message && (
|
||||
<div className="rounded-lg bg-emerald-500/10 border border-emerald-500/20 px-4 py-3">
|
||||
<p className="text-sm text-emerald-400">{message}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="rounded-lg bg-red-500/10 border border-red-500/20 px-4 py-3">
|
||||
<p className="text-sm text-red-400">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button
|
||||
onClick={handleResend}
|
||||
disabled={loading}
|
||||
className={cn(
|
||||
"w-full flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-semibold transition-colors",
|
||||
loading
|
||||
? "bg-emerald-500/50 text-neutral-950/50 cursor-not-allowed"
|
||||
: "bg-emerald-500 hover:bg-emerald-400 text-neutral-950"
|
||||
)}
|
||||
>
|
||||
{loading && <Loader2 className="w-4 h-4 animate-spin" />}
|
||||
{loading ? "Sending..." : "Resend verification email"}
|
||||
</button>
|
||||
|
||||
<p className="text-center text-sm text-neutral-400">
|
||||
Already verified?{" "}
|
||||
<Link
|
||||
href="/login"
|
||||
className="text-emerald-400 hover:text-emerald-300 font-medium transition-colors"
|
||||
>
|
||||
Sign in
|
||||
</Link>
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
95
apps/web/src/app/api/auth/forgot-password/route.ts
Normal file
95
apps/web/src/app/api/auth/forgot-password/route.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { randomBytes, createHash } from "crypto";
|
||||
import { z } from "zod";
|
||||
import nodemailer from "nodemailer";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
const forgotPasswordSchema = z.object({
|
||||
email: z.email("Invalid email address"),
|
||||
});
|
||||
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: "smtp.migadu.com",
|
||||
port: 465,
|
||||
secure: true,
|
||||
auth: {
|
||||
user: "hunter@repi.fun",
|
||||
pass: process.env.EMAIL_PASSWORD,
|
||||
},
|
||||
});
|
||||
|
||||
function hashToken(token: string): string {
|
||||
return createHash("sha256").update(token).digest("hex");
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body: unknown = await request.json();
|
||||
const parsed = forgotPasswordSchema.safeParse(body);
|
||||
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues[0]?.message ?? "Invalid input" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const { email } = parsed.data;
|
||||
const normalizedEmail = email.toLowerCase();
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: normalizedEmail },
|
||||
});
|
||||
|
||||
// Always return success to prevent email enumeration
|
||||
if (!user) {
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
|
||||
await prisma.passwordResetToken.updateMany({
|
||||
where: { userId: user.id, used: false },
|
||||
data: { used: true },
|
||||
});
|
||||
|
||||
const rawToken = randomBytes(32).toString("hex");
|
||||
const tokenHash = hashToken(rawToken);
|
||||
|
||||
await prisma.passwordResetToken.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
token: tokenHash,
|
||||
expiresAt: new Date(Date.now() + 60 * 60 * 1000),
|
||||
},
|
||||
});
|
||||
|
||||
const resetUrl = `https://agentlens.vectry.tech/reset-password?token=${rawToken}`;
|
||||
|
||||
await transporter.sendMail({
|
||||
from: '"AgentLens" <hunter@repi.fun>',
|
||||
to: normalizedEmail,
|
||||
subject: "Reset your AgentLens password",
|
||||
text: `You requested a password reset for your AgentLens account.\n\nClick the link below to set a new password:\n${resetUrl}\n\nThis link expires in 1 hour.\n\nIf you did not request this, you can safely ignore this email.`,
|
||||
html: `
|
||||
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; max-width: 480px; margin: 0 auto; padding: 40px 20px;">
|
||||
<h2 style="color: #f5f5f5; font-size: 20px; margin-bottom: 16px;">Reset your password</h2>
|
||||
<p style="color: #a3a3a3; font-size: 14px; line-height: 1.6; margin-bottom: 24px;">
|
||||
You requested a password reset for your AgentLens account. Click the button below to set a new password.
|
||||
</p>
|
||||
<a href="${resetUrl}" style="display: inline-block; background-color: #10b981; color: #0a0a0a; font-weight: 600; font-size: 14px; padding: 12px 24px; border-radius: 8px; text-decoration: none;">
|
||||
Reset password
|
||||
</a>
|
||||
<p style="color: #737373; font-size: 12px; line-height: 1.5; margin-top: 32px;">
|
||||
This link expires in 1 hour. If you did not request this, you can safely ignore this email.
|
||||
</p>
|
||||
</div>
|
||||
`,
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { hash } from "bcryptjs";
|
||||
import crypto from "crypto";
|
||||
import { z } from "zod";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { sendEmail } from "@/lib/email";
|
||||
|
||||
const registerSchema = z.object({
|
||||
email: z.email("Invalid email address"),
|
||||
@@ -57,6 +59,45 @@ export async function POST(request: Request) {
|
||||
},
|
||||
});
|
||||
|
||||
// Send verification email (non-blocking — don't fail registration on email errors)
|
||||
try {
|
||||
const rawToken = crypto.randomBytes(32).toString("hex");
|
||||
const tokenHash = crypto
|
||||
.createHash("sha256")
|
||||
.update(rawToken)
|
||||
.digest("hex");
|
||||
|
||||
await prisma.emailVerificationToken.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
token: tokenHash,
|
||||
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24 hours
|
||||
},
|
||||
});
|
||||
|
||||
const verifyUrl = `https://agentlens.vectry.tech/verify-email?token=${rawToken}`;
|
||||
await sendEmail({
|
||||
to: user.email,
|
||||
subject: "Verify your AgentLens email",
|
||||
html: `
|
||||
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 480px; margin: 0 auto; padding: 40px 20px;">
|
||||
<h2 style="color: #e5e5e5; margin-bottom: 16px;">Verify your email</h2>
|
||||
<p style="color: #a3a3a3; line-height: 1.6;">
|
||||
Thanks for signing up for AgentLens. Click the link below to verify your email address.
|
||||
</p>
|
||||
<a href="${verifyUrl}" style="display: inline-block; margin-top: 24px; padding: 12px 24px; background-color: #10b981; color: #000; text-decoration: none; border-radius: 8px; font-weight: 600;">
|
||||
Verify Email
|
||||
</a>
|
||||
<p style="color: #737373; font-size: 13px; margin-top: 32px;">
|
||||
This link expires in 24 hours. If you didn't create an account, you can safely ignore this email.
|
||||
</p>
|
||||
</div>
|
||||
`,
|
||||
});
|
||||
} catch (emailError) {
|
||||
console.error("[register] Failed to send verification email:", emailError);
|
||||
}
|
||||
|
||||
return NextResponse.json(user, { status: 201 });
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
|
||||
78
apps/web/src/app/api/auth/resend-verification/route.ts
Normal file
78
apps/web/src/app/api/auth/resend-verification/route.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import crypto from "crypto";
|
||||
import { auth } from "@/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { sendEmail } from "@/lib/email";
|
||||
|
||||
export async function POST() {
|
||||
const session = await auth();
|
||||
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: session.user.id },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: "User not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
if (user.emailVerified) {
|
||||
return NextResponse.json({ error: "Email already verified" }, { status: 400 });
|
||||
}
|
||||
|
||||
const latestToken = await prisma.emailVerificationToken.findFirst({
|
||||
where: { userId: user.id },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
|
||||
if (latestToken && Date.now() - latestToken.createdAt.getTime() < 60_000) {
|
||||
return NextResponse.json(
|
||||
{ error: "Please wait 60 seconds before requesting another email" },
|
||||
{ status: 429 }
|
||||
);
|
||||
}
|
||||
|
||||
await prisma.emailVerificationToken.updateMany({
|
||||
where: { userId: user.id, used: false },
|
||||
data: { used: true },
|
||||
});
|
||||
|
||||
const rawToken = crypto.randomBytes(32).toString("hex");
|
||||
const tokenHash = crypto
|
||||
.createHash("sha256")
|
||||
.update(rawToken)
|
||||
.digest("hex");
|
||||
|
||||
await prisma.emailVerificationToken.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
token: tokenHash,
|
||||
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),
|
||||
},
|
||||
});
|
||||
|
||||
const verifyUrl = `https://agentlens.vectry.tech/verify-email?token=${rawToken}`;
|
||||
await sendEmail({
|
||||
to: user.email,
|
||||
subject: "Verify your AgentLens email",
|
||||
html: `
|
||||
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; max-width: 480px; margin: 0 auto; padding: 40px 20px;">
|
||||
<h2 style="color: #e5e5e5; margin-bottom: 16px;">Verify your email</h2>
|
||||
<p style="color: #a3a3a3; line-height: 1.6;">
|
||||
Click the link below to verify your email address for AgentLens.
|
||||
</p>
|
||||
<a href="${verifyUrl}" style="display: inline-block; margin-top: 24px; padding: 12px 24px; background-color: #10b981; color: #000; text-decoration: none; border-radius: 8px; font-weight: 600;">
|
||||
Verify Email
|
||||
</a>
|
||||
<p style="color: #737373; font-size: 13px; margin-top: 32px;">
|
||||
This link expires in 24 hours.
|
||||
</p>
|
||||
</div>
|
||||
`,
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
63
apps/web/src/app/api/auth/reset-password/route.ts
Normal file
63
apps/web/src/app/api/auth/reset-password/route.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { createHash } from "crypto";
|
||||
import { hash } from "bcryptjs";
|
||||
import { z } from "zod";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
const resetPasswordSchema = z.object({
|
||||
token: z.string().min(1, "Token is required"),
|
||||
password: z.string().min(8, "Password must be at least 8 characters"),
|
||||
});
|
||||
|
||||
function hashToken(token: string): string {
|
||||
return createHash("sha256").update(token).digest("hex");
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body: unknown = await request.json();
|
||||
const parsed = resetPasswordSchema.safeParse(body);
|
||||
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json(
|
||||
{ error: parsed.error.issues[0]?.message ?? "Invalid input" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const { token, password } = parsed.data;
|
||||
const tokenHash = hashToken(token);
|
||||
|
||||
const resetToken = await prisma.passwordResetToken.findUnique({
|
||||
where: { token: tokenHash },
|
||||
include: { user: true },
|
||||
});
|
||||
|
||||
if (!resetToken || resetToken.used || resetToken.expiresAt < new Date()) {
|
||||
return NextResponse.json(
|
||||
{ error: "Invalid or expired reset link" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const passwordHash = await hash(password, 12);
|
||||
|
||||
await prisma.$transaction([
|
||||
prisma.user.update({
|
||||
where: { id: resetToken.userId },
|
||||
data: { passwordHash },
|
||||
}),
|
||||
prisma.passwordResetToken.update({
|
||||
where: { id: resetToken.id },
|
||||
data: { used: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: "Internal server error" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
54
apps/web/src/app/api/auth/verify-email/route.ts
Normal file
54
apps/web/src/app/api/auth/verify-email/route.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import crypto from "crypto";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const rawToken = request.nextUrl.searchParams.get("token");
|
||||
|
||||
if (!rawToken) {
|
||||
return NextResponse.redirect(
|
||||
new URL("/login?error=missing-token", request.url)
|
||||
);
|
||||
}
|
||||
|
||||
const tokenHash = crypto
|
||||
.createHash("sha256")
|
||||
.update(rawToken)
|
||||
.digest("hex");
|
||||
|
||||
const verificationToken = await prisma.emailVerificationToken.findUnique({
|
||||
where: { token: tokenHash },
|
||||
include: { user: true },
|
||||
});
|
||||
|
||||
if (!verificationToken) {
|
||||
return NextResponse.redirect(
|
||||
new URL("/login?error=invalid-token", request.url)
|
||||
);
|
||||
}
|
||||
|
||||
if (verificationToken.used) {
|
||||
return NextResponse.redirect(
|
||||
new URL("/login?verified=true", request.url)
|
||||
);
|
||||
}
|
||||
|
||||
if (verificationToken.expiresAt < new Date()) {
|
||||
return NextResponse.redirect(
|
||||
new URL("/login?error=token-expired", request.url)
|
||||
);
|
||||
}
|
||||
|
||||
await prisma.$transaction([
|
||||
prisma.user.update({
|
||||
where: { id: verificationToken.userId },
|
||||
data: { emailVerified: true },
|
||||
}),
|
||||
prisma.emailVerificationToken.update({
|
||||
where: { id: verificationToken.id },
|
||||
data: { used: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
return NextResponse.redirect(new URL("/login?verified=true", request.url));
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
import { ReactNode, useState } from "react";
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useSession } from "next-auth/react";
|
||||
import {
|
||||
Activity,
|
||||
GitBranch,
|
||||
@@ -10,6 +11,9 @@ import {
|
||||
Settings,
|
||||
Menu,
|
||||
ChevronRight,
|
||||
X,
|
||||
AlertTriangle,
|
||||
Loader2,
|
||||
} from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
@@ -101,6 +105,61 @@ function Sidebar({ onNavigate }: { onNavigate?: () => void }) {
|
||||
);
|
||||
}
|
||||
|
||||
function VerificationBanner() {
|
||||
const { data: session } = useSession();
|
||||
const [dismissed, setDismissed] = useState(false);
|
||||
const [resending, setResending] = useState(false);
|
||||
const [sent, setSent] = useState(false);
|
||||
|
||||
if (dismissed || !session?.user || session.user.isEmailVerified) {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function handleResend() {
|
||||
setResending(true);
|
||||
try {
|
||||
const res = await fetch("/api/auth/resend-verification", { method: "POST" });
|
||||
if (res.ok) {
|
||||
setSent(true);
|
||||
}
|
||||
} catch {
|
||||
} finally {
|
||||
setResending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="bg-amber-500/10 border-b border-amber-500/20 px-4 py-3">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<AlertTriangle className="w-4 h-4 text-amber-400 shrink-0" />
|
||||
<p className="text-sm text-amber-200 truncate">
|
||||
{sent
|
||||
? "Verification email sent! Check your inbox."
|
||||
: "Please verify your email address. Check your inbox or"}
|
||||
</p>
|
||||
{!sent && (
|
||||
<button
|
||||
onClick={handleResend}
|
||||
disabled={resending}
|
||||
className="text-sm font-medium text-amber-400 hover:text-amber-300 transition-colors whitespace-nowrap inline-flex items-center gap-1"
|
||||
>
|
||||
{resending && <Loader2 className="w-3 h-3 animate-spin" />}
|
||||
{resending ? "sending..." : "click to resend."}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setDismissed(true)}
|
||||
className="p-1 rounded text-amber-400/60 hover:text-amber-300 transition-colors shrink-0"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function DashboardLayout({ children }: { children: ReactNode }) {
|
||||
const [sidebarOpen, setSidebarOpen] = useState(false);
|
||||
|
||||
@@ -131,6 +190,7 @@ export default function DashboardLayout({ children }: { children: ReactNode }) {
|
||||
|
||||
{/* Main Content */}
|
||||
<main className="flex-1 min-w-0">
|
||||
<VerificationBanner />
|
||||
{/* Mobile Header */}
|
||||
<header className="lg:hidden sticky top-0 z-30 bg-neutral-950/80 backdrop-blur-md border-b border-neutral-800 px-4 py-3">
|
||||
<div className="flex items-center justify-between">
|
||||
|
||||
@@ -12,6 +12,7 @@ declare module "next-auth" {
|
||||
email: string;
|
||||
name?: string | null;
|
||||
image?: string | null;
|
||||
isEmailVerified: boolean;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -19,6 +20,7 @@ declare module "next-auth" {
|
||||
declare module "@auth/core/jwt" {
|
||||
interface JWT {
|
||||
id: string;
|
||||
isEmailVerified: boolean;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,14 +60,24 @@ export const { handlers, auth, signIn, signOut } = NextAuth({
|
||||
}),
|
||||
],
|
||||
callbacks: {
|
||||
jwt({ token, user }) {
|
||||
async jwt({ token, user, trigger }) {
|
||||
if (user) {
|
||||
token.id = user.id as string;
|
||||
}
|
||||
if (trigger === "update" || user) {
|
||||
const dbUser = await prisma.user.findUnique({
|
||||
where: { id: token.id },
|
||||
select: { emailVerified: true },
|
||||
});
|
||||
if (dbUser) {
|
||||
token.isEmailVerified = dbUser.emailVerified;
|
||||
}
|
||||
}
|
||||
return token;
|
||||
},
|
||||
session({ session, token }) {
|
||||
session.user.id = token.id;
|
||||
session.user.isEmailVerified = token.isEmailVerified;
|
||||
return session;
|
||||
},
|
||||
},
|
||||
|
||||
36
apps/web/src/lib/email.ts
Normal file
36
apps/web/src/lib/email.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import nodemailer from "nodemailer";
|
||||
|
||||
interface SendEmailOptions {
|
||||
to: string;
|
||||
subject: string;
|
||||
html: string;
|
||||
}
|
||||
|
||||
export async function sendEmail({ to, subject, html }: SendEmailOptions) {
|
||||
const password = process.env.EMAIL_PASSWORD;
|
||||
|
||||
if (!password) {
|
||||
console.warn(
|
||||
"[email] EMAIL_PASSWORD not set — skipping email send to:",
|
||||
to
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: "smtp.migadu.com",
|
||||
port: 465,
|
||||
secure: true,
|
||||
auth: {
|
||||
user: "hunter@repi.fun",
|
||||
pass: password,
|
||||
},
|
||||
});
|
||||
|
||||
await transporter.sendMail({
|
||||
from: "AgentLens <hunter@repi.fun>",
|
||||
to,
|
||||
subject,
|
||||
html,
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user