22. Autenticación

Versión para imprimir.

A. Introducción

B. Diagrama entidad relación

Diagrama entidad relación

C. Diagrama relacional

Diagrama relacional

D. Diagrama de despliegue

Diagrama de despliegue

E. Hazlo funcionar (con videos)

  1. Prueba el ejemplo en https://srvaut.rf.gd/.

  2. Descarga el archivo /src/srvaut.zip y descompáctalo.

  3. Crea una cuenta de email pqra ti, por ejemplo, pepito@google.com. Si ya tienes un email, omite este paso.

  4. Crea una cuenta de GitHub usando el email anterior y selecciona el nombre de usuario unsando la parte inicial del correo electrónico, por ejemplo pepito. Si ya tienes una cuenta, omite este paso.

  5. Crea un repositorio nuevo. En el nombre del repositorio debes poner el nombre de tu sitio; por ejemplo devuelvejson

  6. Importa el proyecto de GitHub a Visual Studio Code

  7. Edita los archivos que desees.

  8. Prueba tu sitio localmente.

  9. Necesitas un hosting. En este ejemplo se muestra como usar el hosting. https://infinityfree.com/ Si no lo has usado, lo primero que tienes que hacer es entrar a registrar tu email con el botón Registrar. Si ya tienes tu email registrado, omite este paso.

  10. Crea una cuenta. Si ya tienes cuenta, entra a ella y crea un nuevo domino. En este ejemplo no se crean los archivos directamente en el hosting.

  11. Sube tus archivos al hosting usando ftp.

  12. Sube tus archivos a GitHub. En este ejemplo no hay archivo sw.js ni necesitas esperar 11 o más minutos.

F. Hazlo funcionar (texto)

  1. Prueba el ejemplo en https://srvaut.rf.gd/.

  2. Descarga el archivo /src/srvaut.zip y descompáctalo.

  3. Crea tu proyecto en GitHub:

    1. Crea una cuenta de email para tí, por ejemplo, pepito@google.com. Si ya tienes un email, omite este paso.

    2. Crea una cuenta de GitHub usando el email anterior y selecciona el nombre de usuario unsando la parte inicial del correo electrónico, por ejemplo pepito. Si ya tienes una cuenta, omite este paso.

    3. Crea un repositorio nuevo. En la página principal de GitHub cliquea 📘 New.

    4. En la página Create a new repository introduce los siguientes datos:

      • Proporciona el nombre de tu repositorio debajo de donde dice Repository name *.

      • Mantén la selección Public para que otros usuarios puedan ver tu proyecto.

      • Verifica la casilla Add a README file. En este archivo se muestra información sobre tu proyecto.

      • Cliquea License: None. y selecciona la licencia que consideres más adecuada para tu proyecto.

      • Cliquea Create repository.

  4. Importa el proyecto en GitHub:

    1. En la página principal de tu proyecto en GitHub, en la pestaña < > Code, cliquea < > Code y en la sección Branches y copia la dirección que está en HTTPS, debajo de Clone.

    2. En Visual Studio Code, usa el botón de la izquierda para Source Control.

      Imagen de Source Control
    3. Cliquea el botón Clone Repository.

    4. Pega la url que copiaste anteriormente hasta arriba, donde dice algo como Provide repository URL y presiona la teclea Intro.

    5. Selecciona la carpeta donde se guardará la carpeta del proyecto.

    6. Abre la carpeta del proyecto importado.

    7. Añade el contenido de la carpeta descompactada que contiene el código del ejemplo.

  5. Edita los archivos que desees.

  6. Haz clic derecho en index.html, selecciona PHP Server: serve project y se abre el navegador para que puedas probar localmente el ejemplo.

  7. Para depurar paso a paso haz lo siguiente:

    1. En el navegador, haz clic derecho en la página que deseas depurar y selecciona inspeccionar.

    2. Recarga la página, de preferencia haciendo clic derecho en el ícono de volver a cargar la página Ïmagen del ícono de recarga y seleccionando vaciar caché y volver a cargar de manera forzada (o algo parecido). Si no aparece un menú emergente, simplemente cliquea volver a cargar la página Ïmagen del ícono de recarga. Revisa que no aparezca ningún error ni en la pestañas Consola, ni en Red.

    3. Selecciona la pestaña Fuentes (o Sources si tu navegador está en Inglés).

    4. Selecciona el archivo donde vas a empezar a depurar.

    5. Haz clic en el número de la línea donde vas a empezar a depurar.

    6. En Visual Studio Code, abre el archivo de PHP donde vas a empezar a depurar.

    7. Haz clic en Run and Debug .

    8. Si no está configurada la depuración, haz clic en create a launch json file.

    9. Haz clic en la flechita RUN AND DEBUG, al lado de la cual debe decir Listen for Xdebug .

    10. Aparece un cuadro con los controles de depuración

    11. Selecciona otra vez el archivo de PHP y haz clic en el número de la línea donde vas a empezar a depurar.

    12. Regresa al navegador, recarga la página y empieza a usarla.

    13. Si se ejecuta alguna de las líneas de código seleccionadas, aparece resaltada en la pestaña de fuentes. Usa los controles de depuración para avanzar, como se muestra en este video.

  8. Sube el proyecto al hosting que elijas.

    1. Crea una nueva carpeta para crear un nuevo proyecto que estará conectado directamente al servidor web por ftp.

    2. Abre la nueva carpeta con Visual Studio Code.

    3. Tecle al mismo Mayúsculas+Control+P y selecciona SFTP: Config. Aparece un archivo de configuración de FTP. Llena los datos con la configuración de FTP de tu servidor, excepto la contraseña.

    4. Cliquea el botón de SFTP y luego haz clic en la URL de tu servidos. En la barra superior te pide la contraseña y ENTER.

    5. Pásate a la parte de archivos y coloca tus archivos.

    6. Cliquea con el botón derecho en la sección de archivos y selecciona Sync: Local -> Remote.

  9. Abre un navegador y prueba el proyecto en tu hosting.

  10. En el hosting InfinityFree, la primera vez que corres la página, puede marcar un mensaje de error, pero al recargar funciona correctamente. Puedes evitar este problema usando un dominio propio.

  11. Para subir el código a GitHub, en la sección de SOURCE CONTROL, en Message introduce un mensaje sobre los cambios que hiciste, por ejemplo index.html corregido, selecciona v y luego Commit & Push.

    Imagen de Commit & Push

