ghostguild-org/server/api/helcim/customer.post.js
Jennie Robinson Faber b7279f57d1 Add Zod validation, fix mass assignment, remove test endpoints and dead code
- Add centralized Zod schemas (server/utils/schemas.js) and validateBody
  utility for all API endpoints
- Fix critical mass assignment in member creation: raw body no longer
  passed to new Member(), only validated fields (email, name, circle,
  contributionTier) are accepted
- Apply Zod validation to login, profile patch, event registration,
  updates, verify-payment, and admin event creation endpoints
- Fix logout cookie flags to match login (httpOnly: true, secure
  conditional on NODE_ENV)
- Delete unauthenticated test/debug endpoints (test-connection,
  test-subscription, test-bot)
- Remove sensitive console.log statements from Helcim and member
  endpoints
- Remove unused bcryptjs dependency
- Add 10MB file size limit on image uploads
- Use runtime config for JWT secret across all endpoints
- Add 38 validation tests (117 total, all passing)
2026-03-01 14:02:46 +00:00

142 lines
No EOL
4 KiB
JavaScript

// Create a Helcim customer
import jwt from 'jsonwebtoken'
import Member from '../../models/member.js'
import { connectDB } from '../../utils/mongoose.js'
const HELCIM_API_BASE = 'https://api.helcim.com/v2'
export default defineEventHandler(async (event) => {
try {
await connectDB()
const config = useRuntimeConfig(event)
const body = await readBody(event)
// Validate required fields
if (!body.name || !body.email) {
throw createError({
statusCode: 400,
statusMessage: 'Name and email are required'
})
}
// Check if member already exists
const existingMember = await Member.findOne({ email: body.email })
if (existingMember) {
throw createError({
statusCode: 409,
statusMessage: 'A member with this email already exists'
})
}
// Get token directly from environment if not in config
const helcimToken = config.public.helcimToken || process.env.NUXT_PUBLIC_HELCIM_TOKEN
if (!helcimToken) {
throw createError({
statusCode: 500,
statusMessage: 'Helcim API token not configured'
})
}
// Test the connection first with native fetch
try {
const testResponse = await fetch('https://api.helcim.com/v2/connection-test', {
method: 'GET',
headers: {
'accept': 'application/json',
'api-token': helcimToken
}
})
if (!testResponse.ok) {
throw new Error(`HTTP ${testResponse.status}: ${testResponse.statusText}`)
}
await testResponse.json()
} catch (testError) {
console.error('Connection test failed:', testError)
throw createError({
statusCode: 401,
statusMessage: `Helcim API connection failed: ${testError.message}`
})
}
// Create customer in Helcim using native fetch
const customerResponse = await fetch(`${HELCIM_API_BASE}/customers`, {
method: 'POST',
headers: {
'accept': 'application/json',
'content-type': 'application/json',
'api-token': helcimToken
},
body: JSON.stringify({
customerType: 'PERSON',
contactName: body.name,
email: body.email
})
})
if (!customerResponse.ok) {
const errorText = await customerResponse.text()
console.error('Customer creation failed:', customerResponse.status, errorText)
throw createError({
statusCode: customerResponse.status,
statusMessage: `Failed to create customer: ${errorText}`
})
}
const customerData = await customerResponse.json()
// Create member in database
const member = await Member.create({
email: body.email,
name: body.name,
circle: body.circle,
contributionTier: body.contributionTier,
helcimCustomerId: customerData.id,
status: 'pending_payment'
})
// Generate JWT token for the session
const token = jwt.sign(
{
memberId: member._id,
email: body.email,
helcimCustomerId: customerData.id
},
config.jwtSecret,
{ expiresIn: '24h' }
)
// Set the session cookie server-side
setCookie(event, 'auth-token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax',
maxAge: 60 * 60 * 24, // 24 hours
path: '/',
domain: undefined // Let browser set domain automatically
})
return {
success: true,
customerId: customerData.id,
customerCode: customerData.customerCode,
token,
member: {
id: member._id,
email: member.email,
name: member.name,
circle: member.circle,
contributionTier: member.contributionTier,
status: member.status
}
}
} catch (error) {
console.error('Error creating Helcim customer:', error)
throw createError({
statusCode: error.statusCode || 500,
statusMessage: error.message || 'Failed to create customer'
})
}
})