Module: middleware/authMiddleware

Authentication and authorization middleware for Express.

Source:

Requires

  • module:jsonwebtoken
  • module:../models/userModel

Methods

(inner) admin(req, res, next) → {void}

Middleware to restrict access to admin-only routes.

  • Must be used after the protect middleware.
  • Checks if req.user.role is "admin".
Parameters:
Name Type Description
req Object

Express request object. Requires req.user to be set by protect.

res Object

Express response object.

next function

Express next middleware function.

Source:
Returns:

Proceeds to next middleware if user is admin, otherwise responds with 403 Forbidden.

Type
void

(async, inner) protect(req, res, next) → {Promise.<void>}

Middleware to protect routes by verifying a JWT token.

  • Looks for a token in the Authorization header in the format: Bearer <token>.
  • Verifies the token and decodes the user ID.
  • Attaches the user (minus password) to req.user.
Parameters:
Name Type Description
req Object

Express request object. Expects an Authorization header.

res Object

Express response object.

next function

Express next middleware function.

Source:
Returns:

Proceeds to next middleware if authorized, otherwise responds with 401 Unauthorized.

Type
Promise.<void>