G. Archivos

Haz clic en los triángulos para expandir las carpetas

H. index.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>Autenticación</title>
10
11
 <script type="module" src="js/lib/manejaErrores.js"></script>
12
 <script type="module" src="./js/custom/mi-nav.js"></script>
13
14
</head>
15
16
<body>
17
18
 <mi-nav></mi-nav>
19
20
 <h1>Autenticación</h1>
21
22
 <p>Bienvenid@.</p>
23
24
 <script type="module">
25
26
  import { descargaVista } from "./js/lib/descargaVista.js"
27
28
  addEventListener("load", () => descargaVista("php/vista-index.php"))
29
30
 </script>
31
32
</body>
33
34
</html>

I. perfil.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>Perfil</title>
10
11
 <script type="module" src="js/lib/manejaErrores.js"></script>
12
 <script type="module" src="./js/custom/mi-nav.js"></script>
13
14
15
</head>
16
17
<body>
18
19
 <mi-nav></mi-nav>
20
21
 <h1>Perfil</h1>
22
23
 <p>
24
  <output id="outputSan">
25
   <progress max="100">Cargando…</progress>
26
  </output>
27
 </p>
28
29
 <p>
30
  <output id="outputRoles"></output>
31
 </p>
32
33
 <p>
34
35
  <a id="login" hidden href="login.html">Iniciar sesión</a>
36
37
  <button id="botonLogout" type="button" hidden>
38
   Terminar sesión
39
  </button>
40
41
 </p>
42
43
 <script type="module">
44
45
  import { descargaVista } from "./js/lib/descargaVista.js"
46
  import { consume } from "./js/lib/consume.js"
47
  import { recibeJson } from "./js/lib/recibeJson.js"
48
49
  addEventListener("load", descargaDatos)
50
51
  async function descargaDatos() {
52
   await descargaVista("php/vista-perfil.php")
53
   botonLogout.addEventListener("click", logout)
54
  }
55
56
  async function logout() {
57
   await consume(recibeJson('php/logout.php?'))
58
   location.reload()
59
  }
60
61
 </script>
62
63
</body>
64
65
</html>

J. login.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>Iniciar sesión</title>
10
11
 <script type="module" src="js/lib/manejaErrores.js"></script>
12
13
</head>
14
15
<body>
16
17
 <progress id="ocupado" max="100">Cargando…</progress>
18
19
 <form id="formulario" hidden>
20
21
  <h1>Iniciar Sesión</h1>
22
23
  <p><a href="perfil.html">Cancelar</a></p>
24
25
  <p>
26
   <label>
27
    San
28
    <input name="san">
29
   </label>
30
  </p>
31
32
  <p>
33
   <label>
34
    Sen
35
    <input type="password" name="sen">
36
   </label>
37
  </p>
38
39
  <p><button type="submit">Iniciar sesión</button></p>
40
41
 </form>
42
43
 <script type="module">
44
45
  import { descargaVista } from "./js/lib/descargaVista.js"
46
  import { submitAccion } from "./js/lib/submitAccion.js"
47
48
  descargaDatos()
49
50
  async function descargaDatos() {
51
52
   await descargaVista("php/vista-login.php")
53
54
   formulario.addEventListener(
55
    "submit",
56
    event => submitAccion(event, "php/login.php", formulario, "perfil.html")
57
   )
58
59
  }
60
61
 </script>
62
63
</body>
64
65
</html>

K. administrador.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>Solo Administradores</title>
10
11
 <script type="module" src="js/lib/manejaErrores.js"></script>
12
 <script type="module" src="./js/custom/mi-nav.js"></script>
13
14
</head>
15
16
<body>
17
18
 <mi-nav></mi-nav>
19
20
 <main id="main" hidden>
21
22
  <h1>Solo Administradores</h1>
23
24
  <p>Hola.</p>
25
26
  <p>
27
   <button id="botonSaludo">
28
    Ejecuta servicio
29
   </button>
30
  </p>
31
32
 </main>
33
34
 <script type="module">
35
36
  import { descargaVista } from "./js/lib/descargaVista.js"
37
  import { consume } from "./js/lib/consume.js"
38
  import { recibeJson } from "./js/lib/recibeJson.js"
39
40
  addEventListener("load", descargaDatos)
41
42
  async function descargaDatos() {
43
   await descargaVista("php/vista-administrador.php")
44
   botonSaludo.addEventListener("click", saludo)
45
  }
46
47
  async function saludo() {
48
   const respuesta = await consume(recibeJson('php/saludo-cliente.php'))
49
   const json = await respuesta.json()
50
   alert(json)
51
  }
52
53
 </script>
54
55
</body>
56
57
</html>

L. cliente.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>Solo Clientes</title>
10
11
 <script type="module" src="js/lib/manejaErrores.js"></script>
12
 <script type="module" src="./js/custom/mi-nav.js"></script>
13
14
</head>
15
16
<body>
17
18
 <mi-nav id="nav"></mi-nav>
19
20
 <main id="main" hidden>
21
22
  <h1>Solo Clientes</h1>
23
24
  <p>Hola.</p>
25
26
  <p>
27
   <button id="botonSaludo">
28
    Ejecuta servicio
29
   </button>
30
  </p>
31
32
 </main>
33
34
 <script type="module">
35
36
  import { descargaVista } from "./js/lib/descargaVista.js"
37
  import { consume } from "./js/lib/consume.js"
38
  import { recibeJson } from "./js/lib/recibeJson.js"
39
40
  addEventListener("load", descargaDatos)
41
42
  async function descargaDatos() {
43
   await descargaVista("php/vista-cliente.php")
44
   botonSaludo.addEventListener("click", saludo)
45
  }
46
47
  async function saludo() {
48
   const respuesta = await consume(recibeJson('php/saludo-cliente.php'))
49
   const json = await respuesta.json()
50
   alert(json)
51
  }
