Files
OpenSquawk/server/api/service/invitations/bootstrap.post.ts

36 lines
1.1 KiB
TypeScript

import { randomBytes } from 'node:crypto'
import { createError, readBody } from 'h3'
import { InvitationCode } from '../../../models/InvitationCode'
const CREATION_DEADLINE = new Date(process.env.BOOTSTRAP_INVITE_DEADLINE ?? '2024-07-01T00:00:00Z')
export default defineEventHandler(async (event) => {
const now = new Date()
if (Number.isNaN(CREATION_DEADLINE.getTime())) {
throw createError({ statusCode: 500, statusMessage: 'Konfiguration für Bootstrap-Deadline ungültig' })
}
if (now > CREATION_DEADLINE) {
throw createError({ statusCode: 403, statusMessage: 'Bootstrap-Zeitraum abgelaufen' })
}
const body = await readBody<{ label?: string }>(event).catch(() => ({ label: undefined }))
const code = randomBytes(4).toString('hex').toUpperCase()
const expiresAt = CREATION_DEADLINE
await InvitationCode.create({
code,
createdAt: now,
expiresAt,
channel: 'bootstrap',
label: body?.label?.trim() || undefined,
})
return {
success: true,
code,
expiresAt: expiresAt.toISOString(),
label: body?.label ?? null,
}
})