All files / src/utils tokenMiddleware.ts

100% Statements 11/11
100% Branches 6/6
100% Functions 1/1
100% Lines 11/11

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          5x     5x 1x 1x       4x 4x   4x 3x 3x 3x   1x    
import { NextFunction, Request, Response } from "express"
import pino from "pino"
 
import { env } from "../config"
 
const logger = pino()
 
export async function TokenMiddleware(req: Request, res: Response, next: NextFunction): Promise<void> {
  if (!env.useApiToken) {
    logger.debug("API token protection is disabled, skipping token verification")
    return next()
  }
 
  // Token is passed in the query parameters as ?api_token=...TOKEN
  const token = req.query.api_token as string | undefined
  logger.debug("Verifying API token")
 
  if (!token || token !== env.apiToken) {
    logger.error("Invalid or missing API token")
    await res.status(401).send("Unauthorized")
    return
  }
  return next()
}