feat(pitch-deck): admin UI for investor + financial-model management (#3)
All checks were successful
CI / test-go-consent (push) Successful in 42s
CI / test-python-voice (push) Successful in 30s
CI / test-bqas (push) Successful in 30s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / Deploy (push) Successful in 2s
All checks were successful
CI / test-go-consent (push) Successful in 42s
CI / test-python-voice (push) Successful in 30s
CI / test-bqas (push) Successful in 30s
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / Deploy (push) Successful in 2s
Adds /pitch-admin dashboard with real bcrypt admin accounts and full audit attribution for every state-changing action. - pitch_admins + pitch_admin_sessions tables (migration 002) - pitch_audit_logs.admin_id + target_investor_id columns - lib/admin-auth.ts: bcryptjs, single-session, jose JWT with audience claim - middleware.ts: two-cookie gating with bearer-secret CLI fallback - 14 new API routes (admin-auth, dashboard, investor detail/edit/resend, admins CRUD, fm scenarios + assumptions PATCH) - 9 admin pages: login, dashboard, investors list/new/[id], audit, financial-model list/[id], admins - Bootstrap CLI: npm run admin:create - 36 vitest tests covering auth, admin-auth, rate-limit primitives Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit was merged in pull request #3.
This commit is contained in:
81
pitch-deck/app/api/admin/admins/[id]/route.ts
Normal file
81
pitch-deck/app/api/admin/admins/[id]/route.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
import { requireAdmin, logAdminAudit, hashPassword, revokeAllAdminSessions } from '@/lib/admin-auth'
|
||||
|
||||
interface RouteContext {
|
||||
params: Promise<{ id: string }>
|
||||
}
|
||||
|
||||
export async function PATCH(request: NextRequest, ctx: RouteContext) {
|
||||
const guard = await requireAdmin(request)
|
||||
if (guard.kind === 'response') return guard.response
|
||||
const actorAdminId = guard.kind === 'admin' ? guard.admin.id : null
|
||||
|
||||
const { id } = await ctx.params
|
||||
const body = await request.json().catch(() => ({}))
|
||||
const { name, is_active, password } = body
|
||||
|
||||
const before = await pool.query(
|
||||
`SELECT email, name, is_active FROM pitch_admins WHERE id = $1`,
|
||||
[id],
|
||||
)
|
||||
if (before.rows.length === 0) {
|
||||
return NextResponse.json({ error: 'Admin not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
const updates: string[] = []
|
||||
const params: unknown[] = []
|
||||
let p = 1
|
||||
|
||||
if (typeof name === 'string' && name.trim()) {
|
||||
updates.push(`name = $${p++}`)
|
||||
params.push(name.trim())
|
||||
}
|
||||
if (typeof is_active === 'boolean') {
|
||||
updates.push(`is_active = $${p++}`)
|
||||
params.push(is_active)
|
||||
}
|
||||
if (typeof password === 'string') {
|
||||
if (password.length < 12) {
|
||||
return NextResponse.json({ error: 'password must be at least 12 characters' }, { status: 400 })
|
||||
}
|
||||
const hash = await hashPassword(password)
|
||||
updates.push(`password_hash = $${p++}`)
|
||||
params.push(hash)
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
return NextResponse.json({ error: 'no fields to update' }, { status: 400 })
|
||||
}
|
||||
|
||||
updates.push(`updated_at = NOW()`)
|
||||
params.push(id)
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE pitch_admins SET ${updates.join(', ')}
|
||||
WHERE id = $${p}
|
||||
RETURNING id, email, name, is_active, last_login_at, created_at`,
|
||||
params,
|
||||
)
|
||||
|
||||
// If deactivated or password changed, revoke their sessions
|
||||
if (is_active === false || typeof password === 'string') {
|
||||
await revokeAllAdminSessions(id)
|
||||
}
|
||||
|
||||
const action = is_active === false ? 'admin_deactivated' : 'admin_edited'
|
||||
await logAdminAudit(
|
||||
actorAdminId,
|
||||
action,
|
||||
{
|
||||
target_admin_id: id,
|
||||
target_email: before.rows[0].email,
|
||||
before: before.rows[0],
|
||||
after: { name: rows[0].name, is_active: rows[0].is_active },
|
||||
password_changed: typeof password === 'string',
|
||||
},
|
||||
request,
|
||||
)
|
||||
|
||||
return NextResponse.json({ admin: rows[0] })
|
||||
}
|
||||
52
pitch-deck/app/api/admin/admins/route.ts
Normal file
52
pitch-deck/app/api/admin/admins/route.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
import { requireAdmin, logAdminAudit, hashPassword } from '@/lib/admin-auth'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const guard = await requireAdmin(request)
|
||||
if (guard.kind === 'response') return guard.response
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`SELECT id, email, name, is_active, last_login_at, created_at, updated_at
|
||||
FROM pitch_admins ORDER BY created_at ASC`,
|
||||
)
|
||||
return NextResponse.json({ admins: rows })
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const guard = await requireAdmin(request)
|
||||
if (guard.kind === 'response') return guard.response
|
||||
const adminId = guard.kind === 'admin' ? guard.admin.id : null
|
||||
|
||||
const body = await request.json().catch(() => ({}))
|
||||
const email = (body.email || '').trim().toLowerCase()
|
||||
const name = (body.name || '').trim()
|
||||
const password = body.password || ''
|
||||
|
||||
if (!email || !name || !password) {
|
||||
return NextResponse.json({ error: 'email, name, password required' }, { status: 400 })
|
||||
}
|
||||
if (password.length < 12) {
|
||||
return NextResponse.json({ error: 'password must be at least 12 characters' }, { status: 400 })
|
||||
}
|
||||
|
||||
const hash = await hashPassword(password)
|
||||
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
`INSERT INTO pitch_admins (email, name, password_hash, is_active)
|
||||
VALUES ($1, $2, $3, true)
|
||||
RETURNING id, email, name, is_active, created_at`,
|
||||
[email, name, hash],
|
||||
)
|
||||
const newAdmin = rows[0]
|
||||
await logAdminAudit(adminId, 'admin_created', { email, name, new_admin_id: newAdmin.id }, request)
|
||||
return NextResponse.json({ admin: newAdmin })
|
||||
} catch (err) {
|
||||
const e = err as { code?: string }
|
||||
if (e.code === '23505') {
|
||||
return NextResponse.json({ error: 'Email already exists' }, { status: 409 })
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
@@ -1,42 +1,77 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
import { validateAdminSecret } from '@/lib/auth'
|
||||
import { requireAdmin } from '@/lib/admin-auth'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
if (!validateAdminSecret(request)) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
const guard = await requireAdmin(request)
|
||||
if (guard.kind === 'response') return guard.response
|
||||
|
||||
const { searchParams } = new URL(request.url)
|
||||
const investorId = searchParams.get('investor_id')
|
||||
const targetInvestorId = searchParams.get('target_investor_id')
|
||||
const adminId = searchParams.get('admin_id')
|
||||
const actorType = searchParams.get('actor_type') // 'admin' | 'investor'
|
||||
const action = searchParams.get('action')
|
||||
const since = searchParams.get('since') // ISO date
|
||||
const until = searchParams.get('until')
|
||||
const limit = Math.min(parseInt(searchParams.get('limit') || '100'), 500)
|
||||
const offset = parseInt(searchParams.get('offset') || '0')
|
||||
|
||||
const conditions: string[] = []
|
||||
const params: unknown[] = []
|
||||
let paramIdx = 1
|
||||
let p = 1
|
||||
|
||||
if (investorId) {
|
||||
conditions.push(`a.investor_id = $${paramIdx++}`)
|
||||
conditions.push(`a.investor_id = $${p++}`)
|
||||
params.push(investorId)
|
||||
}
|
||||
if (targetInvestorId) {
|
||||
conditions.push(`a.target_investor_id = $${p++}`)
|
||||
params.push(targetInvestorId)
|
||||
}
|
||||
if (adminId) {
|
||||
conditions.push(`a.admin_id = $${p++}`)
|
||||
params.push(adminId)
|
||||
}
|
||||
if (actorType === 'admin') {
|
||||
conditions.push(`a.admin_id IS NOT NULL`)
|
||||
} else if (actorType === 'investor') {
|
||||
conditions.push(`a.investor_id IS NOT NULL`)
|
||||
}
|
||||
if (action) {
|
||||
conditions.push(`a.action = $${paramIdx++}`)
|
||||
conditions.push(`a.action = $${p++}`)
|
||||
params.push(action)
|
||||
}
|
||||
if (since) {
|
||||
conditions.push(`a.created_at >= $${p++}`)
|
||||
params.push(since)
|
||||
}
|
||||
if (until) {
|
||||
conditions.push(`a.created_at <= $${p++}`)
|
||||
params.push(until)
|
||||
}
|
||||
|
||||
const where = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`SELECT a.*, i.email as investor_email, i.name as investor_name
|
||||
`SELECT a.*,
|
||||
i.email AS investor_email, i.name AS investor_name,
|
||||
ti.email AS target_investor_email, ti.name AS target_investor_name,
|
||||
ad.email AS admin_email, ad.name AS admin_name
|
||||
FROM pitch_audit_logs a
|
||||
LEFT JOIN pitch_investors i ON i.id = a.investor_id
|
||||
LEFT JOIN pitch_investors ti ON ti.id = a.target_investor_id
|
||||
LEFT JOIN pitch_admins ad ON ad.id = a.admin_id
|
||||
${where}
|
||||
ORDER BY a.created_at DESC
|
||||
LIMIT $${paramIdx++} OFFSET $${paramIdx++}`,
|
||||
[...params, limit, offset]
|
||||
LIMIT $${p++} OFFSET $${p++}`,
|
||||
[...params, limit, offset],
|
||||
)
|
||||
|
||||
return NextResponse.json({ logs: rows })
|
||||
const totalRes = await pool.query(
|
||||
`SELECT COUNT(*)::int AS total FROM pitch_audit_logs a ${where}`,
|
||||
params,
|
||||
)
|
||||
|
||||
return NextResponse.json({ logs: rows, total: totalRes.rows[0].total })
|
||||
}
|
||||
|
||||
46
pitch-deck/app/api/admin/dashboard/route.ts
Normal file
46
pitch-deck/app/api/admin/dashboard/route.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
import { requireAdmin } from '@/lib/admin-auth'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const guard = await requireAdmin(request)
|
||||
if (guard.kind === 'response') return guard.response
|
||||
|
||||
const [totals, recentLogins, recentActivity] = await Promise.all([
|
||||
pool.query(`
|
||||
SELECT
|
||||
(SELECT COUNT(*)::int FROM pitch_investors) AS total_investors,
|
||||
(SELECT COUNT(*)::int FROM pitch_investors WHERE status = 'invited') AS pending_invites,
|
||||
(SELECT COUNT(*)::int FROM pitch_investors WHERE last_login_at >= NOW() - INTERVAL '7 days') AS active_7d,
|
||||
(SELECT COUNT(*)::int FROM pitch_audit_logs WHERE action = 'slide_viewed') AS slides_viewed_total,
|
||||
(SELECT COUNT(*)::int FROM pitch_sessions WHERE revoked = false AND expires_at > NOW()) AS active_sessions,
|
||||
(SELECT COUNT(*)::int FROM pitch_admins WHERE is_active = true) AS active_admins
|
||||
`),
|
||||
pool.query(`
|
||||
SELECT a.created_at, a.ip_address, i.id AS investor_id, i.email, i.name, i.company
|
||||
FROM pitch_audit_logs a
|
||||
JOIN pitch_investors i ON i.id = a.investor_id
|
||||
WHERE a.action = 'login_success'
|
||||
ORDER BY a.created_at DESC
|
||||
LIMIT 10
|
||||
`),
|
||||
pool.query(`
|
||||
SELECT a.id, a.action, a.created_at, a.details,
|
||||
i.email AS investor_email, i.name AS investor_name,
|
||||
ti.email AS target_investor_email,
|
||||
ad.email AS admin_email, ad.name AS admin_name
|
||||
FROM pitch_audit_logs a
|
||||
LEFT JOIN pitch_investors i ON i.id = a.investor_id
|
||||
LEFT JOIN pitch_investors ti ON ti.id = a.target_investor_id
|
||||
LEFT JOIN pitch_admins ad ON ad.id = a.admin_id
|
||||
ORDER BY a.created_at DESC
|
||||
LIMIT 15
|
||||
`),
|
||||
])
|
||||
|
||||
return NextResponse.json({
|
||||
totals: totals.rows[0],
|
||||
recent_logins: recentLogins.rows,
|
||||
recent_activity: recentActivity.rows,
|
||||
})
|
||||
}
|
||||
93
pitch-deck/app/api/admin/fm/assumptions/[id]/route.ts
Normal file
93
pitch-deck/app/api/admin/fm/assumptions/[id]/route.ts
Normal file
@@ -0,0 +1,93 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
import { requireAdmin, logAdminAudit } from '@/lib/admin-auth'
|
||||
|
||||
interface RouteContext {
|
||||
params: Promise<{ id: string }>
|
||||
}
|
||||
|
||||
export async function PATCH(request: NextRequest, ctx: RouteContext) {
|
||||
const guard = await requireAdmin(request)
|
||||
if (guard.kind === 'response') return guard.response
|
||||
const adminId = guard.kind === 'admin' ? guard.admin.id : null
|
||||
|
||||
const { id } = await ctx.params
|
||||
const body = await request.json().catch(() => ({}))
|
||||
const { value, min_value, max_value, step_size, label_de, label_en } = body
|
||||
|
||||
const before = await pool.query(
|
||||
`SELECT scenario_id, key, label_de, label_en, value, min_value, max_value, step_size
|
||||
FROM pitch_fm_assumptions WHERE id = $1`,
|
||||
[id],
|
||||
)
|
||||
if (before.rows.length === 0) {
|
||||
return NextResponse.json({ error: 'Assumption not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
const updates: string[] = []
|
||||
const params: unknown[] = []
|
||||
let p = 1
|
||||
|
||||
if (value !== undefined) {
|
||||
updates.push(`value = $${p++}`)
|
||||
params.push(JSON.stringify(value))
|
||||
}
|
||||
if (min_value !== undefined) {
|
||||
updates.push(`min_value = $${p++}`)
|
||||
params.push(min_value)
|
||||
}
|
||||
if (max_value !== undefined) {
|
||||
updates.push(`max_value = $${p++}`)
|
||||
params.push(max_value)
|
||||
}
|
||||
if (step_size !== undefined) {
|
||||
updates.push(`step_size = $${p++}`)
|
||||
params.push(step_size)
|
||||
}
|
||||
if (typeof label_de === 'string') {
|
||||
updates.push(`label_de = $${p++}`)
|
||||
params.push(label_de)
|
||||
}
|
||||
if (typeof label_en === 'string') {
|
||||
updates.push(`label_en = $${p++}`)
|
||||
params.push(label_en)
|
||||
}
|
||||
|
||||
if (updates.length === 0) {
|
||||
return NextResponse.json({ error: 'no fields to update' }, { status: 400 })
|
||||
}
|
||||
|
||||
params.push(id)
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE pitch_fm_assumptions SET ${updates.join(', ')} WHERE id = $${p} RETURNING *`,
|
||||
params,
|
||||
)
|
||||
|
||||
// Invalidate cached results for this scenario so the next compute uses the new value
|
||||
await pool.query(`DELETE FROM pitch_fm_results WHERE scenario_id = $1`, [before.rows[0].scenario_id])
|
||||
|
||||
await logAdminAudit(
|
||||
adminId,
|
||||
'assumption_edited',
|
||||
{
|
||||
assumption_id: id,
|
||||
scenario_id: before.rows[0].scenario_id,
|
||||
key: before.rows[0].key,
|
||||
before: {
|
||||
value: typeof before.rows[0].value === 'string' ? JSON.parse(before.rows[0].value) : before.rows[0].value,
|
||||
min_value: before.rows[0].min_value,
|
||||
max_value: before.rows[0].max_value,
|
||||
step_size: before.rows[0].step_size,
|
||||
},
|
||||
after: {
|
||||
value: typeof rows[0].value === 'string' ? JSON.parse(rows[0].value) : rows[0].value,
|
||||
min_value: rows[0].min_value,
|
||||
max_value: rows[0].max_value,
|
||||
step_size: rows[0].step_size,
|
||||
},
|
||||
},
|
||||
request,
|
||||
)
|
||||
|
||||
return NextResponse.json({ assumption: rows[0] })
|
||||
}
|
||||
52
pitch-deck/app/api/admin/fm/scenarios/[id]/route.ts
Normal file
52
pitch-deck/app/api/admin/fm/scenarios/[id]/route.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
import { requireAdmin, logAdminAudit } from '@/lib/admin-auth'
|
||||
|
||||
interface RouteContext {
|
||||
params: Promise<{ id: string }>
|
||||
}
|
||||
|
||||
export async function PATCH(request: NextRequest, ctx: RouteContext) {
|
||||
const guard = await requireAdmin(request)
|
||||
if (guard.kind === 'response') return guard.response
|
||||
const adminId = guard.kind === 'admin' ? guard.admin.id : null
|
||||
|
||||
const { id } = await ctx.params
|
||||
const body = await request.json().catch(() => ({}))
|
||||
const { name, description, color } = body
|
||||
|
||||
if (name === undefined && description === undefined && color === undefined) {
|
||||
return NextResponse.json({ error: 'name, description, or color required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const before = await pool.query(
|
||||
`SELECT name, description, color FROM pitch_fm_scenarios WHERE id = $1`,
|
||||
[id],
|
||||
)
|
||||
if (before.rows.length === 0) {
|
||||
return NextResponse.json({ error: 'Scenario not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE pitch_fm_scenarios SET
|
||||
name = COALESCE($1, name),
|
||||
description = COALESCE($2, description),
|
||||
color = COALESCE($3, color)
|
||||
WHERE id = $4
|
||||
RETURNING *`,
|
||||
[name ?? null, description ?? null, color ?? null, id],
|
||||
)
|
||||
|
||||
await logAdminAudit(
|
||||
adminId,
|
||||
'scenario_edited',
|
||||
{
|
||||
scenario_id: id,
|
||||
before: before.rows[0],
|
||||
after: { name: rows[0].name, description: rows[0].description, color: rows[0].color },
|
||||
},
|
||||
request,
|
||||
)
|
||||
|
||||
return NextResponse.json({ scenario: rows[0] })
|
||||
}
|
||||
27
pitch-deck/app/api/admin/fm/scenarios/route.ts
Normal file
27
pitch-deck/app/api/admin/fm/scenarios/route.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
import { requireAdmin } from '@/lib/admin-auth'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
const guard = await requireAdmin(request)
|
||||
if (guard.kind === 'response') return guard.response
|
||||
|
||||
const scenarios = await pool.query(
|
||||
`SELECT * FROM pitch_fm_scenarios ORDER BY is_default DESC, name`,
|
||||
)
|
||||
const assumptions = await pool.query(
|
||||
`SELECT * FROM pitch_fm_assumptions ORDER BY scenario_id, sort_order`,
|
||||
)
|
||||
|
||||
const result = scenarios.rows.map(s => ({
|
||||
...s,
|
||||
assumptions: assumptions.rows
|
||||
.filter(a => a.scenario_id === s.id)
|
||||
.map(a => ({
|
||||
...a,
|
||||
value: typeof a.value === 'string' ? JSON.parse(a.value) : a.value,
|
||||
})),
|
||||
}))
|
||||
|
||||
return NextResponse.json({ scenarios: result })
|
||||
}
|
||||
60
pitch-deck/app/api/admin/investors/[id]/resend/route.ts
Normal file
60
pitch-deck/app/api/admin/investors/[id]/resend/route.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
import { generateToken } from '@/lib/auth'
|
||||
import { requireAdmin, logAdminAudit } from '@/lib/admin-auth'
|
||||
import { sendMagicLinkEmail } from '@/lib/email'
|
||||
import { checkRateLimit, RATE_LIMITS } from '@/lib/rate-limit'
|
||||
|
||||
interface RouteContext {
|
||||
params: Promise<{ id: string }>
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest, ctx: RouteContext) {
|
||||
const guard = await requireAdmin(request)
|
||||
if (guard.kind === 'response') return guard.response
|
||||
const adminId = guard.kind === 'admin' ? guard.admin.id : null
|
||||
|
||||
const { id } = await ctx.params
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`SELECT id, email, name, status FROM pitch_investors WHERE id = $1`,
|
||||
[id],
|
||||
)
|
||||
if (rows.length === 0) {
|
||||
return NextResponse.json({ error: 'Investor not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
const investor = rows[0]
|
||||
if (investor.status === 'revoked') {
|
||||
return NextResponse.json({ error: 'Investor is revoked. Reactivate first by re-inviting.' }, { status: 400 })
|
||||
}
|
||||
|
||||
// Rate limit by email
|
||||
const rl = checkRateLimit(`magic-link:${investor.email}`, RATE_LIMITS.magicLink)
|
||||
if (!rl.allowed) {
|
||||
return NextResponse.json({ error: 'Too many resends for this email. Try again later.' }, { status: 429 })
|
||||
}
|
||||
|
||||
const token = generateToken()
|
||||
const ttlHours = parseInt(process.env.MAGIC_LINK_TTL_HOURS || '72')
|
||||
const expiresAt = new Date(Date.now() + ttlHours * 60 * 60 * 1000)
|
||||
|
||||
await pool.query(
|
||||
`INSERT INTO pitch_magic_links (investor_id, token, expires_at) VALUES ($1, $2, $3)`,
|
||||
[investor.id, token, expiresAt],
|
||||
)
|
||||
|
||||
const baseUrl = process.env.PITCH_BASE_URL || 'https://pitch.breakpilot.ai'
|
||||
const magicLinkUrl = `${baseUrl}/auth/verify?token=${token}`
|
||||
await sendMagicLinkEmail(investor.email, investor.name, magicLinkUrl)
|
||||
|
||||
await logAdminAudit(
|
||||
adminId,
|
||||
'magic_link_resent',
|
||||
{ email: investor.email, expires_at: expiresAt.toISOString() },
|
||||
request,
|
||||
investor.id,
|
||||
)
|
||||
|
||||
return NextResponse.json({ success: true, expires_at: expiresAt.toISOString() })
|
||||
}
|
||||
99
pitch-deck/app/api/admin/investors/[id]/route.ts
Normal file
99
pitch-deck/app/api/admin/investors/[id]/route.ts
Normal file
@@ -0,0 +1,99 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
import { requireAdmin, logAdminAudit } from '@/lib/admin-auth'
|
||||
|
||||
interface RouteContext {
|
||||
params: Promise<{ id: string }>
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest, ctx: RouteContext) {
|
||||
const guard = await requireAdmin(request)
|
||||
if (guard.kind === 'response') return guard.response
|
||||
|
||||
const { id } = await ctx.params
|
||||
|
||||
const [investor, sessions, snapshots, audit] = await Promise.all([
|
||||
pool.query(
|
||||
`SELECT id, email, name, company, status, last_login_at, login_count, created_at, updated_at
|
||||
FROM pitch_investors WHERE id = $1`,
|
||||
[id],
|
||||
),
|
||||
pool.query(
|
||||
`SELECT id, ip_address, user_agent, expires_at, revoked, created_at
|
||||
FROM pitch_sessions WHERE investor_id = $1
|
||||
ORDER BY created_at DESC LIMIT 50`,
|
||||
[id],
|
||||
),
|
||||
pool.query(
|
||||
`SELECT id, scenario_id, label, is_latest, created_at
|
||||
FROM pitch_investor_snapshots WHERE investor_id = $1
|
||||
ORDER BY created_at DESC LIMIT 50`,
|
||||
[id],
|
||||
),
|
||||
pool.query(
|
||||
`SELECT a.id, a.action, a.created_at, a.details, a.ip_address, a.slide_id,
|
||||
ad.email AS admin_email, ad.name AS admin_name
|
||||
FROM pitch_audit_logs a
|
||||
LEFT JOIN pitch_admins ad ON ad.id = a.admin_id
|
||||
WHERE a.investor_id = $1 OR a.target_investor_id = $1
|
||||
ORDER BY a.created_at DESC LIMIT 100`,
|
||||
[id],
|
||||
),
|
||||
])
|
||||
|
||||
if (investor.rows.length === 0) {
|
||||
return NextResponse.json({ error: 'Investor not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
investor: investor.rows[0],
|
||||
sessions: sessions.rows,
|
||||
snapshots: snapshots.rows,
|
||||
audit: audit.rows,
|
||||
})
|
||||
}
|
||||
|
||||
export async function PATCH(request: NextRequest, ctx: RouteContext) {
|
||||
const guard = await requireAdmin(request)
|
||||
if (guard.kind === 'response') return guard.response
|
||||
const adminId = guard.kind === 'admin' ? guard.admin.id : null
|
||||
|
||||
const { id } = await ctx.params
|
||||
const body = await request.json().catch(() => ({}))
|
||||
const { name, company } = body
|
||||
|
||||
if (name === undefined && company === undefined) {
|
||||
return NextResponse.json({ error: 'name or company required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const before = await pool.query(
|
||||
`SELECT name, company FROM pitch_investors WHERE id = $1`,
|
||||
[id],
|
||||
)
|
||||
if (before.rows.length === 0) {
|
||||
return NextResponse.json({ error: 'Investor not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE pitch_investors SET
|
||||
name = COALESCE($1, name),
|
||||
company = COALESCE($2, company),
|
||||
updated_at = NOW()
|
||||
WHERE id = $3
|
||||
RETURNING id, email, name, company, status`,
|
||||
[name ?? null, company ?? null, id],
|
||||
)
|
||||
|
||||
await logAdminAudit(
|
||||
adminId,
|
||||
'investor_edited',
|
||||
{
|
||||
before: before.rows[0],
|
||||
after: { name: rows[0].name, company: rows[0].company },
|
||||
},
|
||||
request,
|
||||
id,
|
||||
)
|
||||
|
||||
return NextResponse.json({ investor: rows[0] })
|
||||
}
|
||||
@@ -1,18 +1,17 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
import { validateAdminSecret } from '@/lib/auth'
|
||||
import { requireAdmin } from '@/lib/admin-auth'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
if (!validateAdminSecret(request)) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
const guard = await requireAdmin(request)
|
||||
if (guard.kind === 'response') return guard.response
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`SELECT i.id, i.email, i.name, i.company, i.status, i.last_login_at, i.login_count, i.created_at,
|
||||
(SELECT COUNT(*) FROM pitch_audit_logs a WHERE a.investor_id = i.id AND a.action = 'slide_viewed') as slides_viewed,
|
||||
(SELECT MAX(a.created_at) FROM pitch_audit_logs a WHERE a.investor_id = i.id) as last_activity
|
||||
FROM pitch_investors i
|
||||
ORDER BY i.created_at DESC`
|
||||
ORDER BY i.created_at DESC`,
|
||||
)
|
||||
|
||||
return NextResponse.json({ investors: rows })
|
||||
|
||||
@@ -1,22 +1,23 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
import { validateAdminSecret, generateToken, logAudit, getClientIp } from '@/lib/auth'
|
||||
import { generateToken } from '@/lib/auth'
|
||||
import { requireAdmin, logAdminAudit } from '@/lib/admin-auth'
|
||||
import { sendMagicLinkEmail } from '@/lib/email'
|
||||
import { checkRateLimit, RATE_LIMITS } from '@/lib/rate-limit'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
if (!validateAdminSecret(request)) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
const guard = await requireAdmin(request)
|
||||
if (guard.kind === 'response') return guard.response
|
||||
const adminId = guard.kind === 'admin' ? guard.admin.id : null
|
||||
|
||||
const body = await request.json()
|
||||
const body = await request.json().catch(() => ({}))
|
||||
const { email, name, company } = body
|
||||
|
||||
if (!email || typeof email !== 'string') {
|
||||
return NextResponse.json({ error: 'Email required' }, { status: 400 })
|
||||
}
|
||||
|
||||
// Rate limit by email
|
||||
// Rate limit by email (3/hour)
|
||||
const rl = checkRateLimit(`magic-link:${email.toLowerCase()}`, RATE_LIMITS.magicLink)
|
||||
if (!rl.allowed) {
|
||||
return NextResponse.json({ error: 'Too many invites for this email. Try again later.' }, { status: 429 })
|
||||
@@ -34,7 +35,7 @@ export async function POST(request: NextRequest) {
|
||||
status = CASE WHEN pitch_investors.status = 'revoked' THEN 'invited' ELSE pitch_investors.status END,
|
||||
updated_at = NOW()
|
||||
RETURNING id, status`,
|
||||
[normalizedEmail, name || null, company || null]
|
||||
[normalizedEmail, name || null, company || null],
|
||||
)
|
||||
|
||||
const investor = rows[0]
|
||||
@@ -47,17 +48,21 @@ export async function POST(request: NextRequest) {
|
||||
await pool.query(
|
||||
`INSERT INTO pitch_magic_links (investor_id, token, expires_at)
|
||||
VALUES ($1, $2, $3)`,
|
||||
[investor.id, token, expiresAt]
|
||||
[investor.id, token, expiresAt],
|
||||
)
|
||||
|
||||
// Build magic link URL
|
||||
const baseUrl = process.env.PITCH_BASE_URL || 'https://pitch.breakpilot.ai'
|
||||
const magicLinkUrl = `${baseUrl}/auth/verify?token=${token}`
|
||||
|
||||
// Send email
|
||||
await sendMagicLinkEmail(normalizedEmail, name || null, magicLinkUrl)
|
||||
|
||||
await logAudit(investor.id, 'magic_link_sent', { email: normalizedEmail }, request)
|
||||
await logAdminAudit(
|
||||
adminId,
|
||||
'investor_invited',
|
||||
{ email: normalizedEmail, name: name || null, company: company || null, expires_at: expiresAt.toISOString() },
|
||||
request,
|
||||
investor.id,
|
||||
)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
|
||||
@@ -1,26 +1,32 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import pool from '@/lib/db'
|
||||
import { validateAdminSecret, revokeAllSessions, logAudit } from '@/lib/auth'
|
||||
import { revokeAllSessions } from '@/lib/auth'
|
||||
import { requireAdmin, logAdminAudit } from '@/lib/admin-auth'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
if (!validateAdminSecret(request)) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
const guard = await requireAdmin(request)
|
||||
if (guard.kind === 'response') return guard.response
|
||||
const adminId = guard.kind === 'admin' ? guard.admin.id : null
|
||||
|
||||
const body = await request.json()
|
||||
const body = await request.json().catch(() => ({}))
|
||||
const { investor_id } = body
|
||||
|
||||
if (!investor_id) {
|
||||
return NextResponse.json({ error: 'investor_id required' }, { status: 400 })
|
||||
}
|
||||
|
||||
await pool.query(
|
||||
`UPDATE pitch_investors SET status = 'revoked', updated_at = NOW() WHERE id = $1`,
|
||||
[investor_id]
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE pitch_investors SET status = 'revoked', updated_at = NOW()
|
||||
WHERE id = $1 RETURNING email`,
|
||||
[investor_id],
|
||||
)
|
||||
|
||||
if (rows.length === 0) {
|
||||
return NextResponse.json({ error: 'Investor not found' }, { status: 404 })
|
||||
}
|
||||
|
||||
await revokeAllSessions(investor_id)
|
||||
await logAudit(investor_id, 'investor_revoked', {}, request)
|
||||
await logAdminAudit(adminId, 'investor_revoked', { email: rows[0].email }, request, investor_id)
|
||||
|
||||
return NextResponse.json({ success: true })
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user