8. El servidor RdvMedecins, una caja negra
Los ejemplos 22 a 25, seguidos del caso de estudio, interactúan con un servidor: el servidor JSON de la aplicación [RdvMedecins]. Es el servidor [NestJS] de los cursos [React], [Vue.js] y [Angular]: el servidor del curso [NestJS], cuyos controladores ya no generan páginas HTML sino que producen respuestas JSON. Los lectores de estas lecciones ya conocen este capítulo, que se reproduce aquí casi sin cambios; solo necesitan centrarse en la sección sobre autenticación, que explica qué cambia para una aplicación móvil.
En este curso, este servidor es una caja negra: no necesita 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. 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].
8.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; gestionar 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; gestionar sus cuentas. En una agenda, no pueden ver los nombres de los demás pacientes |
Las cuentas de demostración usan su nombre de usuario como contraseña. El servidor verifica las reglas de gestión, sea cual sea el cliente:
- no se permiten citas en el pasado;
- solo una cita próxima 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 alguien más modificó entretanto no se puede sobrescribir (bloqueo optimista);
- a un paciente nunca se le asigna el nombre de otro paciente.
8.2. Instalación
Se necesitan [Node.js] y un servidor [MySQL] (o [MariaDB]): su instalación se describe en el apéndice.
- 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 iniciales.
- Bibliotecas. En una ventana de consola abierta en la carpeta [rdvmedecins-nestjs-json]:
- 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 incluirse en el control de versiones (contraseñas).
# -----------------------------------------------------------------------
# puerto de escucha del servidor JSON
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 incluida en el control de versiones).
JWT_SECRET=change-me-to-a-long-random-string
# validez de un token JWT, en segundos (7200 s = 2 h). La cookie
# que lleva el token tiene la misma duración.
JWT_EXPIRES_IN_SECONDS=7200
# establecer 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
# -----------------------------------------------------------------------
# inicio de sesión: 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, sumando todos los logins)
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 se
# acepta como respuesta a CUALQUIER CAPTCHA. Útil 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 web compilado, servida por este servidor (por defecto: client/)
# CLIENT_DIR=client
# establecer 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 son adecuados;
- línea 25: la clave secreta que firma los tokens de autenticación;
- líneas 38–45: medidas antibots (bloqueo tras varios intentos fallidos de inicio de sesión, número de cuentas creadas por hora);
- Línea 51: modo de prueba del CAPTCHA. La página de inicio de sesión exige 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] de este capítulo, escriba [CAPTCHA_TEST=test]. Las pruebas automatizadas que generaron las capturas de pantalla de este curso también usan este valor. Déjela VACÍA en producción;
- líneas 57–59: dos ajustes para producción (véase el capítulo “Despliegue”).
- 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 es inaccesible (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 4xx o 5xx y, en el cuerpo, un objeto que SIEMPRE tiene 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 21);
- [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 es JSON | [ERRORS.JSON_REQUIRED] |
429 | Demasiados intentos | [ERRORS.TOO_MANY_ATTEMPTS], [ERRORS.TOO_MANY_ACCOUNTS] (+ params.minutes) |
500 | error del servidor | [ERRORS.SERVER_ERROR] |
8.4. Autenticación
El cliente se autentica mediante [POST /api/auth/login], con un nombre de usuario, una contraseña y la respuesta al CAPTCHA. A cambio, el servidor envía, en el encabezado [Set-Cookie] de su respuesta, una cookie que contiene un token JWT firmado:
| Set-Cookie: rdvmedecins_jwt=eyJhbGciOiJIUzI1NiIs...; Max-Age=7200; Path=/api; HttpOnly; SameSite=Strict
|
A partir de ese momento, el cliente debe incluir esta cookie, en el encabezado [Cookie], en cada solicitud a [/api]: así sabe el servidor quién hace la solicitud.
Este servidor se diseñó para clientes web, y sus decisiones de diseño responden a los riesgos propios de los navegadores web:
- [HttpOnly]: el código de la página ([JavaScript]) 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]: la cookie solo se incluye en las solicitudes a la API;
- [SameSite=Strict]: el navegador adjunta la cookie únicamente a 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 (el llamado ataque CSRF);
- [Max-Age=7200]: vence después de dos horas, al mismo tiempo que el token.
Una segunda protección contra los ataques CSRF: el servidor rechaza (415) cualquier solicitud POST cuyo cuerpo no esté en JSON. Un formulario HTML comprometido en otro sitio no puede enviar JSON.
¿Y una aplicación móvil? No hay navegador: nadie guarda la cookie ni la reenvía por sí solo. La aplicación asumirá ese papel leyendo el encabezado [Set-Cookie] de las respuestas y escribiendo el encabezado [Cookie] en las solicitudes (ejemplo 23). Los atributos [HttpOnly] y [SameSite] solo se aplican a los navegadores: no tienen efecto en la aplicación, como tampoco en [curl]. La misma aplicación [Flutter], compilada para la web, funcionará en cambio como lo hacen los navegadores: el navegador gestiona la cookie, siempre que la aplicación y la API compartan el mismo origen (véase el ejemplo 22 y el capítulo “Despliegue”).
8.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 | un registro |
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]: ¿está disponible el horario ese día?
- [patient]: el paciente de la cita. Para un paciente con sesión iniciada, es igual a [null], salvo en SU PROPIA cita: los nombres de los demás 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 próximas)?
- [appointmentId]: se completa si el usuario puede cancelar esta cita.
El servidor DECIDE; el cliente muestra. E incluso si un cliente hiciera trampa (mostrando un botón “Reservar” cuando no corresponde), el servidor volvería a verificar todo en el momento de la reserva.
8.6. Consulta de la API con curl
La carpeta [curl] del servidor contiene los cuerpos de las solicitudes JSON de este capítulo, con un archivo por solicitud. Por ejemplo, [curl/login-admin.json]:
| { "login": "admin", "password": "admin", "captchaId": "-", "captcha": "test" }
|
Los comandos se escriben 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 reenvía. Así [curl] “mantiene la sesión iniciada” de un comando al siguiente, igual que lo haría un navegador.
En [PowerShell], debe escribir [curl.exe] y no [curl] (que allí designa un comando distinto). Las respuestas JSON, algo extensas, se formatearon para este documento, y se eliminaron los encabezados [Date], [ETag], [Connection] y [Keep-Alive] .
8.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: 11428
{"id": "968678a8-25f0-4892-9fc4-bd93533dab33", "svg": "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"150..."}
|
Sin 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] guarda 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"}
|
8.6.2. Médicos, clientes, agenda
La lista de médicos, vista por ADMIN (con nombres de usuario):
| $ 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"}
|
8.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}
|
La agenda 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
}
|
Intentemos de nuevo: el paciente ya tiene una cita próxima. También se rechaza una cita en el pasado:
| $ 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"}
|
8.6.4. La perspectiva de un paciente
Cierre la sesión y luego inicie 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 se envió:
| $ 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"}
|
Hace una 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 lo haría con 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
{}
|
8.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"}
|
8.6.6. Gestión de médicos y clientes (ADMIN)
Una adición. Si falta el nombre de usuario, se usa por defecto el apellido 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 que se leyó del registro (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 el mismo cambio (con la versión 1) sobrescribiría un registro que alguien más modificó entretanto: 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 se puede eliminar; 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
{}
|
8.6.7. Creación de una cuenta
Sin 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=60f5fa35-f939-4c87-b5a2-7c2f38054cc3; 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 se usó: no se puede utilizar 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"}
|
8.6.8. Gestión de su cuenta
La nueva paciente inicia sesión y lee el registro de su cuenta:
| $ 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 necesita 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"}
|
8.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"}
|
Ahora sabemos todo lo que necesitamos saber sobre el servidor para escribir nuestro cliente.