Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/Imjuanisss/proyecto-melika/llms.txt

Use this file to discover all available pages before exploring further.

MELIKA’s access-control layer is composed of four Express middleware functions defined in authMiddleware.js. verifyToken validates the JWT on every protected request; the three role guards (isAdmin, isMedico, isPaciente) are applied on top of it to restrict individual routes or entire routers to a single role. All middleware functions attach data to req.usuario so subsequent handlers can read the authenticated user’s identity without touching the database again.
The JWT payload shape is { id, nombre, rol }. The rol field will be one of "paciente", "medico", or "admin". Every middleware below reads from this decoded payload, so the token must be valid before any role guard runs.

verifyToken

verifyToken reads the authorization request header (lowercase bracket notation: req.headers['authorization']), extracts the Bearer token, and verifies it against JWT_SECRET. On success it populates req.usuario with the decoded payload and calls next(). On failure it ends the request immediately with a 401.

How it works

1

Read the header

The middleware reads req.headers['authorization'] (lowercase key). If the header is absent or falsy, it returns 401 immediately.
2

Extract the token

The header value is split on a space (' ') and index [1] is taken as the Bearer token.
3

Verify with JWT_SECRET

jwt.verify(token, process.env.JWT_SECRET) is called. If verification succeeds, the decoded object is stored on req.usuario.
4

Continue or reject

A valid token calls next(). An invalid or expired token returns 401 with "Token inválido o expirado.".

Error responses

StatusMessageTrigger
401"Acceso denegado. Token requerido."authorization header is missing
401"Token inválido o expirado."Token signature is wrong or TTL has elapsed

Role guards

Role guards are thin middleware functions that inspect req.usuario.rol (set by verifyToken) and either call next() or return a 403. They must always be chained after verifyToken.

Guard reference

MiddlewareRequired role403 message
isAdmin"admin""Acceso restringido a administradores."
isMedico"medico""Acceso restringido a médicos."
isPaciente"paciente""Acceso restringido a pacientes."

Calling a protected endpoint

Pass the JWT returned by POST /auth/login in the Authorization header of every subsequent request.
curl -H "Authorization: Bearer <token>" \
  https://your-api.railway.app/citas/mis-citas
Replace <token> with the string value of the token field from the login response.

Applying guards: route-level vs. router-level

Guards can be attached at two granularities depending on how broadly the restriction should apply.

Router-level (applies to all routes in a file)

Place verifyToken and the appropriate role guard as the first arguments to router.use() at the top of the router file. Every route registered below it will require that role.
// adminRoutes.js
const { verifyToken, isAdmin } = require('../middleware/authMiddleware');

router.use(verifyToken, isAdmin); // all routes below require admin

router.get('/usuarios', getAllUsers);
router.delete('/usuarios/:id', deleteUser);

Route-level (applies to a single endpoint)

Pass the guards directly in the route definition when only certain endpoints within a router need protection.
// citasRoutes.js
const { verifyToken, isMedico, isPaciente } = require('../middleware/authMiddleware');

router.get('/mis-citas',      verifyToken, isPaciente, getMisCitas);
router.put('/:id/confirmar',  verifyToken, isMedico,   confirmarCita);

Response scenarios

Requesting a protected route without an Authorization header:
curl https://your-api.railway.app/citas/mis-citas
{
  "mensaje": "Acceso denegado. Token requerido."
}
HTTP 401

Quick-reference card

verifyToken

Reads authorization header via req.headers['authorization'], splits on space to get index [1], verifies with JWT_SECRET, and populates req.usuario. Required on every protected route.

isAdmin

Asserts req.usuario.rol === 'admin'. Returns 403 for any other role.

isMedico

Asserts req.usuario.rol === 'medico'. Returns 403 for any other role.

isPaciente

Asserts req.usuario.rol === 'paciente'. Returns 403 for any other role.

Build docs developers (and LLMs) love