@pintahub/admin-middleware
v1.1.1
Published
Express middleware for admin services: JWT authentication and role-based authorization.
Readme
@pintahub/admin-middleware
Express middleware for admin services: JWT authentication and role-based authorization.
Setup
const {Middleware} = require('@pintahub/admin-middleware')
const middleware = new Middleware({secretKey: process.env.JWT_SECRET_KEY})
module.exports = middlewareToken.authenticated()
Verifies the Authorization: Bearer <jwt> header and puts the decoded payload on the request:
| Property | Value |
|--------------------------|----------------------------------|
| req.authenticatedAccount | the full decoded JWT payload |
| req.accountId | _id claim |
| req.accountRole | role claim |
A missing, expired, or invalid token responds 403 {success: false, message}.
Token.requireRole(...roles)
Allows the request through only when req.accountRole is one of roles. Anything else —
wrong role, or no role on the request at all — responds 403 {success: false, message}.
const {Token} = require('../connections/middleware')
router.get('/accounts', Token.authenticated(), Token.requireRole('admin'), ctrl.listAccounts)
router.get('/orders', Token.authenticated(), Token.requireRole('admin', 'seller'), ctrl.listOrders)It must be mounted after authenticated() — that is what sets req.accountRole. Mounting it
alone denies every request (fails closed) rather than letting them through, so a route that forgets
authenticated() returns 403 instead of leaking. Role matching is exact and case-sensitive
(Account.role values are stored lowercase: 'admin', 'seller').
Calling it with no roles — requireRole(), or requireRole(['admin']) instead of
requireRole('admin') — would allow nobody, so it throws at route-registration time (app boot)
rather than silently 403-ing every request in production.
Authorization trusts the JWT claim
The role is read from the token, not from the database, so there is no lookup on the request path.
The trade-off: a token stays valid for its full lifetime (30d with remember me, otherwise 7d),
so an account whose role is downgraded keeps its old privileges until the token expires. That is
accepted for an internal tool. To revoke immediately, the role would have to be looked up per
request via options.getModel (declared in src/interfaces/Options.ts, currently unused).
Development
yarn build # tsc -> dist/
yarn test # build, then run the verification scripts in test/Only dist/ is published (see .npmignore); prepublishOnly rebuilds it so a manual
npm publish always ships a fresh build.