52
53
 </script>
54
55
</body>
56
57
</html>

M. Carpeta « js »

Versión para imprimir.

A. Carpeta « js / custom »

1. js / custom / mi-nav.js

1
export class MiNav extends HTMLElement {
2
3
 constructor() {
4
  super()
5
  this.cargado = false
6
 }
7
8
 connectedCallback() {
9
10
  this.style.display = "block"
11
12
  if (this.cargado === false) {
13
   this.innerHTML = /* html */
14
    `<nav>
15
      <ul style="display: flex;
16
                 flex-wrap: wrap;
17
                 padding:0;
18
                 gap: 0.5em;
19
                 list-style-type: none">
20
       <li id="ocupado"><progress max="100">Cargando…</progress></li>
21
       <li id="aIndex" hidden><a href="index.html">Inicio</a></li>
22
       <li id="aAdmin" hidden>
23
        <a href="administrador.html">Para administradores</a>
24
       </li>
25
       <li id="aCliente" hidden><a href="cliente.html">Para clientes</a></li>
26
       <li id="san" hidden></li>
27
       <li id="aPerfil" hidden><a href="perfil.html">Perfil</a></li>
28
      </ul>
29
     </nav>`
30
31
   this.cargado = true
32
  }
33
 }
34
35
}
36
37
customElements.define("mi-nav", MiNav)

B. Carpeta « js / lib »

1. js / lib / consume.js

1
import { ProblemDetailsError } from "./ProblemDetailsError.js"
2
3
/**
4
 * Espera a que la promesa de un fetch termine. Si
5
 * hay error, lanza una excepción.
6
 * 
7
 * @param {Promise<Response> } servicio
8
 */
9
export async function consume(servicio) {
10
 const respuesta = await servicio
11
 if (respuesta.ok) {
12
  return respuesta
13
 } else {
14
  const contentType = respuesta.headers.get("Content-Type")
15
  if (
16
   contentType !== null && contentType.startsWith("application/problem+json")
17
  )
18
   throw new ProblemDetailsError(await respuesta.json())
19
  else
20
   throw new Error(respuesta.statusText)
21
 }
22
}

2. js / lib / descargaVista.js

1
import { consume } from "./consume.js"
2
import { muestraObjeto } from "./muestraObjeto.js"
3
import { recibeJson } from "./recibeJson.js"
4
5
/**
6
 * @param {string} url
7
 * @param { "GET" | "POST"| "PUT" | "PATCH" | "DELETE" | "TRACE" | "OPTIONS"
8
 *  | "CONNECT" | "HEAD" } metodoHttp
9
 */
10
export async function descargaVista(url, metodoHttp = "GET") {
11
 const respuesta = await consume(recibeJson(url, metodoHttp))
12
 const json = await respuesta.json()
13
 muestraObjeto(document, json)
14
 return json
15
}

3. js / lib / enviaFormRecibeJson.js

1
/**
2
 * Envía los datos de un formolario a la url usando la codificación
3
 * multipart/form-data.
4
 * @param {string} url
5
 * @param {HTMLFormElement} formulario
6
 * @param { "GET" | "POST"| "PUT" | "PATCH" | "DELETE" | "TRACE" | "OPTIONS"
7
 *  | "CONNECT" | "HEAD" } metodoHttp
8
 */
9
export function enviaFormRecibeJson(url, formulario, metodoHttp = "POST") {
10
 return fetch(
11
  url,
12
  {
13
   method: metodoHttp,
14
   headers: { "Accept": "application/json, application/problem+json" },
15
   body: new FormData(formulario)
16
  }
17
 )
18
}

4. js / lib / manejaErrores.js

1
import { muestraError } from "./muestraError.js"
2
3
/**
4
 * Intercepta Response.prototype.json para capturar errores de parseo
5
 * y asegurar que se reporten correctamente en navegadores Chromium.
6
 */
7
{
8
 const originalJson = Response.prototype.json
9
10
 Response.prototype.json = function () {
11
  // Llamamos al método original usando el contexto (this) de la respuesta
12
  return originalJson.apply(this, arguments)
13
   .catch((/** @type {any} */ error) => {
14
    // Corrige un error de Chrome que evita el manejo correcto de errores.
15
    throw new Error(error)
16
   })
17
 }
18
}
19
20
window.onerror = function (
21
  /** @type {string} */ _message,
22
  /** @type {string} */ _url,
23
  /** @type {number} */ _line,
24
  /** @type {number} */ _column,
25
  /** @type {Error} */ errorObject
26
) {
27
 muestraError(errorObject)
28
 return true
29
}
30
31
window.addEventListener('unhandledrejection', event => {
32
 muestraError(event.reason)
33
 event.preventDefault()
34
})
35

5. js / lib / muestraError.js

1
import { ProblemDetailsError } from "./ProblemDetailsError.js"
2
3
/**
4
 * Muestra los datos de una Error en la consola y en un cuadro de alerta.
5
 * @param { ProblemDetailsError | Error | null } error descripción del error.
6
 */
7
export function muestraError(error) {
8
9
 if (error === null) {
10
11
  console.error("Error")
12
  alert("Error")
13
14
 } else if (error instanceof ProblemDetailsError) {
15
16
  const problemDetails = error.problemDetails
17
18
  let mensaje =
19
   typeof problemDetails["title"] === "string" ? problemDetails["title"] : ""
20
  if (typeof problemDetails["detail"] === "string") {
21
   if (mensaje !== "") {
22
    mensaje += "\n\n"
23
   }
24
   mensaje += problemDetails["detail"]
25
  }
26
  if (mensaje === "") {
27
   mensaje = "Error"
28
  }
29
  console.error(error, problemDetails)
30
  alert(mensaje)
31
32
 } else {
33
34
  console.error(error)
35
  alert(error.message)
36
37
 }
38
39
}

6. js / lib / muestraObjeto.js

1
/**
2
 * @param {Document | HTMLElement | ShadowRoot} raizHtml
3
 * @param { any } objeto
4
 */
