api key authentication system implementation
This commit is contained in:
48
middleware/auth.ts
Normal file
48
middleware/auth.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
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)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user