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], [Angular] y [Flutter]: el servidor del curso [NestJS], cuyos controladores ya no generan páginas HTML sino que producen respuestas JSON. Los lectores de esos cursos ya conocen este capítulo, que se reproduce aquí casi sin cambios; pueden centrarse únicamente 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. 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 mediante [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] | Médicos ([pelissier], [tatou], [dupont]) | Programar y cancelar citas de todos los pacientes; ver todos los nombres en las agendas |
[USER] | 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 otros pacientes |
Las cuentas de demostración usan su nombre de usuario como contraseña. Las reglas de gestión las verifica el servidor, sin importar el cliente:
- no hay citas en el pasado;
- solo una cita futura por paciente;
- un horario solo se puede reservar una vez al 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;
- no se puede eliminar a un médico con citas programadas;
- Un registro que fue modificado mientras tanto por otra persona no se puede sobrescribir (bloqueo optimista);
- Nunca se asigna a un paciente el nombre de otro paciente.
8.2. Instalación
Necesitará [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 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 subirse al repositorio (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 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
# póngalo en true en producción (sitio servido por HTTPS): la cookie
# de autenticación entonces nunca se enviará 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 se bloquee...
LOGIN_MAX_FAILURES=5
# ... durante esta duración (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 clientes: 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. 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 web compilado, servido por este servidor (por defecto: client/)
# CLIENT_DIR=client
# póngalo en true si el servidor está detrás de un proxy (nginx...)
TRUST_PROXY=false
|
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, un error que SIEMPRE sigue 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 mediante sus diccionarios (consulte 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 | Infracció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 una 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 entonces, el cliente debe presentar esta cookie, en el encabezado [Cookie], con cada solicitud a [/api]: así es como el servidor sabe quién realiza la solicitud.
Este servidor fue diseñado para clientes web, y sus decisiones de diseño responden a los riesgos propios de los navegadores web:
- [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í solo 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 (un ataque conocido como CSRF);
- [Max-Age=7200]: vence a las dos horas, en el mismo momento en que vence el token.
Una segunda salvaguarda 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 almacena la cookie ni la devuelve por sí solo. La aplicación asumirá este papel: la biblioteca [OkHttp], a la que se confía un “almacén de cookies” (un [CookieJar]), lee el encabezado [Set-Cookie] de las respuestas y escribe el encabezado [Cookie] en las solicitudes (ejemplo 23). Los atributos [HttpOnly] y [SameSite] solo se aplican a los navegadores: no tienen efecto sobre ella, así como no tienen efecto sobre [curl].
8.5. 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] | 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] excepto en SUS PROPIAS citas: 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, para un paciente, sin citas futuras)?
- [appointmentId]: se completa si el usuario puede cancelar esta cita.
El servidor DECIDE; el cliente muestra. Y aunque un cliente hiciera trampa (mostrando un botón “Reservar” cuando no debería), el servidor volvería a verificarlo todo en el momento de la reserva.
8.6. Consulta de la API con curl
El directorio del servidor [curl] contiene los cuerpos JSON de las solicitudes 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 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 al siguiente, igual que lo haría un navegador.
En [PowerShell], debe ingresar [curl.exe] y no [curl] (que allí remite a otro comando). Las respuestas algo extensas de JSON se han formateado para este documento, y los encabezados [Date], [ETag], [Connection], y [Keep-Alive] se han eliminado.
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: 11081
{"id": "e347ae38-79ff-4dea-8d6e-19610a7d69a7", "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] 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 que elimine 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 los 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"}
]
|
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
}
|
Inténtelo de nuevo: el paciente ya tiene una cita futura. 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í mediante [-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
Cierra la sesión y luego 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 nombre 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"}
|
Reserva el horario para sí mismo (el cuerpo no contiene [clientId]), solo 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)
Un alta. Si falta el nombre de usuario, se usa por defecto 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 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 ahora está en la versión 2. Volver a enviar el mismo cambio (con la versión 1) sobrescribiría un registro que entretanto fue modificado por otra persona: esto es lo que impide el bloqueo optimista:
| $ 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"}
|
No se puede eliminar a un médico con citas; a 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 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=f71fa11a-e899-4d06-a35c-42d203dce17d; Max-Age=900; Path=/api/register; Expires=Mon, 28 Sep 2026 11:04:14 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 se puede usar 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 consulta su historia clínica:
| $ curl -s -b cookies-jbernard.txt http://localhost:8080/api/my-account
{"title": "Mme", "firstName": "Julie", "lastName": "BERNARD", "login": "jbernard", "version": 1}
|
Cualquier cambio 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:15 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.