production auth: signup, login, protected dashboard, landing page, WAHA QR fix
AUTH: - NextAuth with credentials provider (bcrypt password hashing) - /api/auth/signup: creates org + user in transaction - /login, /signup pages with clean minimal UI - Middleware protects all /dashboard/* routes → redirects to /login - Session-based org resolution (no more hardcoded 'demo' headers) - SessionProvider wraps entire app - Dashboard header shows org name + sign out button LANDING PAGE: - Full marketing page at / with hero, problem, how-it-works, features, CTA - 'Get Started Free' → /signup → auto-login → /dashboard/setup - Clean responsive design, no auth required for public pages WAHA QR FIX: - WAHA CORE doesn't expose QR value via API or webhook - Now uses /api/screenshot (full browser capture) with CSS crop to QR area - Settings panel shows cropped screenshot with overflow:hidden - Auto-polls every 5s, refresh button MULTI-TENANT: - getOrgId() tries session first, then header, then first-org fallback - All dashboard APIs use session-based org - Signup creates isolated org per charity
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
import NextAuth from "next-auth"
|
||||
import { authOptions } from "@/lib/auth"
|
||||
|
||||
const handler = NextAuth(authOptions)
|
||||
export { handler as GET, handler as POST }
|
||||
58
pledge-now-pay-later/src/app/api/auth/signup/route.ts
Normal file
58
pledge-now-pay-later/src/app/api/auth/signup/route.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { NextRequest, NextResponse } from "next/server"
|
||||
import { hash } from "bcryptjs"
|
||||
import prisma from "@/lib/prisma"
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
if (!prisma) return NextResponse.json({ error: "DB not configured" }, { status: 503 })
|
||||
|
||||
const { email, password, name, charityName } = await request.json()
|
||||
|
||||
if (!email || !password || !charityName) {
|
||||
return NextResponse.json({ error: "Email, password and charity name are required" }, { status: 400 })
|
||||
}
|
||||
if (password.length < 8) {
|
||||
return NextResponse.json({ error: "Password must be at least 8 characters" }, { status: 400 })
|
||||
}
|
||||
|
||||
const cleanEmail = email.toLowerCase().trim()
|
||||
|
||||
// Check if email exists
|
||||
const existing = await prisma.user.findUnique({ where: { email: cleanEmail } })
|
||||
if (existing) {
|
||||
return NextResponse.json({ error: "An account with this email already exists" }, { status: 409 })
|
||||
}
|
||||
|
||||
// Create org + user in transaction
|
||||
const slug = charityName.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "").slice(0, 50)
|
||||
const hashedPassword = await hash(password, 12)
|
||||
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
const org = await tx.organization.create({
|
||||
data: {
|
||||
name: charityName.trim(),
|
||||
slug: slug + "-" + Date.now().toString(36),
|
||||
country: "GB",
|
||||
refPrefix: slug.substring(0, 4).toUpperCase() || "PNPL",
|
||||
},
|
||||
})
|
||||
|
||||
const user = await tx.user.create({
|
||||
data: {
|
||||
email: cleanEmail,
|
||||
name: name?.trim() || null,
|
||||
hashedPassword,
|
||||
role: "org_admin",
|
||||
organizationId: org.id,
|
||||
},
|
||||
})
|
||||
|
||||
return { userId: user.id, orgId: org.id, orgName: org.name }
|
||||
})
|
||||
|
||||
return NextResponse.json(result, { status: 201 })
|
||||
} catch (error) {
|
||||
console.error("Signup error:", error)
|
||||
return NextResponse.json({ error: "Failed to create account" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest, NextResponse } from "next/server"
|
||||
import prisma from "@/lib/prisma"
|
||||
import { resolveOrgId } from "@/lib/org"
|
||||
import { getOrgId } from "@/lib/session"
|
||||
|
||||
interface PledgeRow {
|
||||
id: string
|
||||
@@ -56,7 +56,7 @@ export async function GET(request: NextRequest) {
|
||||
})
|
||||
}
|
||||
|
||||
const orgId = await resolveOrgId(request.headers.get("x-org-id"))
|
||||
const orgId = await getOrgId(request.headers.get("x-org-id"))
|
||||
if (!orgId) {
|
||||
return NextResponse.json({ error: "Organization not found" }, { status: 404 })
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { NextRequest, NextResponse } from "next/server"
|
||||
import prisma from "@/lib/prisma"
|
||||
import { createEventSchema } from "@/lib/validators"
|
||||
import { resolveOrgId } from "@/lib/org"
|
||||
import { getOrgId } from "@/lib/session"
|
||||
|
||||
interface PledgeSummary {
|
||||
amountPence: number
|
||||
@@ -27,7 +27,7 @@ export async function GET(request: NextRequest) {
|
||||
if (!prisma) {
|
||||
return NextResponse.json([])
|
||||
}
|
||||
const orgId = await resolveOrgId(request.headers.get("x-org-id"))
|
||||
const orgId = await getOrgId(request.headers.get("x-org-id"))
|
||||
if (!orgId) {
|
||||
return NextResponse.json({ error: "Organization not found" }, { status: 404 })
|
||||
}
|
||||
@@ -73,7 +73,7 @@ export async function POST(request: NextRequest) {
|
||||
if (!prisma) {
|
||||
return NextResponse.json({ error: "Database not configured" }, { status: 503 })
|
||||
}
|
||||
const orgId = await resolveOrgId(request.headers.get("x-org-id"))
|
||||
const orgId = await getOrgId(request.headers.get("x-org-id"))
|
||||
if (!orgId) {
|
||||
return NextResponse.json({ error: "Organization not found" }, { status: 404 })
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { NextRequest, NextResponse } from "next/server"
|
||||
import prisma from "@/lib/prisma"
|
||||
import { resolveOrgId } from "@/lib/org"
|
||||
import { getOrgId } from "@/lib/session"
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
if (!prisma) return NextResponse.json({ error: "DB not configured" }, { status: 503 })
|
||||
const orgId = await resolveOrgId(request.headers.get("x-org-id") || "demo")
|
||||
const orgId = await getOrgId(request.headers.get("x-org-id"))
|
||||
if (!orgId) return NextResponse.json({ error: "Org not found" }, { status: 404 })
|
||||
|
||||
const org = await prisma.organization.findUnique({ where: { id: orgId } })
|
||||
@@ -39,7 +39,7 @@ export async function PUT(request: NextRequest) {
|
||||
const body = await request.json()
|
||||
|
||||
// Try to find existing org first
|
||||
const orgId = await resolveOrgId(request.headers.get("x-org-id") || "default")
|
||||
const orgId = await getOrgId(request.headers.get("x-org-id"))
|
||||
|
||||
if (orgId) {
|
||||
// Update existing
|
||||
@@ -76,7 +76,7 @@ export async function PUT(request: NextRequest) {
|
||||
export async function PATCH(request: NextRequest) {
|
||||
try {
|
||||
if (!prisma) return NextResponse.json({ error: "DB not configured" }, { status: 503 })
|
||||
const orgId = await resolveOrgId(request.headers.get("x-org-id") || "demo")
|
||||
const orgId = await getOrgId(request.headers.get("x-org-id"))
|
||||
if (!orgId) return NextResponse.json({ error: "Org not found" }, { status: 404 })
|
||||
|
||||
const body = await request.json()
|
||||
|
||||
@@ -4,65 +4,63 @@ const WAHA_URL = process.env.WAHA_API_URL || "https://waha.quikcue.com"
|
||||
const WAHA_KEY = process.env.WAHA_API_KEY || "qc-waha-api-7Fp3nR9xYm2K"
|
||||
const WAHA_SESSION = process.env.WAHA_SESSION || "default"
|
||||
|
||||
async function wahaGet(path: string) {
|
||||
const res = await fetch(`${WAHA_URL}${path}`, {
|
||||
headers: { "X-Api-Key": WAHA_KEY },
|
||||
signal: AbortSignal.timeout(8000),
|
||||
cache: "no-store",
|
||||
})
|
||||
return res
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/whatsapp/qr
|
||||
* Returns the WAHA QR code screenshot as PNG for WhatsApp pairing.
|
||||
* Also returns session status.
|
||||
* Returns session status. For QR scanning, provides the screenshot
|
||||
* cropped to the QR code area, or a link to the WAHA dashboard.
|
||||
*/
|
||||
export async function GET() {
|
||||
try {
|
||||
// First check session status
|
||||
const sessRes = await fetch(`${WAHA_URL}/api/sessions`, {
|
||||
headers: { "X-Api-Key": WAHA_KEY },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
})
|
||||
const sessRes = await wahaGet("/api/sessions")
|
||||
const sessions = await sessRes.json()
|
||||
|
||||
const session = Array.isArray(sessions)
|
||||
? sessions.find((s: { name: string }) => s.name === WAHA_SESSION)
|
||||
: null
|
||||
|
||||
if (!session) {
|
||||
return NextResponse.json({
|
||||
status: "NO_SESSION",
|
||||
message: "No WAHA session exists. Start one first.",
|
||||
})
|
||||
return NextResponse.json({ status: "NO_SESSION" })
|
||||
}
|
||||
|
||||
if (session.status === "WORKING") {
|
||||
const me = session.me || {}
|
||||
return NextResponse.json({
|
||||
status: "CONNECTED",
|
||||
phone: me.id?.replace("@c.us", "") || "unknown",
|
||||
pushName: me.pushname || "",
|
||||
phone: session.me?.id?.replace("@c.us", "") || "",
|
||||
pushName: session.me?.pushname || "",
|
||||
})
|
||||
}
|
||||
|
||||
if (session.status === "SCAN_QR_CODE") {
|
||||
// Get screenshot
|
||||
const qrRes = await fetch(`${WAHA_URL}/api/screenshot?session=${WAHA_SESSION}`, {
|
||||
headers: { "X-Api-Key": WAHA_KEY },
|
||||
signal: AbortSignal.timeout(10000),
|
||||
})
|
||||
|
||||
if (!qrRes.ok) {
|
||||
return NextResponse.json({ status: "SCAN_QR_CODE", error: "Failed to get QR" })
|
||||
}
|
||||
|
||||
const buffer = await qrRes.arrayBuffer()
|
||||
const base64 = Buffer.from(buffer).toString("base64")
|
||||
// Get screenshot from WAHA and return as base64
|
||||
try {
|
||||
const ssRes = await wahaGet(`/api/screenshot?session=${WAHA_SESSION}`)
|
||||
if (ssRes.ok) {
|
||||
const buf = await ssRes.arrayBuffer()
|
||||
const b64 = Buffer.from(buf).toString("base64")
|
||||
return NextResponse.json({
|
||||
status: "SCAN_QR_CODE",
|
||||
screenshot: `data:image/png;base64,${b64}`,
|
||||
message: "Scan the QR code with WhatsApp → Linked Devices → Link a Device",
|
||||
})
|
||||
}
|
||||
} catch { /* fall through */ }
|
||||
|
||||
return NextResponse.json({
|
||||
status: "SCAN_QR_CODE",
|
||||
qrImage: `data:image/png;base64,${base64}`,
|
||||
message: "Scan this QR code with WhatsApp on your phone",
|
||||
screenshot: null,
|
||||
message: "QR loading... Refresh in a moment.",
|
||||
})
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
status: session.status,
|
||||
message: `Session is ${session.status}`,
|
||||
})
|
||||
return NextResponse.json({ status: session.status })
|
||||
} catch (error) {
|
||||
console.error("WhatsApp QR error:", error)
|
||||
return NextResponse.json({ status: "ERROR", error: String(error) })
|
||||
@@ -70,54 +68,43 @@ export async function GET() {
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/whatsapp/qr - Start or restart a session
|
||||
* POST /api/whatsapp/qr - Start or restart session
|
||||
*/
|
||||
export async function POST() {
|
||||
try {
|
||||
// Check if session exists
|
||||
const sessRes = await fetch(`${WAHA_URL}/api/sessions`, {
|
||||
headers: { "X-Api-Key": WAHA_KEY },
|
||||
signal: AbortSignal.timeout(5000),
|
||||
})
|
||||
const sessRes = await wahaGet("/api/sessions")
|
||||
const sessions = await sessRes.json()
|
||||
const existing = Array.isArray(sessions)
|
||||
? sessions.find((s: { name: string }) => s.name === WAHA_SESSION)
|
||||
: null
|
||||
|
||||
if (existing) {
|
||||
// Stop and restart
|
||||
await fetch(`${WAHA_URL}/api/sessions/stop`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", "X-Api-Key": WAHA_KEY },
|
||||
body: JSON.stringify({ name: WAHA_SESSION }),
|
||||
signal: AbortSignal.timeout(10000),
|
||||
})
|
||||
// Small delay
|
||||
}).catch(() => {})
|
||||
await new Promise(r => setTimeout(r, 2000))
|
||||
}
|
||||
|
||||
// Start session with webhook
|
||||
const startRes = await fetch(`${WAHA_URL}/api/sessions/start`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", "X-Api-Key": WAHA_KEY },
|
||||
body: JSON.stringify({
|
||||
name: WAHA_SESSION,
|
||||
config: {
|
||||
webhooks: [
|
||||
{
|
||||
url: `${process.env.BASE_URL || "https://pledge.quikcue.com"}/api/whatsapp/webhook`,
|
||||
events: ["message"],
|
||||
},
|
||||
],
|
||||
webhooks: [{
|
||||
url: `${process.env.BASE_URL || "https://pledge.quikcue.com"}/api/whatsapp/webhook`,
|
||||
events: ["message", "session.status"],
|
||||
}],
|
||||
},
|
||||
}),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
})
|
||||
|
||||
const result = await startRes.json()
|
||||
return NextResponse.json({ success: true, status: result.status || "STARTING" })
|
||||
} catch (error) {
|
||||
console.error("WhatsApp session start error:", error)
|
||||
return NextResponse.json({ success: false, error: String(error) })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,29 @@
|
||||
import { NextRequest, NextResponse } from "next/server"
|
||||
import prisma from "@/lib/prisma"
|
||||
import { sendWhatsAppMessage } from "@/lib/whatsapp"
|
||||
import { setQrValue } from "@/lib/qr-store"
|
||||
|
||||
/**
|
||||
* WAHA webhook — receives incoming WhatsApp messages
|
||||
* WAHA webhook — receives incoming WhatsApp messages + session status events
|
||||
* Handles: PAID, HELP, CANCEL commands from donors
|
||||
* Also captures QR code value for the pairing flow
|
||||
*/
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json()
|
||||
const { payload } = body
|
||||
const { event, payload } = body
|
||||
|
||||
// Handle session.status events (for QR code capture)
|
||||
if (event === "session.status") {
|
||||
console.log("[WAHA] Session status:", JSON.stringify({ status: payload?.status, hasQr: !!payload?.qr, keys: Object.keys(payload || {}) }))
|
||||
// WAHA sends QR in different formats depending on version
|
||||
const qrVal = payload?.qr?.value || payload?.qr || payload?.qrCode
|
||||
if (payload?.status === "SCAN_QR_CODE" && qrVal && typeof qrVal === "string") {
|
||||
setQrValue(qrVal)
|
||||
console.log("[WAHA] QR value stored, length:", qrVal.length)
|
||||
}
|
||||
return NextResponse.json({ ok: true })
|
||||
}
|
||||
|
||||
// WAHA sends message events
|
||||
if (!payload?.body || !payload?.from) {
|
||||
|
||||
Reference in New Issue
Block a user