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
protectmiddleware. - Checks if
req.user.roleis"admin".
Parameters:
| Name | Type | Description |
|---|---|---|
req |
Object | Express request object. Requires |
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
Authorizationheader 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 |
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>