48 lines
1.3 KiB
TypeScript
48 lines
1.3 KiB
TypeScript
import type { NextApiRequest, NextApiResponse } from 'next'
|
|
import { validateApiKey, hasPermission, ApiKey } from '../lib/api-auth'
|
|
|
|
export interface AuthenticatedRequest extends NextApiRequest {
|
|
apiKey?: ApiKey
|
|
}
|
|
|
|
export function requireAuth(permission?: string) {
|
|
return async (
|
|
req: AuthenticatedRequest,
|
|
res: NextApiResponse,
|
|
next: () => void
|
|
) => {
|
|
const apiKeyHeader = req.headers['x-api-key'] as string
|
|
|
|
if (!apiKeyHeader) {
|
|
return res.status(401).json({ error: 'API key required' })
|
|
}
|
|
|
|
const apiKey = await validateApiKey(apiKeyHeader)
|
|
|
|
if (!apiKey) {
|
|
return res.status(401).json({ error: 'Invalid API key' })
|
|
}
|
|
|
|
if (permission && !hasPermission(apiKey, permission)) {
|
|
return res.status(403).json({ error: 'Insufficient permissions' })
|
|
}
|
|
|
|
req.apiKey = apiKey
|
|
next()
|
|
}
|
|
}
|
|
|
|
export function withAuth(
|
|
handler: (req: AuthenticatedRequest, res: NextApiResponse) => Promise<void>,
|
|
permission?: string
|
|
) {
|
|
return async (req: AuthenticatedRequest, res: NextApiResponse) => {
|
|
const authMiddleware = requireAuth(permission)
|
|
|
|
return new Promise<void>((resolve, reject) => {
|
|
authMiddleware(req, res, () => {
|
|
handler(req, res).then(resolve).catch(reject)
|
|
})
|
|
})
|
|
}
|
|
} |