All files / services/crawler-api/src/middleware auth.js

43.9% Statements 18/41
66.66% Branches 2/3
33.33% Functions 1/3
43.9% Lines 18/41

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 421x 1x             1x                             1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x  
const { requireAuth: jwtRequireAuth, peekUserId } = require('../../shared/jwtAuth');
 
function getUserId(req) {
  // Authentifié par requireAuth ? → userId vérifié
  if (req.userId) return req.userId;
  // Sinon, extraction non fiable pour logs uniquement
  return peekUserId(req);
}
 
function getOrganizationId(req) {
  if (req.params?.organizationId) return req.params.organizationId;
  if (req.organizationId) return req.organizationId;
  const authHeader = req.headers['authorization'];
  if (!authHeader) return null;
  const token = authHeader.split(' ')[1];
  if (!token) return null;
  try {
    const jwt = require('jsonwebtoken');
    const decoded = jwt.decode(token);
    return decoded?.organizationId || null;
  } catch (e) {}
  return null;
}
 
/**
 * Authentification : valide la signature JWT (requireAuth) ou le bypass API-key (x-config-id).
 */
function requireAuth(req, res, next) {
  const configId = req.headers['x-config-id'];
  if (configId) {
    req.authMethod = 'api-key';
    return next();
  }
  return jwtRequireAuth(req, res, next);
}
 
module.exports = {
  getUserId,
  getOrganizationId,
  requireAuth,
};