Skip to content

7. 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 la lección anterior, cuyos controladores ya no generan páginas HTML sino 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; 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 la 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 admiten citas en el pasado;
  • solo una cita futura por paciente;
  • una franja horaria 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;
  • no se puede eliminar a un médico que tiene citas;
  • 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ú File / Run a SQL file); en la línea de comandos:

mysql -u root -p < database/dbrdvmedecins2.sql

El script siempre parte de una base de datos vacía: se puede volver a ejecutar para restaurar los datos iniciales.

2. Bibliotecas. En una ventana de consola abierta en la carpeta [rdvmedecins-nestjs-json]:

npm install

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 computadora.
# El archivo [.env] nunca debe compartirse ni subirse al repositorio (contraseñas).
# -----------------------------------------------------------------------

# puerto de escucha del servidor JSON (el cliente Angular lo alcanza a través del proxy de ng serve)
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 tokens JWT - DEBE cambiarse
# en producción (una cadena larga y aleatoria, 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 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
# -----------------------------------------------------------------------
# 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 salón de clases, 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. Útil para consultar
# la API con curl (no se puede "leer" la imagen en una consola).
# Dejar VACÍA en producción.
CAPTCHA_TEST=

# -----------------------------------------------------------------------
# producción
# -----------------------------------------------------------------------
# carpeta del cliente Angular 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 sirven;
  • línea 25: la clave secreta que firma los tokens de autenticación;
  • líneas 38–45: protecciones contra bots (bloqueo tras varios intentos fallidos de inicio de sesión, número de cuentas creadas por hora);
  • línea 51: el modo de prueba del 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] de 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 “Deployment”).

4. Inicio.

npm run start:dev

La consola muestra (extracto):

1
2
3
4
5
6
7
8
[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.

7.3. Formato de las respuestas

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:

1
2
3
4
5
6
{
  "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): 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 invá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 inválido o caducado), [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 cuyo cuerpo 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]

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í solo 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 (un ataque llamado CSRF);
  • [Max-Age=7200]: caduca después de dos horas, al mismo tiempo que el token.

A partir de entonces, el navegador envía automáticamente esta cookie con cada solicitud a [/api]. Por lo tanto, el cliente [Angular] no necesita hacer nada 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 del servidor de desarrollo de [Angular] (véase el ejemplo 22), y del propio servidor en producción (véase el capítulo “Deployment”).

Una segunda protección contra los ataques CSRF: el servidor rechaza (415) cualquier solicitud POST cuyo cuerpo no sea 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
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 una franja horaria Y lo que el usuario conectado está autorizado a hacer con ella:

1
2
3
4
{ "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 la franja horaria ese día?
  • [patient]: el paciente de la cita. Para un paciente conectado, es igual a [null], salvo en el caso de SUS PROPIAS citas: los nombres de los demás pacientes nunca se envían;
  • [mine]: es la cita del paciente conectado;
  • [bookable]: ¿puede el usuario reservar esta franja horaria (disponible, no pasada y, para un paciente, sin citas futuras)?
  • [appointmentId]: se define si el usuario puede cancelar esta cita.

El servidor DECIDE; el cliente muestra. E incluso si un cliente hiciera trampa (mostrando un botón “Book” cuando no debería), el servidor volvería a verificarlo todo en el momento de la reserva.

7.6. Consultar 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 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” de un comando al siguiente, igual que lo haría un navegador.

En [PowerShell], debe ingresar [curl.exe] y no [curl] (que allí designa otro comando). Las respuestas JSON, algo extensas, se han formateado para este documento, y los encabezados [Date], [ETag], [Connection], y [Keep-Alive] se han eliminado.

7.6.1. Inicio de sesión

Primero, el CAPTCHA (la imagen está recortada):

1
2
3
4
5
6
7
$ 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: 11304

{"id": "e33886ae-1a8b-4302-8cbc-cd7015e82f1f", "svg": "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"150..."}

Sin token, una URL protegida devuelve una respuesta 401:

1
2
3
4
5
6
$ 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:

1
2
3
4
5
6
$ 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"}}
1
2
3
4
5
6
$ 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]:

1
2
3
4
5
6
7
$ 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:

1
2
3
4
5
6
$ 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 caducado) produce una sesión expirada, y el servidor indica al navegador que elimine la cookie:

1
2
3
4
5
6
7
$ 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, 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"}
]

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:

1
2
3
4
5
6
$ 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 la franja 3 para el paciente n.º 2 (Alice DURAND). El cuerpo de la solicitud:

{ "day": "2030-01-15", "slotId": 3, "clientId": 2 }
1
2
3
4
5
6
$ 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 muestra ahora esta cita, junto con el nombre del paciente e 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:

1
2
3
4
5
6
$ 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"}
1
2
3
4
5
6
$ 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:

1
2
3
4
5
6
$ 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

Cierre sesión y luego inicie sesión como [martin]:

1
2
3
4
5
6
7
$ 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: la franja 3 está ocupada (["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:

1
2
3
4
5
6
$ 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 }
1
2
3
4
5
6
$ 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}
1
2
3
4
5
6
$ 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 para una cita que no existe: no revela nada sobre las citas de otros pacientes:

1
2
3
4
5
6
$ 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í:

1
2
3
4
5
6
$ 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 conectado 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:

1
2
3
4
5
6
$ 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, el valor predeterminado es el nombre en minúsculas; la contraseña es el nombre de usuario:

{ "title": "Mme", "firstName": "Claire", "lastName": "LEROY" }
1
2
3
4
5
6
$ 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 invá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:

1
2
3
4
5
6
$ 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 }
1
2
3
4
5
6
$ 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 ha sido modificado desde entonces por otra persona: el bloqueo optimista lo impide:

1
2
3
4
5
6
$ 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í:

1
2
3
4
5
6
$ 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"}
1
2
3
4
5
6
$ 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 pase, es imposible:

1
2
3
4
5
6
$ 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 durante 15 minutos, en una cookie:

1
2
3
4
5
6
7
$ 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=73a037d1-78f2-4e8e-a3a5-b6660a4f7fd5; 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:

1
2
3
4
5
6
$ 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" }
1
2
3
4
5
6
7
$ 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 utilizó: no se puede usar para crear una segunda cuenta:

1
2
3
4
5
6
$ 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 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}

Hacer un 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 }
1
2
3
4
5
6
7
$ 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:

1
2
3
4
5
6
7
$ 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

{}
1
2
3
4
5
6
$ 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:

1
2
3
4
5
6
$ 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"}
1
2
3
4
5
6
$ 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 saber sobre el servidor para escribir nuestro cliente.