5
export function muestraObjeto(raizHtml, objeto) {
6
 for (const [nombre, definiciones] of Object.entries(objeto)) {
7
  if (Array.isArray(definiciones)) {
8
   muestraArray(raizHtml, nombre, definiciones)
9
  } else if (definiciones !== undefined && definiciones !== null) {
10
   muestraElemento(raizHtml, nombre, definiciones)
11
  }
12
 }
13
}
14
15
/**
16
 * @param { string } nombre
17
 */
18
export function selectorDeNombre(nombre) {
19
 return `[id="${nombre}"],[name="${nombre}"],[data-name="${nombre}"]`
20
}
21
22
/**
23
 * @param { Document | HTMLElement | ShadowRoot } raizHtml
24
 * @param { string } propiedad
25
 * @param {any[]} valores
26
 */
27
function muestraArray(raizHtml, propiedad, valores) {
28
 const conjunto = new Set(valores)
29
 const elementos = raizHtml.querySelectorAll(selectorDeNombre(propiedad))
30
 if (elementos.length === 1 && elementos[0] instanceof HTMLSelectElement) {
31
  muestraOptions(elementos[0], conjunto)
32
 } else {
33
  muestraInputs(elementos, conjunto)
34
 }
35
36
}
37
38
/**
39
 * @param {HTMLSelectElement} select
40
 * @param {Set<any>} conjunto
41
 */
42
function muestraOptions(select, conjunto) {
43
 for (let i = 0, options = select.options, len = options.length; i < len; i++) {
44
  const option = options[i]
45
  option.selected = conjunto.has(option.value)
46
 }
47
}
48
49
/**
50
 * @param {NodeListOf<Element>} elementos
51
 * @param {Set<any>} conjunto
52
 */
53
function muestraInputs(elementos, conjunto) {
54
 for (let i = 0, len = elementos.length; i < len; i++) {
55
  const elemento = elementos[i]
56
  if (elemento instanceof HTMLInputElement) {
57
   elemento.checked = conjunto.has(elemento.value)
58
  }
59
 }
60
}
61
62
const data_ = "data-"
63
const dataLength = data_.length
64
65
/**
66
 * @param {Document | HTMLElement | ShadowRoot} raizHtml
67
 * @param {string} nombre
68
 * @param {{ [s: string]: any; } } definiciones
69
 */
70
function muestraElemento(raizHtml, nombre, definiciones) {
71
 const elemento = raizHtml.querySelector(selectorDeNombre(nombre))
72
 if (elemento !== null) {
73
  for (const [propiedad, valor] of Object.entries(definiciones)) {
74
   if (propiedad in elemento) {
75
    elemento[propiedad] = valor
76
   } else if (
77
    propiedad.length > dataLength
78
    && propiedad.startsWith(data_)
79
    && elemento instanceof HTMLElement
80
   ) {
81
    elemento.dataset[propiedad.substring(dataLength)] = valor
82
   }
83
  }
84
 }
85
}

7. js / lib / ProblemDetailsError.js

1
export class ProblemDetailsError extends Error {
2
3
 /**
4
  * Detalle de los errores devueltos por un servicio.
5
  * Crea una instancia de ProblemDetailsError.
6
  * @param {object} problemDetails Objeto con la descripcipon del error.
7
  */
8
 constructor(problemDetails) {
9
10
  super(typeof problemDetails["detail"] === "string"
11
   ? problemDetails["detail"]
12
   : (typeof problemDetails["title"] === "string"
13
    ? problemDetails["title"]
14
    : "Error"))
15
16
  this.problemDetails = problemDetails
17
18
 }
19
20
}

8. js / lib / recibeJson.js

1
2
/**
3
 * @param {string} url
4
 * @param { "GET" | "POST"| "PUT" | "PATCH" | "DELETE" | "TRACE" | "OPTIONS"
5
 *  | "CONNECT" | "HEAD" } metodoHttp
6
 */
7
export async function recibeJson(url, metodoHttp = "GET") {
8
 return fetch(
9
  url,
10
  {
11
   method: metodoHttp,
12
   headers: { "Accept": "application/json, application/problem+json" }
13
  }
14
 )
15
}

9. js / lib / submitAccion.js

1
import { consume } from "./consume.js"
2
import { enviaFormRecibeJson } from "./enviaFormRecibeJson.js"
3
4
/**
5
 * @param {Event} event
6
 * @param {string} url
7
 * @param {HTMLFormElement} formulario
8
 * @param {string} nuevaVista
9
 */
10
export async function submitAccion(event, url, formulario, nuevaVista) {
11
 event.preventDefault()
12
 await consume(enviaFormRecibeJson(url, formulario))
13
 location.href = nuevaVista
14
}

N. Carpeta « php »

Versión para imprimir.

A. php / Bd.php

