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:
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));
|
||||
}
|
||||
Reference in New Issue
Block a user