Skip to content

Auth Middleware

Authentication Middleware Documentation

This Node.js module contains middleware functions for user authentication and authorization in an Express application. The functions are:

  1. authenticateJWT:

    • Purpose: Verifies JWT tokens in the request header.
    • How: Extracts the token from the Authorization header, verifies it using JWT’s verify method, and stores the decoded payload in res.locals.user.
    • Importance: Centralizes JWT verification logic, making it reusable across different routes.
  2. ensureLoggedIn:

    • Purpose: Ensures the user is authenticated (logged in).
    • How: Checks if res.locals.user is set (by authenticateJWT), indicating an authenticated session.
    • Importance: Prevents unauthorized access to routes requiring a logged-in user.
  3. ensureAdmin:

    • Purpose: Restricts access to admin-only routes.
    • How: Validates if the authenticated user (res.locals.user) has is_admin set to true.
    • Importance: Secures sensitive routes by allowing only users with admin privileges.
  4. ensureCorrectUserOrAdmin:

    • Purpose: Validates access for the correct user or an admin.
    • How: Confirms if the authenticated user is either the one specified in the route parameters (req.params.id) or an admin.
    • Importance: Provides a flexible authorization mechanism, supporting both user-specific and admin-level access.

Each middleware enhances the security and integrity of the application by ensuring proper access controls and user authentication. They are integral to creating secure routes and protecting sensitive data.