1
<?php
2
3
require_once __DIR__ . "/ROL_ID_CLIENTE.php";
4
require_once __DIR__ . "/ROL_ID_ADMINISTRADOR.php";
5
require_once __DIR__ . "/lib/rolBusca.php";
6
require_once __DIR__ . "/lib/rolAgrega.php";
7
require_once __DIR__ . "/lib/usuRolAgrega.php";
8
require_once __DIR__ . "/usuarioBuscaSan.php";
9
10
class Bd
11
{
12
13
 private static ?PDO $pdo = null;
14
15
 static function pdo(): PDO
16
 {
17
  if (self::$pdo === null) {
18
19
   self::$pdo = new PDO(
20
    // cadena de conexión
21
    "sqlite:" . __DIR__ . "/srvaut.db",
22
    // usuario
23
    null,
24
    // contraseña
25
    null,
26
    // Opciones: pdos no persistentes y lanza excepciones.
27
    [PDO::ATTR_PERSISTENT => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
28
   );
29
30
   self::$pdo->exec(
31
    'CREATE TABLE IF NOT EXISTS USUARIO (
32
      USU_ID INTEGER,
33
      USU_SAN TEXT NOT NULL,
34
      USU_SEN TEXT NOT NULL,
35
      CONSTRAINT USU_PK
36
       PRIMARY KEY(USU_ID),
37
      CONSTRAINT USU_SAN_UNQ
38
       UNIQUE(USU_SAN),
39
      CONSTRAINT USU_SAN_NV
40
       CHECK(LENGTH(USU_SAN) > 0)
41
     )'
42
   );
43
   self::$pdo->exec(
44
    'CREATE TABLE IF NOT EXISTS ROL (
45
      ROL_ID TEXT NOT NULL,
46
      ROL_DESCRIPCION TEXT NOT NULL,
47
      CONSTRAINT ROL_PK
48
       PRIMARY KEY(ROL_ID),
49
      CONSTRAINT ROL_ID_NV
50
       CHECK(LENGTH(ROL_ID) > 0),
51
      CONSTRAINT ROL_DESCR_UNQ
52
       UNIQUE(ROL_DESCRIPCION),
53
      CONSTRAINT ROL_DESCR_NV
54
       CHECK(LENGTH(ROL_DESCRIPCION) > 0)
55
     )'
56
   );
57
   self::$pdo->exec(
58
    'CREATE TABLE IF NOT EXISTS USU_ROL (
59
       USU_ID INTEGER NOT NULL,
60
       ROL_ID TEXT NOT NULL,
61
       CONSTRAINT USU_ROL_PK
62
        PRIMARY KEY(USU_ID, ROL_ID),
63
       CONSTRAINT USU_ROL_USU_FK
64
        FOREIGN KEY (USU_ID) REFERENCES USUARIO(USU_ID),
65
       CONSTRAINT USU_ROL_ROL_FK
66
        FOREIGN KEY (ROL_ID) REFERENCES ROL(ROL_ID)
67
      )'
68
   );
69
70
   self::$pdo->beginTransaction();
71
72
   if (rolBusca(self::$pdo, "Administrador") === false) {
73
    rolAgrega(
74
     bd: self::$pdo,
75
     id: "Administrador",
76
     descripcion: "Administra el sistema."
77
    );
78
   }
79
80
   if (rolBusca(self::$pdo, "Cliente") === false) {
81
    rolAgrega(
82
     bd: self::$pdo,
83
     id: "Cliente",
84
     descripcion: "Realiza compras."
85
    );
86
   }
87
88
   $usuarioAgrega = self::$pdo->prepare(
89
    "INSERT INTO USUARIO (
90
        USU_SAN, USU_SEN
91
       ) VALUES (
92
        :USU_SAN, :USU_SEN
93
       )"
94
   );
95
96
   if (usuarioBuscaSan(self::$pdo, "pepito") === false) {
97
    $usuarioAgrega->execute([
98
     ":USU_SAN" => "pepito",
99
     ":USU_SEN" => password_hash("cuentos", PASSWORD_DEFAULT),
100
    ]);
101
    $usuId = self::$pdo->lastInsertId();
102
    usuRolAgrega(self::$pdo, $usuId, [ROL_ID_CLIENTE]);
103
   }
104
105
   if (usuarioBuscaSan(self::$pdo, "susana") === false) {
106
    $usuarioAgrega->execute([
107
     ":USU_SAN" => "susana",
108
     ":USU_SEN" => password_hash("alegria", PASSWORD_DEFAULT),
109
    ]);
110
    $usuId = self::$pdo->lastInsertId();
111
    usuRolAgrega(self::$pdo, $usuId, [ROL_ID_ADMINISTRADOR]);
112
   }
113
114
   if (usuarioBuscaSan(self::$pdo, "bebe") === false) {
115
    $usuarioAgrega->execute([
116
     ":USU_SAN" => "bebe",
117
     ":USU_SEN" => password_hash("saurio", PASSWORD_DEFAULT),
118
    ]);
119
    $usuId = self::$pdo->lastInsertId();
120
    usuRolAgrega(self::$pdo, $usuId, [ROL_ID_CLIENTE,ROL_ID_ADMINISTRADOR]);
121
   }
122
123
   self::$pdo->commit();
124
  }
125
126
  return self::$pdo;
127
 }
128
}
129

B. php / jsonMiNav.php

1
<?php
2
3
function jsonMiNav(string $san, array $rolIds)
4
{
5
 $json = [
6
  "ocupado" => ["hidden" => true],
7
  "aIndex" => ["hidden" => false],
8
  "aAdmin" => [
9
   "hidden" => array_search(ROL_ID_ADMINISTRADOR, $rolIds, true) === false
10
  ],
11
  "aCliente" => [
12
   "hidden" => array_search(ROL_ID_CLIENTE, $rolIds, true) === false
13
  ],
14
  "san" => [
15
   "hidden" => $san === "",
16
   "textContent" => $san
17
  ],
18
  "aPerfil" => ["hidden" => false],
19
 ];
20
21
 return $json;
22
}
23

C. php / login.php

1
<?php
2
3
require_once __DIR__ . "/lib/manejaErrores.php";
4
require_once __DIR__ . "/lib/BAD_REQUEST.php";
5
require_once __DIR__ . "/lib/recibeTextoObligatorio.php";
6
require_once __DIR__ . "/lib/recibeTexto.php";
7
require_once __DIR__ . "/lib/devuelveJson.php";
8
require_once __DIR__ . "/lib/rolIdsParaUsuId.php";
9
require_once __DIR__ . "/SAN.php";
10
require_once __DIR__ . "/USU_ID.php";
11
require_once __DIR__ . "/ROL_IDS.php";
12
require_once __DIR__ . "/Bd.php";
13
require_once __DIR__ . "/protegeLogin.php";
14
require_once __DIR__ . "/usuarioBuscaSan.php";
15
16
list($san, $rolIds) = protegeLogin([]);
17
18
$san = recibeTextoObligatorio("san");
19
$sen = recibeTexto("sen");
20
21
$bd = Bd::pdo();
22
23
$usuario = usuarioBuscaSan($bd, $san);
24
25
if (
26
 $usuario === false
27
 || !password_verify(
28
  ($sen === false || $sen === null) ? "" : $sen,
29
  $usuario["USU_SEN"]
30
 )
31
)
32
 throw new ProblemDetailsException([
33
  "status" => BAD_REQUEST,
34
  "type" => "/errors/datosincorrectos.html",
35
  "title" => "Datos incorrectos.",
36
  "detail" => "El san y/o el sen proporcionados son incorrectos.",
37
 ]);
