Closes P0 #6 from PARTIAL to RESOLVED. 8/8 P0s now closed. Extends lib/rate-limit.js from single-class to 5 named limiters (auth/search/upload/generate/import). Atomically gates the 3 import routes (auth + admin-role check + rate limit) and fixes pages/admin/card-import.js's missing Bearer header in the same commit (architect's critical discovery: API gating alone would have broken the admin UI). Per Decision 1 Option A. 10 files +185/-23. Local: lint 128 baseline, vitest 21/21. CI: Playwright smoke 3/3 in 3.8s, forbidden-cors-headers pass, all gates green. PR #20 architect-commit60b842e, implementer-commit51a3a97. Brief 4's login.js + register.js byte-identical.
54 lines
No EOL
1.5 KiB
JavaScript
54 lines
No EOL
1.5 KiB
JavaScript
import { sql } from '@vercel/postgres';
|
|
import jwt from 'jsonwebtoken';
|
|
import { JWT_SECRET } from '../../../lib/auth-secret.js';
|
|
import { checkSearchRateLimit } from '../../../lib/rate-limit.js';
|
|
|
|
export default async function handler(req, res) {
|
|
if (req.method !== 'GET') {
|
|
return res.status(405).json({ error: 'Method not allowed' });
|
|
}
|
|
|
|
// Verify authentication
|
|
const authHeader = req.headers.authorization;
|
|
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
|
return res.status(401).json({ error: 'Authentication required' });
|
|
}
|
|
|
|
const token = authHeader.substring(7);
|
|
try {
|
|
jwt.verify(token, JWT_SECRET);
|
|
} catch (error) {
|
|
return res.status(401).json({ error: 'Invalid token' });
|
|
}
|
|
|
|
const { allowed, reset } = await checkSearchRateLimit(req);
|
|
if (!allowed) {
|
|
res.setHeader('Retry-After', Math.ceil((reset - Date.now()) / 1000));
|
|
return res.status(429).json({ error: 'Too many attempts. Try again later.' });
|
|
}
|
|
|
|
const { q: query } = req.query;
|
|
|
|
if (!query || query.length < 2) {
|
|
return res.status(400).json({ error: 'Query must be at least 2 characters' });
|
|
}
|
|
|
|
try {
|
|
// Search users by email (partial match)
|
|
const result = await sql`
|
|
SELECT id, email, role, created_at
|
|
FROM users
|
|
WHERE email ILIKE ${`%${query}%`}
|
|
ORDER BY email
|
|
LIMIT 10
|
|
`;
|
|
|
|
res.status(200).json({
|
|
users: result.rows
|
|
});
|
|
|
|
} catch (error) {
|
|
console.error('User search error:', error);
|
|
res.status(500).json({ error: 'Internal server error' });
|
|
}
|
|
}
|