11. php / lib / validaToken.php

1
<?php
2
3
require_once __DIR__ . "/FORBIDDEN.php";
4
require_once __DIR__ . "/INTERNAL_SERVER_ERROR.php";
5
require_once __DIR__ . "/ProblemDetailsException.php";
6
7
function validaToken(string $pagina, string $token)
8
{
9
 if (!isset($_SESSION[$pagina]))
10
  throw new ProblemDetailsException([
11
   "status" => FORBIDDEN,
12
   "title" => "Página no registrada.",
13
   "type" => "/error/paginanoregistrada.html",
14
  ]);
15
16
 $tokensParaPagina = $_SESSION[$pagina];
17
18
 if (!is_array($tokensParaPagina))
19
  throw new ProblemDetailsException([
20
   "status" => INTERNAL_SERVER_ERROR,
21
   " title" => "No hay arreglo de tokens.",
22
   "type" => "/error/sintokens.html",
23
  ]);
24
25
 $hallado = false;
26
27
 // Valida que el token se haya registrado.
28
  $time = time();
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 ProblemDetailsException([
37
     "status" => FORBIDDEN,
38
     "title" => "Tiempo de expiración excedido.",
39
     "type" => "/error/paginaexpirada.html",
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 ProblemDetailsException([
55
   "status" => FORBIDDEN,
56
   "title" => "Página no registrada.",
57
   "type" => "/error/paginanoregistrada.html",
58
  ]);
59
}
60
skip_previous skip_next