38
39
$_SESSION[SAN] = $san;
40
$_SESSION[USU_ID] = $usuario[USU_ID];
41
42
devuelveJson([
43
 SAN => $san,
44
 ROL_IDS => rolIdsParaUsuId($bd, $usuario[USU_ID])
45
]);
46

D. php / logout.php

1
<?php
2
3
require_once __DIR__ . "/lib/manejaErrores.php";
4
require_once __DIR__ . "/lib/devuelveNoContent.php";
5
require_once __DIR__ . "/SAN.php";
6
require_once __DIR__ . "/ROL_IDS.php";
7
8
session_start();
9
10
if (isset($_SESSION[SAN])) {
11
 unset($_SESSION[SAN]);
12
}
13
if (isset($_SESSION[ROL_IDS])) {
14
 unset($_SESSION[ROL_IDS]);
15
}
16
17
session_destroy();
18
19
devuelveNoContent();
20

E. php / protege.php

1
<?php
2
3
require_once __DIR__ . "/lib/NO_AUTORIZADO.php";
4
require_once __DIR__ . "/lib/ProblemDetailsException.php";
5
require_once __DIR__ . "/lib/rolIdsParaUsuId.php";
6
require_once __DIR__ . "/SAN.php";
7
require_once __DIR__ . "/USU_ID.php";
8
require_once __DIR__ . "/Bd.php";
9
10
function protege(array $rolIdsPermitidos)
11
{
12
13
 session_start();
14
15
 $san = isset($_SESSION[SAN]) ? $_SESSION[SAN] : "";
16
 $usuId = isset($_SESSION[USU_ID]) ? $_SESSION[USU_ID] : -1;
17
 $rolIds = rolIdsParaUsuId(Bd::pdo(), $usuId);
18
19
 if (count($rolIdsPermitidos) === 0) {
20
21
  return [$san, $rolIds, $usuId];
22
 } else {
23
24
  if ($san === "")  throw creaNoAutorizado();
25
26
  foreach ($rolIdsPermitidos as $rolId) {
27
   if (array_search($rolId, $rolIds, true) !== false) {
28
    return [$san, $rolIds, $usuId];
29
   }
30
  }
31
32
  throw creaNoAutorizado();
33
 }
34
}
35
36
function creaNoAutorizado()
37
{
38
 return new ProblemDetailsException([
39
  "status" => NO_AUTORIZADO,
40
  "type" => "/errors/noautorizado.html",
41
  "title" => "No autorizado.",
42
  "detail" => "No estás autorizado para usar este recurso.",
43
 ]);
44
}
45

F. php / protegeLogin.php

1
<?php
2
3
require_once __DIR__ . "/lib/NO_AUTORIZADO.php";
4
require_once __DIR__ . "/lib/ProblemDetailsException.php";
5
require_once __DIR__ . "/protege.php";
6
7
function protegeLogin(array $rolIdsPermitidos)
8
{
9
10
 list($san, $rolIds, $usuId) = protege($rolIdsPermitidos);
11
12
 if ($san !== "")
13
  throw new ProblemDetailsException([
14
   "status" => NO_AUTORIZADO,
15
   "type" => "/errors/sesioniniciada.html",
16
   "title" => "Sesión iniciada.",
17
   "detail" => "La sesión ya está iniciada.",
18
  ]);
19
20
 return [$san, $rolIds, $usuId];
21
}
22

G. php / ROL_IDS.php

1
<?php
2
3
const ROL_IDS = "rolIds";

H. php / ROL_ID_ADMINISTRADOR.php

1
<?php
2
3
const ROL_ID_ADMINISTRADOR = "Administrador";
4

I. php / ROL_ID_CLIENTE.php

1
<?php
2
3
const ROL_ID_CLIENTE = "Cliente";

J. php / saludo-cliente.php

1
<?php
2
3
require_once __DIR__ . "/lib/manejaErrores.php";
4
require_once __DIR__ . "/lib/devuelveJson.php";
5
require_once __DIR__ . "/ROL_ID_CLIENTE.php";
6
require_once __DIR__ . "/protege.php";
7
8
list($san) = protege([ROL_ID_CLIENTE]);
9
10
devuelveJson("Hola " . $san);
11

K. php / SAN.php

1
<?php
2
3
const SAN = "san";

L. php / usuarioBuscaSan.php

1
<?php
2
3
function usuarioBuscaSan(\PDO $bd, string $san)
4
{
5
 $usuarioBusca = $bd->prepare("SELECT * FROM USUARIO WHERE USU_SAN = :USU_SAN");
6
 $usuarioBusca->execute([":USU_SAN" => $san]);
7
 $usuario = $usuarioBusca->fetch(PDO::FETCH_ASSOC);
8
 return $usuario;
9
}
10

M. php / USU_ID.php

1
<?php
2
3
const USU_ID = "USU_ID";

N. php / vista-administrador.php

1
<?php
2
3
require_once __DIR__ . "/lib/manejaErrores.php";
4
require_once __DIR__ . "/protege.php";
5
require_once __DIR__ . "/lib/devuelveJson.php";
6
require_once __DIR__ . "/ROL_ID_ADMINISTRADOR.php";
7
require_once __DIR__ . "/jsonMiNav.php";
8
9
list($san, $rolIds) = protege([ROL_ID_ADMINISTRADOR]);
10
devuelveJson([
11
 ...jsonMiNav($san, $rolIds),
12
 "main" => ["hidden" => false],
13
]);
14

O. php / vista-cliente.php

1
<?php
2
3
require_once __DIR__ . "/lib/manejaErrores.php";
4
require_once __DIR__ . "/protege.php";
5
require_once __DIR__ . "/lib/devuelveJson.php";
6
require_once __DIR__ . "/ROL_ID_CLIENTE.php";
7
require_once __DIR__ . "/jsonMiNav.php";
8
9
list($san, $rolIds) = protege([ROL_ID_CLIENTE]);
10
11
devuelveJson([
12
 ...jsonMiNav($san, $rolIds),
13
 "main" => ["hidden" => false],
14
]);
15

P. php / vista-index.php

