(params: {
req: NextRequest
getUserInfoFromApiKey: GetUserInfoFromApiKeyFn
logger: Logger
loggerWithContext: LoggerWithContextFn
trackEvent: TrackEventFn
authErrorEvent: AnalyticsEvent
})
| 83 | } |
| 84 | |
| 85 | export const requireUserFromApiKey = async (params: { |
| 86 | req: NextRequest |
| 87 | getUserInfoFromApiKey: GetUserInfoFromApiKeyFn |
| 88 | logger: Logger |
| 89 | loggerWithContext: LoggerWithContextFn |
| 90 | trackEvent: TrackEventFn |
| 91 | authErrorEvent: AnalyticsEvent |
| 92 | }): Promise< |
| 93 | HandlerResult<{ userId: string; userInfo: UserInfo; logger: Logger }> |
| 94 | > => { |
| 95 | const { |
| 96 | req, |
| 97 | getUserInfoFromApiKey, |
| 98 | logger: baseLogger, |
| 99 | loggerWithContext, |
| 100 | trackEvent, |
| 101 | authErrorEvent, |
| 102 | } = params |
| 103 | |
| 104 | const apiKey = extractApiKeyFromHeader(req) |
| 105 | if (!apiKey) { |
| 106 | trackEvent({ |
| 107 | event: authErrorEvent, |
| 108 | userId: 'unknown', |
| 109 | properties: { reason: 'Missing API key' }, |
| 110 | logger: baseLogger, |
| 111 | }) |
| 112 | return { |
| 113 | ok: false, |
| 114 | response: NextResponse.json({ message: 'Unauthorized' }, { status: 401 }), |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | const userInfo = await getUserInfoFromApiKey({ |
| 119 | apiKey, |
| 120 | fields: ['id', 'email', 'discord_id'], |
| 121 | logger: baseLogger, |
| 122 | }) |
| 123 | if (!userInfo) { |
| 124 | trackEvent({ |
| 125 | event: authErrorEvent, |
| 126 | userId: 'unknown', |
| 127 | properties: { reason: 'Invalid API key' }, |
| 128 | logger: baseLogger, |
| 129 | }) |
| 130 | return { |
| 131 | ok: false, |
| 132 | response: NextResponse.json( |
| 133 | { message: 'Invalid Codebuff API key' }, |
| 134 | { status: 401 }, |
| 135 | ), |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | const logger = loggerWithContext({ userInfo }) |
| 140 | return { ok: true, data: { userId: userInfo.id, userInfo, logger } } |
| 141 | } |
| 142 |
no test coverage detected