33 lines
1.3 KiB
TypeScript
33 lines
1.3 KiB
TypeScript
import { createHash, randomBytes } from 'node:crypto'
|
|
import { z } from 'zod'
|
|
import { requireCampaignAccess, requireStageTwoUser, stageTwoApiError, stageTwoDatabase, stageTwoUuid } from '~/server/utils/stage-two-supabase'
|
|
|
|
const BodySchema = z.object({
|
|
maxUses: z.number().int().min(1).max(20).default(1),
|
|
expiresInHours: z.number().int().min(1).max(720).default(72),
|
|
}).strict()
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
try {
|
|
const user = await requireStageTwoUser(event)
|
|
const campaignId = stageTwoUuid(getRouterParam(event, 'id'), 'campaign id')
|
|
await requireCampaignAccess(campaignId, user.id, true)
|
|
const body = BodySchema.parse((await readBody(event)) ?? {})
|
|
const token = randomBytes(32).toString('base64url')
|
|
const tokenHash = createHash('sha256').update(token).digest('hex')
|
|
const expiresAt = new Date(Date.now() + body.expiresInHours * 3_600_000).toISOString()
|
|
await stageTwoDatabase('invites', {
|
|
method: 'POST',
|
|
prefer: 'return=minimal',
|
|
body: JSON.stringify({
|
|
campaign_id: campaignId, created_by: user.id, token_hash: tokenHash,
|
|
max_uses: body.maxUses, expires_at: expiresAt,
|
|
}),
|
|
})
|
|
setResponseStatus(event, 201)
|
|
return { token, expiresAt, maxUses: body.maxUses }
|
|
} catch (error) {
|
|
stageTwoApiError(error)
|
|
}
|
|
})
|