1
<?php
2
3
require_once __DIR__ . "/lib/manejaErrores.php";
4
require_once __DIR__ . "/protege.php";
5
require_once __DIR__ . "/lib/devuelveJson.php";
6
require_once __DIR__ . "/jsonMiNav.php";
7
8
list($san, $rolIds) = protege([]);
9
10
devuelveJson(jsonMiNav($san, $rolIds));
11

Q. php / vista-login.php

1
<?php
2
3
require_once __DIR__ . "/lib/manejaErrores.php";
4
require_once __DIR__ . "/lib/devuelveJson.php";
5
require_once __DIR__ . "/protegeLogin.php";
6
7
list($san) = protegeLogin([]);
8
9
devuelveJson([
10
 "ocupado" => ["hidden" => true],
11
 "formulario" => ["hidden" =>  false],
12
]);
13

R. php / vista-perfil.php

1
<?php
2
3
require_once __DIR__ . "/lib/manejaErrores.php";
4
require_once __DIR__ . "/protege.php";
5
require_once __DIR__ . "/lib/devuelveJson.php";
6
require_once __DIR__ . "/jsonMiNav.php";
7
8
list($san, $rolIds) = protege([]);
9
10
if ($san === "") {
11
 devuelveJson([
12
  ...jsonMiNav($san, $rolIds),
13
  "login" => ["hidden" => false],
14
  "outputSan" => ["value" => "No has iniciado sesión."],
15
  "outputRoles" => ["value" => ""],
16
 ]);
17
} else {
18
 devuelveJson([
19
  ...jsonMiNav($san, $rolIds),
20
  "botonLogout" => ["hidden" => false],
21
  "outputSan" => ["value" => $san],
22
  "outputRoles" => [
23
   "value" => count($rolIds) === 0
24
    ? "Sin roles."
25
    : implode(", ", $rolIds),
26
  ],
27
 ]);
28
}
29

S. Carpeta « php / lib »

1. php / lib / BAD_REQUEST.php

1
<?php
2
3
const BAD_REQUEST = 400;
4

2. php / lib / devuelveJson.php

1
<?php
2
3
require_once __DIR__ . "/devuelveResultadoNoJson.php";
4
5
function devuelveJson($resultado)
6
{
7
 $json = json_encode($resultado);
8
 if ($json === false) {
9
  devuelveResultadoNoJson();
10
 } else {
11
  header("Content-Type: application/json; charset=utf-8");
12
  echo $json;
13
 }
14
 exit();
15
}
16

3. php / lib / devuelveNoContent.php

1
<?php
2
3
function devuelveNoContent()
4
{
5
 http_response_code(204);
6
}
7

4. php / lib / devuelveResultadoNoJson.php

1
<?php
2
3
require_once __DIR__ . "/INTERNAL_SERVER_ERROR.php";
4
5
function devuelveResultadoNoJson()
6
{
7
 http_response_code(INTERNAL_SERVER_ERROR);
8
 header("Content-Type: application/problem+json; charset=utf-8");
9
10
 echo '{' .
11
  "status: " . INTERNAL_SERVER_ERROR .
12
  '"title": "El resultado no puede representarse como JSON."' .
13
  '"type": "/errors/resultadonojson.html"' .
14
  '}';
15
}
16

5. php / lib / INTERNAL_SERVER_ERROR.php

1
<?php
2
3
const INTERNAL_SERVER_ERROR = 500;

6. php / lib / manejaErrores.php

1
<?php
2
3
require_once __DIR__ . "/INTERNAL_SERVER_ERROR.php";
4
require_once __DIR__ . "/ProblemDetailsException.php";
5
6
// Hace que se lance una excepción automáticamente cuando se genere un error.
7
set_error_handler(function ($severity, $message, $file, $line) {
8
 throw new ErrorException($message, 0, $severity, $file, $line);
9
});
10
11
// Código cuando una excepción no es atrapada.
12
set_exception_handler(function (Throwable $excepcion) {
13
 if ($excepcion instanceof ProblemDetailsException) {
14
  devuelveProblemDetails($excepcion->problemDetails);
15
 } else {
16
  devuelveProblemDetails([
17
   "status" => INTERNAL_SERVER_ERROR,
18
   "title" => "Error interno del servidor",
19
   "detail" => $excepcion->getMessage(),
20
   "type" => "/errors/errorinterno.html",
21
  ]);
22
 }
23
 exit();
24
});
25
26
function devuelveProblemDetails(array $array)
27
{
28
 $json = json_encode($array);
29
 if ($json === false) {
30
  devuelveResultadoNoJson();
31
 } else {
32
  http_response_code(isset($array["status"]) ? $array["status"] : 500);
33
  header("Content-Type: application/problem+json; charset=utf-8");
34
  echo $json;
35
 }
36
}
37

7. php / lib / NO_AUTORIZADO.php

1
<?php
2
3
const NO_AUTORIZADO = 401;
4

8. php / lib / ProblemDetailsException.php

1
<?php
2
3
require_once __DIR__ . "/INTERNAL_SERVER_ERROR.php";
4
5
/**
6
 * Detalle de los errores devueltos por un servicio.
7
 */
8
class ProblemDetailsException extends Exception
9
{
10
11
 public array $problemDetails;
12
13
 public function __construct(
14
  array $problemDetails,
15
 ) {
16
  
17
  parent::__construct(
18
   isset($problemDetails["detail"])
19
    ? $problemDetails["detail"]
20
    : (isset($problemDetails["title"])
21
     ? $problemDetails["title"]
22
     : "Error"),
23
   $problemDetails["status"]
24
    ? $problemDetails["status"]
25
    : INTERNAL_SERVER_ERROR
26
  );
27
28
  $this->problemDetails = $problemDetails;
29
 }
30
}
31

9. php / lib / recibeTexto.php

1
<?php
2
3
/**
4
 * Devuelve el texto de un parámetro enviado al
5
 * servidor por medio de GET, POST o cookie.
6
 * 
7
 * Si el parámetro no se recibe, devuelve false.
8
 */
