6. lib / php / validaToken.php

1<?php
2
3require_once __DIR__ . "/ProblemDetails.php";
4
5const FORBIDDEN = 403;
6
7function validaToken(string $pagina, string $token)
8{
9
10 if (!isset($_SESSION[$pagina]))
11 throw new ProblemDetails(
12 status: FORBIDDEN,
13 type: "/error/paginanoregistrada.html",
14 title: "Página no registrada.",
15 );
16
17 $tokensParaPagina = $_SESSION[$pagina];
18
19 if (!is_array($tokensParaPagina))
20 throw new ProblemDetails(
21 status: FORBIDDEN,
22 type: "/error/sintokens.html",
23 title: "No hay arereglo de tokens.",
24 );
25
26 $hallado = false;
27
28 // Valida que el token se haya registrado.
29 foreach ($tokensParaPagina as $llave => $tokenParaPagina) {
30
31 if (strcmp($token, $tokenParaPagina["texto"]) === 0) {
32
33 if ($tokenParaPagina["expiracion"] < time()) {
34 unset($tokensParaPagina[$llave]);
35 $_SESSION[$pagina] = $tokensParaPagina;
36 throw new ProblemDetails(
37 status: FORBIDDEN,
38 type: "/error/paginaexpirada.html",
39 title: "Tiempo de expiración excedido.",
40 );
41 }
42
43 $hallado = true;
44 } elseif ($tokenParaPagina["expiracion"] > time()) {
45
46 // Elimina tokens expirados
47 unset($tokensParaPagina[$llave]);
48 }
49 }
50
51 $_SESSION[$pagina] = $tokensParaPagina;
52
53 if ($hallado === false)
54 throw new ProblemDetails(
55 status: FORBIDDEN,
56 type: "/error/paginanoregistrada.html",
57 title: "Página no registrada.",
58 );
59}
60
skip_previous skip_next