(params: {
req: NextRequest
getUserInfoFromApiKey: GetUserInfoFromApiKeyFn
getUserUsageData: GetUserUsageDataFn
getOrganizationUsageResponse: GetOrganizationUsageResponseFn
trackEvent: TrackEventFn
logger: Logger
})
| 24 | }) |
| 25 | |
| 26 | export async function postUsage(params: { |
| 27 | req: NextRequest |
| 28 | getUserInfoFromApiKey: GetUserInfoFromApiKeyFn |
| 29 | getUserUsageData: GetUserUsageDataFn |
| 30 | getOrganizationUsageResponse: GetOrganizationUsageResponseFn |
| 31 | trackEvent: TrackEventFn |
| 32 | logger: Logger |
| 33 | }) { |
| 34 | const { |
| 35 | req, |
| 36 | getUserInfoFromApiKey, |
| 37 | getUserUsageData, |
| 38 | getOrganizationUsageResponse, |
| 39 | trackEvent, |
| 40 | logger, |
| 41 | } = params |
| 42 | |
| 43 | try { |
| 44 | let body: unknown |
| 45 | try { |
| 46 | body = await req.json() |
| 47 | } catch (error) { |
| 48 | return NextResponse.json( |
| 49 | { message: 'Invalid JSON in request body' }, |
| 50 | { status: 400 }, |
| 51 | ) |
| 52 | } |
| 53 | |
| 54 | const parseResult = usageRequestSchema.safeParse(body) |
| 55 | if (!parseResult.success) { |
| 56 | return NextResponse.json( |
| 57 | { message: 'Invalid request body', issues: parseResult.error.issues }, |
| 58 | { status: 400 }, |
| 59 | ) |
| 60 | } |
| 61 | |
| 62 | const { fingerprintId, authToken: bodyAuthToken, orgId } = parseResult.data |
| 63 | |
| 64 | // Prefer Authorization header, fall back to body authToken for backwards compatibility |
| 65 | const authToken = extractApiKeyFromHeader(req) ?? bodyAuthToken |
| 66 | |
| 67 | if (!authToken) { |
| 68 | return NextResponse.json( |
| 69 | { message: 'Authentication required' }, |
| 70 | { status: 401 }, |
| 71 | ) |
| 72 | } |
| 73 | |
| 74 | const userInfo = await getUserInfoFromApiKey({ |
| 75 | apiKey: authToken, |
| 76 | fields: ['id'], |
| 77 | logger, |
| 78 | }) |
| 79 | |
| 80 | if (!userInfo) { |
| 81 | trackEvent({ |
| 82 | event: AnalyticsEvent.USAGE_API_AUTH_ERROR, |
| 83 | userId: 'unknown', |
no test coverage detected