9
function recibeTexto(string $parametro): false|string
10
{
11
 /* Si el parámetro está asignado en $_REQUEST,
12
  * devuelve su valor; de lo contrario, devuelve false.
13
  */
14
 $valor = isset($_REQUEST[$parametro])
15
  ? $_REQUEST[$parametro]
16
  : false;
17
 return $valor;
18
}
19

10. php / lib / recibeTextoObligatorio.php

1
<?php
2
3
require_once __DIR__ . "/BAD_REQUEST.php";
4
require_once __DIR__ . "/recibeTexto.php";
5
require_once __DIR__ . "/ProblemDetailsException.php";
6
7
function recibeTextoObligatorio(string $parametro)
8
{
9
 $texto = recibeTexto($parametro);
10
11
 if ($texto === false)
12
  throw new ProblemDetailsException([
13
   "status" => BAD_REQUEST,
14
   "title" => "Falta el valor $parametro.",
15
   "type" => "/errors/faltavalor.html",
16
   "detail" => "La solicitud no tiene el valor de $parametro."
17
  ]);
18
19
 $trimTexto = trim($texto);
20
21
 if ($trimTexto === "")
22
  throw new ProblemDetailsException([
23
   "status" => BAD_REQUEST,
24
   "title" => "Campo $parametro en blanco.",
25
   "type" => "/errors/campoenblanco.html",
26
   "detail" => "Pon texto en el campo $parametro."
27
  ]);
28
29
 return $trimTexto;
30
}
31

11. php / lib / rolAgrega.php

1
<?php
2
3
function rolAgrega(\PDO $bd, string $id, string $descripcion)
4
{
5
 $rolAgrega = $bd->prepare(
6
  "INSERT INTO ROL (
7
     ROL_ID, ROL_DESCRIPCION
8
    ) VALUES (
9
     :ROL_ID, :ROL_DESCRIPCION
10
    )"
11
 );
12
 $rolAgrega->execute([
13
  ":ROL_ID" => $id,
14
  ":ROL_DESCRIPCION" => $descripcion,
15
 ]);
16
}
17

12. php / lib / rolBusca.php

1
<?php
2
3
function rolBusca(\PDO $bd, string $id)
4
{
5
 $rolBusca =  $bd->prepare("SELECT * FROM ROL WHERE ROL_ID = :ROL_ID");
6
 $rolBusca->execute([":ROL_ID" => $id]);
7
 $rol = $rolBusca->fetch(PDO::FETCH_ASSOC);
8
 return $rol;
9
}
10

13. php / lib / rolIdsParaUsuId.php

1
<?php
2
3
function rolIdsParaUsuId(\PDO $bd, int $usuId)
4
{
5
 $stmt = $bd->prepare(
6
  "SELECT ROL_ID
7
   FROM USU_ROL
8
   WHERE USU_ID = :USU_ID
9
   ORDER BY USU_ID"
10
 );
11
 $stmt->execute([":USU_ID" => $usuId]);
12
 $rolIds = $stmt->fetchAll(PDO::FETCH_COLUMN, 0);
13
 return $rolIds;
14
}
15

14. php / lib / usuRolAgrega.php

1
<?php
2
3
function usuRolAgrega(\PDO $bd, string $usuId, array $rolIds)
4
{
5
 $usuRolAgrega = $bd->prepare(
6
  "INSERT INTO USU_ROL (USU_ID, ROL_ID) values (:USU_ID, :ROL_ID)"
7
 );
8
 foreach ($rolIds as $rolId) {
9
  $usuRolAgrega->execute([
10
   ":USU_ID" => $usuId,
11
   ":ROL_ID" => $rolId,
12
  ]);
13
 }
14
}
15

O. Carpeta « errors »

Versión para imprimir.

A. errors / campoenblanco.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>Campo en blanco</title>
10
11
</head>
12
13
<body>
14
15
 <h1>Campo en blanco</h1>
16
17
 <p>Pon texto en el campo obligatorio que está en blanco.</p>
18
19
</body>
20
21
</html>

B. errors / datosincorrectos.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>Datos incorrectos</title>
10
11
</head>
12
13
<body>
14
15
 <h1>Datos incorrectos</h1>
16
17
 <p>El san y/o el sen proporcionados son incorrectos.</p>
18
</body>
19
20
</html>

C. errors / errorinterno.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>Error interno del servidor</title>
10
11
</head>
12
13
<body>
14
15
 <h1>Error interno del servidor</h1>
16
17
 <p>Se presentó de forma inesperada un error interno del servidor.</p>
18
19
</body>
20
21
</html>

D. errors / faltavalor.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>Falta un valor</title>
10
11
</head>
12
13
<body>
14
15
 <h1>Falta un valor</h1>
16
17
 <p>La solicitud no tiene un valor obligatorio.</p>
18
19
</body>
20
21
</html>

E. errors / noautorizado.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>No autorizado</title>
10
11
</head>
12
13
<body>
14
15
 <h1>No autorizado</h1>
16
17
 <p>No está autorizado para usar este recurso.</p>
18
19
</body>
20
21
</html>

F. errors / resultadonojson.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>El resultado no puede representarse como JSON</title>
10
11
</head>
12
13
<body>
14
15
 <h1>El resultado no puede representarse como JSON</h1>
16
17
 <p>
18
  Debido a un error interno del servidor, el resultado generado, no se puede
19
  recuperar.
20
 </p>
21
22
</body>
23
24
</html>

G. errors / sesioniniciada.html

1
<!DOCTYPE html>
2
<html lang="es">
3
4
<head>
5
6
 <meta charset="UTF-8">
7
 <meta name="viewport" content="width=device-width">
8
9
 <title>Sesión iniciada</title>
10
11
</head>
12
13
<body>
14
15
 <h1>Sesión iniciada</h1>
16
17
 <p>La sesión ya está iniciada.</p>
18
19
</body>
20
21
</html>

P. jsconfig.json

1
{
2
 "compilerOptions": {
3
  "checkJs": true,
4
  "strictNullChecks": true,
5
  "target": "ES6",
6
  "module": "Node16",
7
  "moduleResolution": "Node16",
8
  "lib": [
9
   "ES2017",
10
   "WebWorker",
11
   "DOM"
12
  ]
18
}

Q. Resumen