|
| 1 | +import { NextRequest, NextResponse } from "next/server"; |
| 2 | +import { adminAuth, adminDb } from "@/lib/firebase/admin"; |
| 3 | +import { Resend } from "resend"; |
| 4 | +import { SUPER_ADMIN_EMAIL } from "@/lib/constants"; |
| 5 | + |
| 6 | +const APP_URL = process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000"; |
| 7 | +const isDev = process.env.NODE_ENV === "development"; |
| 8 | + |
| 9 | +export async function POST(request: NextRequest) { |
| 10 | + try { |
| 11 | + const { email } = await request.json(); |
| 12 | + if (!email) return NextResponse.json({ error: "Email required" }, { status: 400 }); |
| 13 | + |
| 14 | + if (email !== SUPER_ADMIN_EMAIL) { |
| 15 | + // Allow existing members or those with a valid (unused) invitation |
| 16 | + const [userSnap, invSnap] = await Promise.all([ |
| 17 | + adminDb.collection("users").where("email", "==", email).where("profileComplete", "==", true).get(), |
| 18 | + adminDb.collection("invitations").where("email", "==", email).get(), |
| 19 | + ]); |
| 20 | + |
| 21 | + const hasAccount = !userSnap.empty; |
| 22 | + const hasValidInvitation = !invSnap.empty && !invSnap.docs[0].data().usedAt; |
| 23 | + |
| 24 | + if (!hasAccount && !hasValidInvitation) { |
| 25 | + return NextResponse.json( |
| 26 | + { error: "No account found for this email." }, |
| 27 | + { status: 404 } |
| 28 | + ); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + const link = await adminAuth.generateSignInWithEmailLink(email, { |
| 33 | + url: `${APP_URL}/login/verify`, |
| 34 | + handleCodeInApp: true, |
| 35 | + }); |
| 36 | + |
| 37 | + if (isDev) { |
| 38 | + console.log("\n📬 [DEV] Magic sign-in link (not sent)"); |
| 39 | + console.log(` To: ${email}`); |
| 40 | + console.log(` Link: ${link}\n`); |
| 41 | + } else { |
| 42 | + const resend = new Resend(process.env.RESEND_API_KEY); |
| 43 | + await resend.emails.send({ |
| 44 | + from: "AppDev Alumni <noreply@alumni.cornellappdev.com>", |
| 45 | + to: email, |
| 46 | + subject: "Your sign-in link for Cornell AppDev Alumni", |
| 47 | + html: `<p>Hi,</p><p>Click the link below to sign in. This link expires in 1 hour and can only be used once.</p><p><a href="${link}">Sign in to AppDev Alumni</a></p><p>If you didn't request this, you can ignore this email.</p>`, |
| 48 | + }); |
| 49 | + } |
| 50 | + |
| 51 | + return NextResponse.json({ ok: true }); |
| 52 | + } catch (error) { |
| 53 | + console.error("Send link error:", error); |
| 54 | + return NextResponse.json({ error: "Internal server error" }, { status: 500 }); |
| 55 | + } |
| 56 | +} |
0 commit comments