| 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 creaToken(string $pagina, int $duracionEnMinutos) |
| 8 | { |
| 9 | $criptografiaFuerte = true; |
| 10 | |
| 11 | |
| 12 | $token = [ |
| 13 | "expiracion" => time() + 60 * $duracionEnMinutos, |
| 14 | |
| 15 | "texto" => bin2hex(openssl_random_pseudo_bytes(80, $criptografiaFuerte)) |
| 16 | ]; |
| 17 | |
| 18 | |
| 19 | if (isset($_SESSION[$pagina])) { |
| 20 | |
| 21 | $tokensParaPagina = $_SESSION[$pagina]; |
| 22 | |
| 23 | if (!is_array($tokensParaPagina)) |
| 24 | throw new ProblemDetailsException([ |
| 25 | "status" => INTERNAL_SERVER_ERROR, |
| 26 | " title" => "No hay arreglo de tokens.", |
| 27 | "type" => "/error/sintokens.html", |
| 28 | ]); |
| 29 | |
| 30 | |
| 31 | $time = time(); |
| 32 | foreach ($tokensParaPagina as $llave => $tokenParaPagina) { |
| 33 | if ($tokenParaPagina["expiracion"] > $time) { |
| 34 | unset($tokensParaPagina[$llave]); |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | |
| 39 | $tokensParaPagina[] = $token; |
| 40 | $_SESSION[$pagina] = $tokensParaPagina; |
| 41 | } else { |
| 42 | |
| 43 | |
| 44 | $_SESSION[$pagina] = [$token]; |
| 45 | } |
| 46 | |
| 47 | return $token["texto"]; |
| 48 | } |
| 49 | |