Auth Middleware
Authentication Middleware Documentation
This Node.js module contains middleware functions for user authentication and authorization in an Express application. The functions are:
-
authenticateJWT:
- Purpose: Verifies JWT tokens in the request header.
- How: Extracts the token from the
Authorizationheader, verifies it using JWT’sverifymethod, and stores the decoded payload inres.locals.user. - Importance: Centralizes JWT verification logic, making it reusable across different routes.
-
ensureLoggedIn:
- Purpose: Ensures the user is authenticated (logged in).
- How: Checks if
res.locals.useris set (byauthenticateJWT), indicating an authenticated session. - Importance: Prevents unauthorized access to routes requiring a logged-in user.
-
ensureAdmin:
- Purpose: Restricts access to admin-only routes.
- How: Validates if the authenticated user (
res.locals.user) hasis_adminset totrue. - Importance: Secures sensitive routes by allowing only users with admin privileges.
-
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.