All files / services/scheduler-service/src/middleware auth.js

72.88% Statements 43/59
35.71% Branches 5/14
100% Functions 4/4
72.88% Lines 43/59

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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 601x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x             1x 1x     1x 1x 1x 1x 1x           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
const jwt = require('jsonwebtoken');
 
function extractJwt(req) {
  const authHeader = req.headers['authorization'];
  if (authHeader) {
    const token = authHeader.split(' ')[1];
    if (token) return token;
  }
  return null;
}
 
function getUserId(req) {
  const authHeader = req.headers['authorization'];
  if (!authHeader) return null;
  const token = authHeader.split(' ')[1];
  if (!token) return null;
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    return decoded?.userId || null;
  } catch (e) {
    return null;
  }
}
 
function getOrganizationId(req) {
  if (req.params?.organizationId) return req.params.organizationId;
  const authHeader = req.headers['authorization'];
  if (!authHeader) return null;
  const token = authHeader.split(' ')[1];
  if (!token) return null;
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    return decoded?.organizationId || null;
  } catch (e) {
    return null;
  }
}
 
function requireAuth(req, res, next) {
  const userId = getUserId(req);
  if (!userId) {
    return res.status(401).json({
      success: false,
      message: 'Authentication required',
    });
  }
  req.userId = userId;
  req.authToken = extractJwt(req);
  const orgId = getOrganizationId(req);
  if (orgId) req.organizationId = orgId;
  next();
}
 
module.exports = {
  extractJwt,
  getUserId,
  getOrganizationId,
  requireAuth,
};