All files / src/middleware auth.js

100% Statements 15/15
100% Branches 2/2
100% Functions 1/1
100% Lines 15/15

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 264x 4x 4x 4x     90x   90x 2x     88x   88x 88x 88x 88x   2x 2x       4x  
const jwt = require("jsonwebtoken");
const SECRET = process.env.JWT_SECRET;
const { ForbiddenError } = require("../lib/errors");
const { UnauthorizedError } = require("../lib/errors");
 
function authenticate(req, res, next) {
  const authHeader = req.headers.authorization;
 
  if (!authHeader?.startsWith("Bearer ")) {
    throw new UnauthorizedError("No token provided"); // This correctly throws a 401 for NO token
  }
 
  const token = authHeader.split(" ")[1];
 
  try {
    const decoded = jwt.verify(token, SECRET);
    req.user = decoded;
    next();
  } catch (err) {
    req.log.warn({ err }, "Error authenticating");
    next(err); // Pass the original JWT error to the central error handler
  }
}
 
module.exports = authenticate;