All files / backend/src/api/middleware auth-middleware.ts

100% Statements 12/12
100% Branches 4/4
100% Functions 2/2
100% Lines 12/12

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                                              5x   5x 5x 5x   5x 1x 1x     4x 4x 4x       4x   2x        
/**
 * JWT Auth Middleware
 *
 * Validates JWT tokens from Authorization header or ?token query parameter.
 * Attaches decoded user to req.auth when valid.
 * Returns 401 for missing/invalid tokens.
 */
 
import type { Request, Response, NextFunction } from 'express';
import type { TokenService } from '../../auth/token-service.js';
 
declare global {
  namespace Express {
    interface Request {
      auth?: {
        userId: string;
        email: string;
      };
    }
  }
}
 
export function createAuthMiddleware(tokenService: TokenService) {
  return (req: Request, res: Response, next: NextFunction) => {
    // Extract token from Authorization header or query parameter
    const headerToken = req.headers.authorization?.replace('Bearer ', '');
    const queryToken = req.query.token as string | undefined;
    const token = headerToken || queryToken;
 
    if (!token) {
      res.status(401).json({ error: 'Unauthorized' });
      return;
    }
 
    try {
      const payload = tokenService.verifyToken(token, 'access');
      req.auth = {
        userId: payload.userId,
        email: payload.email,
      };
      next();
    } catch {
      res.status(401).json({ error: 'Unauthorized' });
    }
  };
}