src/middlewares/auth.middleware.ts
Overview
All middleware functions extract a Bearer token fromAuthorization, verify it against SECRET_KEY, load the user from MongoDB, and confirm the token matches loginToken on the user document.
Helper functions
Exported middleware
isAdmin
- Requires valid JWT and matching
loginToken - Requires
user.role === 'admin' - Sets
req.user = { id: user._id, type: user.role } - Returns
401if token missing/invalid;403if not admin
isAuth
- Same token/session checks as
isAdmin - Accepts any role (
adminoruser) - No page-access filtering
isUser(allowedPages?)
- Factory returning an
asyncHandler-wrapped middleware - Requires
user.role === 'user'(admins are rejected) - If
allowedPagesis set, checkspageAccesspopulation - Returns
403 Access denied to this pageon mismatch
isToken(allowedPages?)
- Factory returning an
asyncHandler-wrapped middleware - Accepts any authenticated role
- Admins bypass page-access checks
- Non-admin users must have matching
pageAccesswhenallowedPagesis provided
asyncHandler(fn)
Wraps async route handlers to forward errors to Express error middleware.
Page access check logic
pageAccess is populated with AppSetting documents. The index field on each setting (e.g. nifty50, bankNifty) is compared against PageAccess enum values.