7. El servidor RdvMedecins, una caja negra
Los ejemplos 17 a 20, seguidos del caso de estudio, interactúan con un servidor: el servidor JSON de la aplicación [RdvMedecins]. Es el servidor [NestJS] de la lección anterior, cuyos controladores ya no generan páginas HTML sino que producen respuestas JSON. Sus capas de negocio y de acceso a datos permanecen sin cambios.
En este curso, este servidor es una caja negra: no necesitamos saber cómo está escrito. Lo único que importa es su API, es decir, la lista de solicitudes HTTP que acepta y las respuestas que devuelve. Esta es la situación típica de un desarrollador de clientes: la API es un contrato, y el equipo del servidor puede cambiar lo que quiera detrás de ese contrato. Su código fuente se proporciona (carpeta [rdvmedecins-nestjs-json]) y está ampliamente comentado, para el lector curioso.
Este capítulo explica cómo instalar el servidor, describe su API y lo consulta con [curl].
7.1. La aplicación RdvMedecins
La aplicación gestiona las citas de un consultorio médico. Tiene tres roles:
Rol | Quién | Qué puede hacer |
[ADMIN] | El administrador ([admin]) | Programar y cancelar citas de todos los pacientes; administrar médicos y clientes |
[DOCTOR] | Los médicos ([pelissier], [tatou], [dupont]) | Programar y cancelar citas de todos los pacientes; ver todos los nombres en las agendas |
[USER] | Los pacientes ([martin], [durand], [bistrou], [german]) | reservar citas para sí mismos; cancelar sus citas; administrar sus cuentas. En una agenda, no pueden ver los nombres de otros pacientes |
Las cuentas de demostración usan su nombre de usuario como contraseña. Las reglas de gestión las verifica el servidor, independientemente del cliente:
- no hay citas en el pasado;
- solo una cita futura por paciente;
- un horario solo se puede reservar una vez por día;
- dos médicos (o dos clientes) no pueden tener el mismo nombre y apellido; un nombre de usuario pertenece a una sola cuenta;
- un médico con citas no se puede eliminar;
- un registro que ha sido modificado entretanto por otra persona no se puede sobrescribir (bloqueo optimista);
- a un paciente nunca se le asigna el nombre de otro paciente.
7.2. Instalación
Necesitará [Node.js] y un servidor [MySQL] (o [MariaDB]): su instalación se describe en el apéndice.
1. La base de datos. El script [database/dbrdvmedecins2.sql] crea la base de datos [dbrdvmedecins2], sus tablas y sus datos de ejemplo. Con [Laragon], ejecútelo desde [HeidiSQL] (menú Archivo / Ejecutar un archivo SQL); en la línea de comandos:
mysql -u root -p < database/dbrdvmedecins2.sql
El script siempre parte de una base de datos vacía: puede volver a ejecutarlo para restaurar los datos originales.
2. Bibliotecas. En una consola abierta en la carpeta [rdvmedecins-nestjs-json]:
3. Configuración. Copie el archivo [.env.example] a [.env] (en [Windows]: [copy .env.example .env]) y luego modifíquelo:
| # -----------------------------------------------------------------------
# Archivo de configuración de ejemplo.
# Copie este archivo a [.env] y luego adapte los valores a su máquina.
# El archivo [.env] nunca debe compartirse ni subirse al repositorio (contraseñas).
# -----------------------------------------------------------------------
# puerto de escucha del servidor JSON (el cliente Vue.js lo alcanza a través del proxy de Vite)
PORT=8080
# parámetros de conexión a la base de datos MySQL [dbrdvmedecins2]
# (script: database/dbrdvmedecins2.sql)
DB_HOST=localhost
DB_PORT=3306
DB_USERNAME=root
DB_PASSWORD=
DB_DATABASE=dbrdvmedecins2
# true: muestra en la consola las consultas SQL enviadas a MySQL
DB_LOGGING=false
# -----------------------------------------------------------------------
# autenticación
# -----------------------------------------------------------------------
# clave secreta usada para firmar/verificar los tokens JWT - DEBE cambiarse
# en producción (una cadena aleatoria larga, nunca subida al repositorio).
JWT_SECRET=change-me-to-a-long-random-string
# validez de un token JWT, en segundos (7200 s = 2 h). La cookie
# que transporta el token tiene la misma duración.
JWT_EXPIRES_IN_SECONDS=7200
# establézcalo en true en producción (sitio servido por HTTPS): la cookie de
# autenticación nunca se enviará entonces por una conexión sin cifrar.
COOKIE_SECURE=false
# -----------------------------------------------------------------------
# protección contra bots
# -----------------------------------------------------------------------
# login: número de fallos (captcha o contraseña incorrectos) permitidos para
# el mismo login desde la misma dirección IP, antes de que este par sea bloqueado...
LOGIN_MAX_FAILURES=5
# ... durante este tiempo (una dirección IP también se bloquea si acumula
# 5 veces más fallos, todos los logins combinados)
LOGIN_BLOCK_MINUTES=15
# creación de cuentas de cliente: número máximo de cuentas creadas por hora
# desde la misma dirección IP. En un aula, todas las computadoras suelen salir
# por la misma dirección: aumente el valor si es necesario.
REGISTRATION_MAX_PER_HOUR=10
# MODO DE PRUEBA del captcha: si esta variable tiene un valor, ese valor es
# aceptado como respuesta a CUALQUIER captcha. Práctico para consultar
# la API con curl (no se puede "leer" la imagen en una consola).
# Déjela VACÍA en producción.
CAPTCHA_TEST=
# -----------------------------------------------------------------------
# producción
# -----------------------------------------------------------------------
# carpeta del cliente Vue.js compilado, servido por este servidor (predeterminado: client/)
# CLIENT_DIR=client
# establézcalo en true si el servidor está detrás de un proxy (nginx...)
TRUST_PROXY=false
|
- línea 8: el servidor escucha en el puerto 8080;
- Líneas 12–16: la conexión a [MySQL]. Con [Laragon], el usuario [root] no tiene contraseña: los valores predeterminados sirven;
- línea 25: la clave secreta que firma los tokens de autenticación;
- líneas 38–45: protecciones antibots (bloqueo tras varios intentos fallidos de inicio de sesión, número de cuentas creadas por hora);
- línea 51: el modo de prueba de CAPTCHA. La página de inicio de sesión exige que el usuario vuelva a escribir los caracteres de una imagen, lo cual es imposible desde una consola. Si esta variable tiene un valor, ese valor se acepta como respuesta a cualquier CAPTCHA, de forma similar a las “claves de prueba” que [Google] ofrece para su [reCAPTCHA]. Para las pruebas con [curl] en este capítulo, ingrese [CAPTCHA_TEST=test]. Déjela VACÍA en producción;
- líneas 57–59: dos ajustes para producción (véase el capítulo “Despliegue”).
4. Inicio.
La consola muestra (extracto):
| [Nest] LOG [NestFactory] Starting Nest application...
[Nest] WARN [RdvMedecins] captcha TEST MODE active (CAPTCHA_TEST in .env): never use it in production
[Nest] LOG [RoutesResolver] ScheduleController {/api/schedule}:
[Nest] LOG [RouterExplorer] Mapped {/api/schedule, GET} route
[Nest] LOG [RoutesResolver] AppointmentsController {/api/appointments}:
...
[Nest] LOG [NestApplication] Nest application successfully started
[Nest] LOG [RdvMedecins] JSON server started: http://localhost:8080/api
|
Si la base de datos no está accesible (servidor [MySQL] detenido, contraseña incorrecta), el servidor se detiene de inmediato con un mensaje de error de conexión.
Todas las URL comienzan con [/api]. Una solicitud exitosa recibe un código de estado 2xx y, en su cuerpo, los datos solicitados en formato JSON. Una solicitud rechazada recibe un código de estado 4xx o 5xx y, en el cuerpo, datos en el mismo formato:
| {
"statusCode": 400,
"key": "ERRORS.INVALID_FORM",
"params": { "min": "6" },
"fields": { "lastName": "ERRORS.LASTNAME_REQUIRED", "password": "ERRORS.PASSWORD_TOO_SHORT" }
}
|
- [statusCode]: el código HTTP, repetido en el cuerpo;
- [key]: la clave de traducción del mensaje. El servidor nunca devuelve texto para mostrar: ya no conoce el idioma del usuario. Es el cliente quien traduce la clave con sus diccionarios (véase el Ejemplo 16);
- [params] (opcional): los parámetros del mensaje ([At least {min} characters.], [Try again in {minutes} minute(s).]);
- [fields] (opcional): para un formulario rechazado, el error de cada campo.
Códigos utilizados:
Código | Significado | Ejemplos de claves |
400 | Solicitud no válida | [ERRORS.INVALID_FORM] (+ fields), [ERRORS.INVALID_DATE], [ERRORS.WRONG_CAPTCHA], [ERRORS.CHOOSE_PATIENT], [ERRORS.WRONG_CURRENT_PASSWORD], [ERRORS.BAD_REQUEST]... |
401 | no autenticado | [ERRORS.AUTH_REQUIRED] (sin token), [ERRORS.SESSION_EXPIRED] (token no válido o vencido), [LOGIN.ERROR] |
403 | Acceso denegado | [ERRORS.FORBIDDEN] (rol insuficiente), [ERRORS.CAPTCHA_BEFORE_ACCOUNT] (sin pase) |
404 | No encontrado | [ERRORS.NOT_FOUND], [ERRORS.DOCTOR_NOT_FOUND], [ERRORS.APPOINTMENT_NOT_FOUND]... |
409 | Violación de una regla de negocio | [ERRORS.PAST_DATE], [ERRORS.SLOT_ALREADY_BOOKED], [ERRORS.LOGIN_TAKEN], [ERRORS.CONCURRENT_UPDATE]... |
415 | POST que no está en JSON | [ERRORS.JSON_REQUIRED] |
429 | Demasiados intentos | [ERRORS.TOO_MANY_ATTEMPTS], [ERRORS.TOO_MANY_ACCOUNTS] (+ params.minutes) |
500 | error del servidor | [ERRORS.SERVER_ERROR] |
7.4. Autenticación
El cliente se autentica mediante [POST /api/auth/login], con un nombre de usuario, una contraseña y una respuesta al CAPTCHA. A cambio, el servidor coloca en el navegador una cookie que contiene un token JWT firmado:
| Set-Cookie: rdvmedecins_jwt=eyJhbGciOiJIUzI1NiIs...; Max-Age=7200; Path=/api; HttpOnly; SameSite=Strict
|
Sus atributos son importantes para la seguridad:
- [HttpOnly]: el código [JavaScript] de la página no puede leer esta cookie. Por lo tanto, un script malicioso inyectado en la página no podría robar el token. Consecuencia para el cliente: no puede determinar por sí mismo si ha iniciado sesión. Se lo pregunta al servidor ([GET /api/auth/me]);
- [Path=/api]: el navegador solo la incluye en las solicitudes a la API;
- [SameSite=Strict]: el navegador solo incluye este token en las solicitudes enviadas DESDE una página de este sitio. Una página maliciosa de otro sitio no puede hacer que el navegador actúe en nombre del usuario (lo que se conoce como ataque CSRF);
- [Max-Age=7200]: vence después de dos horas, al mismo tiempo que vence el token.
A partir de entonces, el navegador envía automáticamente esta cookie con cada solicitud a [/api]. Por lo tanto, el cliente [Vue.js] no tiene nada que hacer para autenticarse, siempre que sus páginas y la API compartan el mismo origen (mismo protocolo, misma máquina, mismo puerto). Este es el papel del proxy de [Vite] durante el desarrollo (véase el Ejemplo 17) y del propio servidor en producción (véase el capítulo “Despliegue”).
Una segunda salvaguarda contra los ataques CSRF: el servidor rechaza (415) toda solicitud POST cuyo cuerpo no esté en JSON. Un formulario HTML comprometido en otro sitio no puede enviar JSON.
7.5. La API
Método | Dirección | Roles | Cuerpo enviado/respuesta |
GET | [/api/captcha] | público | Respuesta: [{ id, svg }] |
POST | [/api/auth/login] | público | [{ login, password, captchaId, captcha }]; respuesta: [{ login, name, role }] + cookie |
POST | [/api/auth/logout] | público | [{}] ; elimina la cookie |
GET | [/api/auth/me] | con sesión iniciada | respuesta: [{ login, name, role }] |
GET | [/api/schedule?doctorId=&day=] | todos | Respuesta: la agenda (sin doctorId: para un DOCTOR, la suya) |
POST | [/api/appointments] | todos | [{ day, slotId, clientId }] (clientId se ignora para un USER); 201 |
DELETE | [/api/appointments/:id] | todos | Un USER solo cancela las suyas |
GET | [/api/doctors] | todos | la lista (con login para ADMIN) |
GET | [/api/clients] | ADMIN, DOCTOR | la lista (con login para ADMIN) |
GET | [/api/doctors/:id], [/api/clients/:id] | ADMIN | una ficha |
POST | [/api/doctors], [/api/clients] | ADMIN | [{ title, firstName, lastName, login?, password? }]; 201 |
PUT | [/api/doctors/:id], [/api/clients/:id] | ADMIN | [{ title, firstName, lastName, login?, password?, version }] |
DELETE | [/api/doctors/:id], [/api/clients/:id] | ADMIN | Respuesta: [{}] |
POST | [/api/register/access] | público | [{ captchaId, captcha }]; emite un token (cookie) |
GET | [/api/register/access] | público | respuesta: [{ valid }] |
POST | [/api/register] | público + pase | [{ title, firstName, lastName, login, password, confirmation }]; 201 |
GET | [/api/my-area] | USER | respuesta: [{ patient, appointments }] |
GET | [/api/my-account] | USER | Respuesta: [{ title, firstName, lastName, login, version }] |
PUT | [/api/my-account] | USER | [{ title, firstName, lastName, login, password?, confirmation?, currentPassword, version }] |
DELETE | [/api/my-account] | USER | [{ currentPassword }]; elimina la cuenta y sus citas |
Una entrada de la agenda ([GET /api/schedule]) describe un horario Y lo que el usuario con sesión iniciada está autorizado a hacer con él:
| { "id": 3, "startHour": 8, "startMinute": 40, "endHour": 9, "endMinute": 0,
"free": false,
"patient": { "title": "Mme", "firstName": "Alice", "lastName": "DURAND" },
"mine": false, "bookable": false, "appointmentId": 2 }
|
- [free]: ¿el horario está disponible ese día?
- [patient]: el paciente de la cita. Para un paciente con sesión iniciada, es igual a [null], salvo en el caso de SU PROPIA cita: los nombres de otros pacientes nunca se envían;
- [mine]: es la cita del paciente con sesión iniciada;
- [bookable]: ¿puede el usuario reservar este horario (disponible, no pasado y, en el caso de un paciente, sin citas futuras)?
- [appointmentId]: se establece si el usuario puede cancelar esta cita.
El servidor DECIDE; el cliente lo muestra. E incluso si un cliente hiciera trampa (mostrando un botón “Reservar” cuando no debería), el servidor volvería a verificar todo en el momento de la reserva.
7.6. Consultar la API con curl
La carpeta [curl] del servidor contiene los cuerpos de solicitud JSON de este capítulo, un archivo por solicitud. Por ejemplo, [curl/login-admin.json]:
| { "login": "admin", "password": "admin", "captchaId": "-", "captcha": "test" }
|
Los comandos se ingresan en una consola abierta en el directorio [rdvmedecins-nestjs-json]. Algunas opciones de [curl]:
- [-i]: muestra también los encabezados de la respuesta; [-s]: sin barra de progreso;
- [--json @file]: envía el contenido del archivo mediante POST, con el encabezado [Content-Type: application/json] (curl 7.82 y posteriores; con una versión anterior, use [-H "Content-Type: application/json" -d @file]);
- [-X PUT], [-X DELETE]: el método HTTP;
- [-c cookies.txt]: guarda las cookies recibidas en este archivo; [-b cookies.txt]: las envía de vuelta. Así es como [curl] “mantiene la sesión iniciada” de un comando a otro, tal como lo haría un navegador.
En [PowerShell], debe ingresar [curl.exe], no [curl] (que se refiere a otro comando). Las respuestas algo extensas de JSON se han formateado para este documento, y se han eliminado los encabezados [Date], [ETag], [Connection], y [Keep-Alive] .
7.6.1. Inicio de sesión
Primero, el CAPTCHA (la imagen está recortada):
| $ curl -i http://localhost:8080/api/captcha
HTTP/1.1 200 OK
Cache-Control: no-store
Content-Type: application/json; charset=utf-8
Content-Length: 15076
{"id": "abf00f0c-60c0-4fde-9782-9906815e26a1", "svg": "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"150..."}
|
Sin un token, una URL protegida devuelve una respuesta 401:
| $ curl -i http://localhost:8080/api/doctors
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Content-Length: 47
{"statusCode": 401, "key": "ERRORS.AUTH_REQUIRED"}
|
Un CAPTCHA incorrecto, seguido de una contraseña incorrecta:
| $ curl -i --json @curl/login-wrong-captcha.json http://localhost:8080/api/auth/login
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
Content-Length: 91
{"statusCode": 400, "key": "ERRORS.WRONG_CAPTCHA", "fields": {"captcha": "ERRORS.WRONG_CAPTCHA"}}
|
| $ curl -i --json @curl/login-wrong-password.json http://localhost:8080/api/auth/login
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Content-Length: 38
{"statusCode": 401, "key": "LOGIN.ERROR"}
|
Un inicio de sesión exitoso establece la cookie, que [curl] almacena en [cookies.txt]:
| $ curl -i -c cookies.txt --json @curl/login-admin.json http://localhost:8080/api/auth/login
HTTP/1.1 200 OK
Set-Cookie: rdvmedecins_jwt=eyJhbGciOiJIUzI1NiIs...; Max-Age=7200; Path=/api; Expires=Mon, 28 Sep 2026 12:49:12 GMT; HttpOnly; SameSite=Strict
Content-Type: application/json; charset=utf-8
Content-Length: 55
{"login": "admin", "name": "Administrator", "role": "ADMIN"}
|
Con esta cookie, el servidor sabe quiénes somos:
| $ curl -i -b cookies.txt http://localhost:8080/api/auth/me
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 55
{"login": "admin", "name": "Administrator", "role": "ADMIN"}
|
Un token falsificado (o vencido) produce una sesión vencida, y el servidor ordena al navegador eliminar la cookie:
| $ curl -i -b "rdvmedecins_jwt=abc.def.ghi" http://localhost:8080/api/auth/me
HTTP/1.1 401 Unauthorized
Set-Cookie: rdvmedecins_jwt=; Path=/api; Expires=Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 49
{"statusCode": 401, "key": "ERRORS.SESSION_EXPIRED"}
|
7.6.2. Médicos, clientes, calendario
La lista de médicos, vista por ADMIN (con los inicios de sesión):
| $ curl -i -b cookies.txt http://localhost:8080/api/doctors
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 282
[
{"id": 3, "version": 0, "title": "Melle", "firstName": "Sophie", "lastName": "DUPONT", "login": "dupont"},
{"id": 1, "version": 0, "title": "Mme", "firstName": "Marie", "lastName": "PELISSIER", "login": "pelissier"},
{"id": 2, "version": 0, "title": "Mr", "firstName": "Paul", "lastName": "TATOU", "login": "tatou"}
]
|
La agenda del Dr. PELISSIER para el 15 de enero de 2030:
| $ curl -s -b cookies.txt "http://localhost:8080/api/schedule?doctorId=1&day=2030-01-15"
{
"doctor": {"id": 1, "version": 0, "title": "Mme", "firstName": "Marie", "lastName": "PELISSIER"},
"day": "2030-01-15",
"slots": [
{"id": 1, "startHour": 8, "startMinute": 0, "endHour": 8, "endMinute": 20, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 2, "startHour": 8, "startMinute": 20, "endHour": 8, "endMinute": 40, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 3, "startHour": 8, "startMinute": 40, "endHour": 9, "endMinute": 0, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 4, "startHour": 9, "startMinute": 0, "endHour": 9, "endMinute": 20, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 5, "startHour": 9, "startMinute": 20, "endHour": 9, "endMinute": 40, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 6, "startHour": 9, "startMinute": 40, "endHour": 10, "endMinute": 0, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 7, "startHour": 10, "startMinute": 0, "endHour": 10, "endMinute": 20, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 8, "startHour": 10, "startMinute": 20, "endHour": 10, "endMinute": 40, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 9, "startHour": 10, "startMinute": 40, "endHour": 11, "endMinute": 0, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 10, "startHour": 11, "startMinute": 0, "endHour": 11, "endMinute": 20, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 11, "startHour": 11, "startMinute": 20, "endHour": 11, "endMinute": 40, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 12, "startHour": 11, "startMinute": 40, "endHour": 12, "endMinute": 0, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null}
],
"info": null
}
|
Una fecha que no existe:
| $ curl -i -b cookies.txt "http://localhost:8080/api/schedule?doctorId=1&day=2030-02-30"
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
Content-Length: 46
{"statusCode": 400, "key": "ERRORS.INVALID_DATE"}
|
7.6.3. Citas
ADMIN reserva el horario 3 para el paciente n.º 2 (Alice DURAND). El cuerpo de la solicitud:
| { "day": "2030-01-15", "slotId": 3, "clientId": 2 }
|
| $ curl -i -b cookies.txt --json @curl/appointment-admin.json http://localhost:8080/api/appointments
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Content-Length: 51
{"id": 2, "day": "2030-01-15", "slotId": 3, "clientId": 2}
|
El calendario ahora muestra esta cita, junto con el nombre del paciente y las instrucciones para cancelarla ([appointmentId]):
| $ curl -s -b cookies.txt "http://localhost:8080/api/schedule?doctorId=1&day=2030-01-15"
{
"doctor": {"id": 1, "version": 0, "title": "Mme", "firstName": "Marie", "lastName": "PELISSIER"},
"day": "2030-01-15",
"slots": [
{"id": 1, "startHour": 8, "startMinute": 0, "endHour": 8, "endMinute": 20, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 2, "startHour": 8, "startMinute": 20, "endHour": 8, "endMinute": 40, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 3, "startHour": 8, "startMinute": 40, "endHour": 9, "endMinute": 0, "free": false, "patient": {"title": "Mme", "firstName": "Alice", "lastName": "DURAND"}, "mine": false, "bookable": false, "appointmentId": 2},
{"id": 4, "startHour": 9, "startMinute": 0, "endHour": 9, "endMinute": 20, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 5, "startHour": 9, "startMinute": 20, "endHour": 9, "endMinute": 40, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 6, "startHour": 9, "startMinute": 40, "endHour": 10, "endMinute": 0, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 7, "startHour": 10, "startMinute": 0, "endHour": 10, "endMinute": 20, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 8, "startHour": 10, "startMinute": 20, "endHour": 10, "endMinute": 40, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 9, "startHour": 10, "startMinute": 40, "endHour": 11, "endMinute": 0, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 10, "startHour": 11, "startMinute": 0, "endHour": 11, "endMinute": 20, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 11, "startHour": 11, "startMinute": 20, "endHour": 11, "endMinute": 40, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 12, "startHour": 11, "startMinute": 40, "endHour": 12, "endMinute": 0, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null}
],
"info": null
}
|
Intente de nuevo: el paciente ya tiene una cita próxima. Una cita en el pasado también es rechazada:
| $ curl -i -b cookies.txt --json @curl/appointment-admin.json http://localhost:8080/api/appointments
HTTP/1.1 409 Conflict
Content-Type: application/json; charset=utf-8
Content-Length: 66
{"statusCode": 409, "key": "ERRORS.PATIENT_HAS_UPCOMING_APPOINTMENT"}
|
| $ curl -i -b cookies.txt --json @curl/appointment-past.json http://localhost:8080/api/appointments
HTTP/1.1 409 Conflict
Content-Type: application/json; charset=utf-8
Content-Length: 43
{"statusCode": 409, "key": "ERRORS.PAST_DATE"}
|
Un formulario HTML estándar (simulado aquí con [-d], que envía [application/x-www-form-urlencoded]) es rechazado:
| $ curl -i -b cookies.txt -d "day=2030-01-15&slotId=4&clientId=2" http://localhost:8080/api/appointments
HTTP/1.1 415 Unsupported Media Type
Content-Type: application/json; charset=utf-8
Content-Length: 47
{"statusCode": 415, "key": "ERRORS.JSON_REQUIRED"}
|
7.6.4. La perspectiva de un paciente
Se cierra la sesión y luego se inicia sesión como [martin]:
| $ curl -i -b cookies.txt -c cookies.txt --json @curl/empty.json http://localhost:8080/api/auth/logout
HTTP/1.1 200 OK
Set-Cookie: rdvmedecins_jwt=; Path=/api; Expires=Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 2
{}
|
| $ curl -s -c cookies-martin.txt --json @curl/login-martin.json http://localhost:8080/api/auth/login
{"login": "martin", "name": "Jean MARTIN", "role": "USER"}
|
La misma agenda, vista por un paciente: el horario 3 está ocupado (["free": false]), pero ["patient"] equivale a [null]: el apellido de Alice, DURAND, no fue enviado:
| $ curl -s -b cookies-martin.txt "http://localhost:8080/api/schedule?doctorId=1&day=2030-01-15"
{
"doctor": {"id": 1, "version": 0, "title": "Mme", "firstName": "Marie", "lastName": "PELISSIER"},
"day": "2030-01-15",
"slots": [
{"id": 1, "startHour": 8, "startMinute": 0, "endHour": 8, "endMinute": 20, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 2, "startHour": 8, "startMinute": 20, "endHour": 8, "endMinute": 40, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 3, "startHour": 8, "startMinute": 40, "endHour": 9, "endMinute": 0, "free": false, "patient": null, "mine": false, "bookable": false, "appointmentId": null},
{"id": 4, "startHour": 9, "startMinute": 0, "endHour": 9, "endMinute": 20, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 5, "startHour": 9, "startMinute": 20, "endHour": 9, "endMinute": 40, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 6, "startHour": 9, "startMinute": 40, "endHour": 10, "endMinute": 0, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 7, "startHour": 10, "startMinute": 0, "endHour": 10, "endMinute": 20, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 8, "startHour": 10, "startMinute": 20, "endHour": 10, "endMinute": 40, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 9, "startHour": 10, "startMinute": 40, "endHour": 11, "endMinute": 0, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 10, "startHour": 11, "startMinute": 0, "endHour": 11, "endMinute": 20, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 11, "startHour": 11, "startMinute": 20, "endHour": 11, "endMinute": 40, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 12, "startHour": 11, "startMinute": 40, "endHour": 12, "endMinute": 0, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null}
],
"info": null
}
|
Un paciente no tiene acceso a la lista de clientes:
| $ curl -i -b cookies-martin.txt http://localhost:8080/api/clients
HTTP/1.1 403 Forbidden
Content-Type: application/json; charset=utf-8
Content-Length: 43
{"statusCode": 403, "key": "ERRORS.FORBIDDEN"}
|
Reserva para sí mismo (el cuerpo no contiene [clientId]), una vez, no dos:
| { "day": "2030-01-15", "slotId": 5 }
|
| $ curl -i -b cookies-martin.txt --json @curl/appointment-martin.json http://localhost:8080/api/appointments
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Content-Length: 51
{"id": 3, "day": "2030-01-15", "slotId": 5, "clientId": 1}
|
| $ curl -i -b cookies-martin.txt --json @curl/appointment-martin-2.json http://localhost:8080/api/appointments
HTTP/1.1 409 Conflict
Content-Type: application/json; charset=utf-8
Content-Length: 55
{"statusCode": 409, "key": "SCHEDULE.ALREADY_BOOKED_INFO"}
|
Su área:
| $ curl -s -b cookies-martin.txt http://localhost:8080/api/my-area
{
"patient": {"title": "Mr", "firstName": "Jean", "lastName": "MARTIN"},
"appointments": [
{
"id": 3,
"day": "2030-01-15",
"slot": {"id": 5, "startHour": 9, "startMinute": 20, "endHour": 9, "endMinute": 40},
"doctor": {"id": 1, "version": 0, "title": "Mme", "firstName": "Marie", "lastName": "PELISSIER"}
}
]
}
|
No puede cancelar la cita de otro paciente. El servidor responde “no encontrado”, igual que ante una cita que no existe: no revela nada sobre las citas de otros pacientes:
| $ curl -i -b cookies-martin.txt -X DELETE http://localhost:8080/api/appointments/2
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
Content-Length: 55
{"statusCode": 404, "key": "ERRORS.APPOINTMENT_NOT_FOUND"}
|
La suya, sí:
| $ curl -i -b cookies-martin.txt -X DELETE http://localhost:8080/api/appointments/3
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 2
{}
|
7.6.5. La perspectiva de un médico
Sin [doctorId], un médico con sesión iniciada recibe SU PROPIA agenda, con todos los nombres:
| $ curl -s -b cookies-pelissier.txt "http://localhost:8080/api/schedule?day=2030-01-15"
{
"doctor": {"id": 1, "version": 0, "title": "Mme", "firstName": "Marie", "lastName": "PELISSIER"},
"day": "2030-01-15",
"slots": [
{"id": 1, "startHour": 8, "startMinute": 0, "endHour": 8, "endMinute": 20, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 2, "startHour": 8, "startMinute": 20, "endHour": 8, "endMinute": 40, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 3, "startHour": 8, "startMinute": 40, "endHour": 9, "endMinute": 0, "free": false, "patient": {"title": "Mme", "firstName": "Alice", "lastName": "DURAND"}, "mine": false, "bookable": false, "appointmentId": 2},
{"id": 4, "startHour": 9, "startMinute": 0, "endHour": 9, "endMinute": 20, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 5, "startHour": 9, "startMinute": 20, "endHour": 9, "endMinute": 40, "free": false, "patient": {"title": "Mr", "firstName": "Jean", "lastName": "MARTIN"}, "mine": false, "bookable": false, "appointmentId": 3},
{"id": 6, "startHour": 9, "startMinute": 40, "endHour": 10, "endMinute": 0, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 7, "startHour": 10, "startMinute": 0, "endHour": 10, "endMinute": 20, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 8, "startHour": 10, "startMinute": 20, "endHour": 10, "endMinute": 40, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 9, "startHour": 10, "startMinute": 40, "endHour": 11, "endMinute": 0, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 10, "startHour": 11, "startMinute": 0, "endHour": 11, "endMinute": 20, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 11, "startHour": 11, "startMinute": 20, "endHour": 11, "endMinute": 40, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null},
{"id": 12, "startHour": 11, "startMinute": 40, "endHour": 12, "endMinute": 0, "free": true, "patient": null, "mine": false, "bookable": true, "appointmentId": null}
],
"info": null
}
|
No gestiona médicos:
| $ curl -i -b cookies-pelissier.txt --json @curl/doctor-add.json http://localhost:8080/api/doctors
HTTP/1.1 403 Forbidden
Content-Type: application/json; charset=utf-8
Content-Length: 43
{"statusCode": 403, "key": "ERRORS.FORBIDDEN"}
|
7.6.6. Gestión de médicos y clientes (ADMIN)
Una alta. Si falta el nombre de usuario, por defecto es el nombre en minúsculas; la contraseña es el nombre de usuario:
| { "title": "Mme", "firstName": "Claire", "lastName": "LEROY" }
|
| $ curl -i -b cookies.txt --json @curl/doctor-add.json http://localhost:8080/api/doctors
HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Content-Length: 90
{"id": 4, "version": 1, "title": "Mme", "firstName": "Claire", "lastName": "LEROY", "login": "leroy"}
|
Cuerpo no válido: la respuesta enumera el error de cada campo:
| { "title": "Dr", "firstName": "", "lastName": "A-LAST-NAME-FAR-TOO-LONG-FOR-THE-DB", "login": "Claire L" }
|
| $ curl -i -b cookies.txt --json @curl/doctor-invalid.json http://localhost:8080/api/doctors
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
Content-Length: 218
{
"statusCode": 400,
"key": "ERRORS.INVALID_FORM",
"params": {"min": "6"},
"fields": {"login": "ERRORS.INVALID_LOGIN", "title": "ERRORS.INVALID_TITLE", "firstName": "ERRORS.FIRSTNAME_REQUIRED", "lastName": "ERRORS.LASTNAME_TOO_LONG"}
}
|
Un homónimo: se señalan los dos campos afectados:
| $ curl -i -b cookies.txt --json @curl/doctor-duplicate.json http://localhost:8080/api/doctors
HTTP/1.1 409 Conflict
Content-Type: application/json; charset=utf-8
Content-Length: 151
{"statusCode": 409, "key": "ERRORS.DOCTOR_ALREADY_EXISTS", "fields": {"firstName": "ERRORS.DOCTOR_ALREADY_EXISTS", "lastName": "ERRORS.DOCTOR_ALREADY_EXISTS"}}
|
Una modificación. La [version] es la leída en la ficha de datos (aquí, 1):
| { "title": "Mme", "firstName": "Claire", "lastName": "LEROY-MARTIN", "version": 1 }
|
| $ curl -i -b cookies.txt -X PUT --json @curl/doctor-edit.json http://localhost:8080/api/doctors/4
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 97
{"id": 4, "version": 2, "title": "Mme", "firstName": "Claire", "lastName": "LEROY-MARTIN", "login": "leroy"}
|
El registro está ahora en la versión 2. Volver a enviar la misma modificación (con la versión 1) sobrescribiría un registro que fue modificado entretanto por otra persona: el bloqueo optimista lo impide:
| $ curl -i -b cookies.txt -X PUT --json @curl/doctor-edit.json http://localhost:8080/api/doctors/4
HTTP/1.1 409 Conflict
Content-Type: application/json; charset=utf-8
Content-Length: 51
{"statusCode": 409, "key": "ERRORS.CONCURRENT_UPDATE"}
|
Un médico con citas no puede eliminarse; los demás sí:
| $ curl -i -b cookies.txt -X DELETE http://localhost:8080/api/doctors/1
HTTP/1.1 409 Conflict
Content-Type: application/json; charset=utf-8
Content-Length: 57
{"statusCode": 409, "key": "ERRORS.DOCTOR_HAS_APPOINTMENTS"}
|
| $ curl -i -b cookies.txt -X DELETE http://localhost:8080/api/doctors/4
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 2
{}
|
7.6.7. Creación de una cuenta
Sin un pase, es imposible:
| $ curl -i --json @curl/registration.json http://localhost:8080/api/register
HTTP/1.1 403 Forbidden
Content-Type: application/json; charset=utf-8
Content-Length: 56
{"statusCode": 403, "key": "ERRORS.CAPTCHA_BEFORE_ACCOUNT"}
|
Primero se resuelve un CAPTCHA; el servidor emite un token, válido por 15 minutos, en una cookie:
| $ curl -i -c cookies-registration.txt --json @curl/captcha-test.json http://localhost:8080/api/register/access
HTTP/1.1 200 OK
Set-Cookie: rdvmedecins_registration=06be5557-401a-4bd4-ada2-277ca48fc74d; Max-Age=900; Path=/api/register; Expires=Mon, 28 Sep 2026 11:04:12 GMT; HttpOnly; SameSite=Strict
Content-Type: application/json; charset=utf-8
Content-Length: 2
{}
|
| $ curl -s -b cookies-registration.txt http://localhost:8080/api/register/access
{"valid": true}
|
La confirmación de la contraseña debe ser idéntica:
| $ curl -i -b cookies-registration.txt --json @curl/registration-confirmation.json http://localhost:8080/api/register
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
Content-Length: 98
{"statusCode": 400, "key": "ERRORS.INVALID_FORM", "fields": {"confirmation": "ERRORS.PASSWORDS_DIFFER"}}
|
| { "title": "Mme", "firstName": "Julie", "lastName": "BERNARD", "login": "jbernard", "password": "secret1", "confirmation": "secret1" }
|
| $ curl -i -b cookies-registration.txt -c cookies-registration.txt --json @curl/registration.json http://localhost:8080/api/register
HTTP/1.1 201 Created
Set-Cookie: rdvmedecins_registration=; Path=/api/register; Expires=Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 20
{"login": "jbernard"}
|
El pase ya fue utilizado: no puede usarse para crear una segunda cuenta:
| $ curl -i -b cookies-registration.txt --json @curl/registration.json http://localhost:8080/api/register
HTTP/1.1 403 Forbidden
Content-Type: application/json; charset=utf-8
Content-Length: 56
{"statusCode": 403, "key": "ERRORS.CAPTCHA_BEFORE_ACCOUNT"}
|
7.6.8. Gestión de la cuenta
La nueva paciente inicia sesión y lee su registro:
| $ curl -s -b cookies-jbernard.txt http://localhost:8080/api/my-account
{"title": "Mme", "firstName": "Julie", "lastName": "BERNARD", "login": "jbernard", "version": 1}
|
Para hacer una modificación se requiere la contraseña actual. El servidor emite un nuevo token, que contiene el nuevo nombre:
| { "title": "Mme", "firstName": "Julie", "lastName": "BERNARD-DUVAL", "login": "jbernard", "currentPassword": "secret1", "version": 1 }
|
| $ curl -i -b cookies-jbernard.txt -c cookies-jbernard.txt -X PUT --json @curl/my-account.json http://localhost:8080/api/my-account
HTTP/1.1 200 OK
Set-Cookie: rdvmedecins_jwt=eyJhbGciOiJIUzI1NiIs...; Max-Age=7200; Path=/api; Expires=Mon, 28 Sep 2026 12:49:13 GMT; HttpOnly; SameSite=Strict
Content-Type: application/json; charset=utf-8
Content-Length: 63
{"login": "jbernard", "name": "Julie BERNARD-DUVAL", "role": "USER"}
|
Eliminar la cuenta también elimina la cookie:
| $ curl -i -b cookies-jbernard.txt -c cookies-jbernard.txt -X DELETE --json @curl/my-account-delete.json http://localhost:8080/api/my-account
HTTP/1.1 200 OK
Set-Cookie: rdvmedecins_jwt=; Path=/api; Expires=Thu, 01 Jan 1970 00:00:00 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 2
{}
|
| $ curl -i -b cookies-jbernard.txt http://localhost:8080/api/auth/me
HTTP/1.1 401 Unauthorized
Content-Type: application/json; charset=utf-8
Content-Length: 47
{"statusCode": 401, "key": "ERRORS.AUTH_REQUIRED"}
|
7.6.9. Algunos errores
Una ruta desconocida, un cuerpo que no es un JSON válido:
| $ curl -i -b cookies-martin.txt http://localhost:8080/api/does-not-exist
HTTP/1.1 404 Not Found
Content-Type: application/json; charset=utf-8
Content-Length: 43
{"statusCode": 404, "key": "ERRORS.NOT_FOUND"}
|
| $ curl -i -b cookies.txt -H "Content-Type: application/json" -d "{not json" http://localhost:8080/api/appointments
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
Content-Length: 45
{"statusCode": 400, "key": "ERRORS.BAD_REQUEST"}
|
Ya sabemos todo lo que necesitamos del servidor para escribir nuestro cliente.