File size: 1,236 Bytes
a705c01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const ApiKey = require('../models/ApiKey');
const User = require('../models/User');

const apiKeyAuth = async (req, res, next) => {
  let key;

  // Check for API key in headers
  if (req.headers['x-api-key']) {
    key = req.headers['x-api-key'];
  } else if (req.headers.authorization && req.headers.authorization.startsWith('Bearer sk-cdx-')) {
    key = req.headers.authorization.split(' ')[1];
  }

  if (!key) {
    return next(); // Proceed to next middleware (maybe regular JWT auth)
  }

  try {
    const apiKeyDoc = await ApiKey.findOne({ key, isActive: true });

    if (!apiKeyDoc) {
      return res.status(401).json({ success: false, error: 'Invalid or inactive API key' });
    }

    // Attach user to request
    const user = await User.findById(apiKeyDoc.userId);
    if (!user) {
      return res.status(401).json({ success: false, error: 'User associated with this key not found' });
    }

    req.user = user;
    req.isApiKey = true;
    
    // Update last used
    apiKeyDoc.lastUsed = Date.now();
    await apiKeyDoc.save();

    next();
  } catch (err) {
    console.error('API Key Auth Error:', err);
    res.status(500).json({ success: false, error: 'Server Error' });
  }
};

module.exports = apiKeyAuth;