1 | <?php |
2 | |
3 | function creaToken(string $pagina, int $duracionEnMinutos) |
4 | { |
5 | $criptografiaFuerte = true; |
6 | |
7 | // Crea el token |
8 | $token = [ |
9 | "expiracion" => time() + 60 * $duracionEnMinutos, |
10 | // El token es de 80 caracteres, criptográficamente fuerte. |
11 | "texto" => bin2hex(openssl_random_pseudo_bytes(80, $criptografiaFuerte)) |
12 | ]; |
13 | |
14 | // Verifica que ya haya tokens $pagina. |
15 | if (isset($_SESSION[$pagina])) { |
16 | |
17 | $tokensParaPagina = $_SESSION[$pagina]; |
18 | |
19 | // Como ya existe el arreglo, elimina los tokens expirados para esta pagina. |
20 | foreach ($tokensParaPagina as $llave => $tokenParaPagina) { |
21 | if ($tokenParaPagina["expiracion"] > time()) { |
22 | unset($tokensParaPagina[$llave]); |
23 | } |
24 | } |
25 | |
26 | // Se puede usar uno o varios tokens por pagina. |
27 | $tokensParaPagina[] = $token; |
28 | $_SESSION[$pagina] = $tokensParaPagina; |
29 | } else { |
30 | |
31 | // Se puede usar uno o varios tokens por pagina |
32 | $_SESSION[$pagina] = [$token]; |
33 | } |
34 | |
35 | return $token["texto"]; |
36 | } |
37 |
1 | <?php |
2 | |
3 | require_once __DIR__ . "/JsonResponse.php"; |
4 | require_once __DIR__ . "/ProblemDetails.php"; |
5 | |
6 | /** |
7 | * Ejecuta una funcion que implementa un servicio. |
8 | */ |
9 | function ejecutaServicio($servicio) |
10 | { |
11 | try { |
12 | $resultado = $servicio(); |
13 | if (!($resultado instanceof JsonResponse)) { |
14 | $resultado = JsonResponse::ok($resultado); |
15 | } |
16 | procesa_json_response($resultado); |
17 | } catch (ProblemDetails $details) { |
18 | procesa_problem_details($details); |
19 | } catch (Throwable $throwable) { |
20 | procesa_problem_details(new ProblemDetails( |
21 | status: ProblemDetails::InternalServerError, |
22 | type: "/error/errorinterno.html", |
23 | title: "Error interno del servidor.", |
24 | detail: $throwable->getMessage() |
25 | )); |
26 | } |
27 | } |
28 | |
29 | function procesa_json_response(JsonResponse $response) |
30 | { |
31 | $json = ""; |
32 | $body = $response->body; |
33 | if ($response->status !== JsonResponse_NoContent) { |
34 | $json = json_encode($body); |
35 | if ($json === false) { |
36 | no_puede_generar_json(); |
37 | return; |
38 | } |
39 | } |
40 | http_response_code($response->status); |
41 | if ($response->location !== null) { |
42 | header("Location: {$response->location}"); |
43 | } |
44 | if ($response->status !== JsonResponse_NoContent) { |
45 | header("Content-Type: application/json"); |
46 | echo $json; |
47 | } |
48 | } |
49 | |
50 | function procesa_problem_details(ProblemDetails $details) |
51 | { |
52 | $body = ["title" => $details->title]; |
53 | if ($details->type !== null) { |
54 | $body["type"] = $details->type; |
55 | } |
56 | if ($details->detail !== null) { |
57 | $body["detail"] = $details->detail; |
58 | } |
59 | $json = json_encode($body); |
60 | if ($json === false) { |
61 | no_puede_generar_json(); |
62 | } else { |
63 | http_response_code($details->status); |
64 | header("Content-Type: application/problem+json"); |
65 | echo $json; |
66 | } |
67 | } |
68 | |
69 | function no_puede_generar_json() |
70 | { |
71 | http_response_code(ProblemDetails::InternalServerError); |
72 | header("Content-Type: application/problem+json"); |
73 | echo '{"type":"/error/nojson.html"' |
74 | . ',"title":"El valor devuelto no puede representarse como JSON."}'; |
75 | } |
76 |
1 | <?php |
2 | |
3 | const JsonResponse_OK = 200; |
4 | const JsonResponse_Created = 201; |
5 | const JsonResponse_NoContent = 204; |
6 | |
7 | class JsonResponse |
8 | { |
9 | |
10 | public int $status; |
11 | public $body; |
12 | public ?string $location; |
13 | |
14 | public function __construct( |
15 | int $status = JsonResponse_OK, |
16 | $body = null, |
17 | ?string $location = null |
18 | ) { |
19 | $this->status = $status; |
20 | $this->body = $body; |
21 | $this->location = $location; |
22 | } |
23 | |
24 | public static function ok($body) |
25 | { |
26 | return new JsonResponse(body: $body); |
27 | } |
28 | |
29 | public static function created(string $location, $body) |
30 | { |
31 | return new JsonResponse(JsonResponse_Created, $body, $location); |
32 | } |
33 | |
34 | public static function noContent() |
35 | { |
36 | return new JsonResponse(JsonResponse_NoContent, null); |
37 | } |
38 | } |
39 |
1 | <?php |
2 | |
3 | /** |
4 | * Recupera el texto de un parámetro enviado al |
5 | * servidor por medio de GET, POST o cookie. |
6 | * Si el parámetro no se recibe, devuelve null. |
7 | */ |
8 | function leeTexto(string $parametro): ?string |
9 | { |
10 | /* Si el parámetro está asignado en $_REQUEST, |
11 | * devuelve su valor; de lo contrario, |
12 | * devuelve null. */ |
13 | $valor = isset($_REQUEST[$parametro]) |
14 | ? $_REQUEST[$parametro] |
15 | : null; |
16 | return $valor; |
17 | } |
18 |
1 | <?php |
2 | |
3 | class ProblemDetails extends Exception |
4 | { |
5 | |
6 | public const BadRequest = 400; |
7 | public const NotFound = 404; |
8 | public const InternalServerError = 500; |
9 | |
10 | public int $status; |
11 | public string $title; |
12 | public ?string $type; |
13 | public ?string $detail; |
14 | |
15 | public function __construct( |
16 | int $status, |
17 | string $title, |
18 | ?string $type = null, |
19 | ?string $detail = null, |
20 | Throwable $previous = null |
21 | ) { |
22 | parent::__construct($title, $status, $previous); |
23 | $this->status = $status; |
24 | $this->type = $type; |
25 | $this->title = $title; |
26 | $this->detail = $detail; |
27 | } |
28 | } |
29 |
1 | <?php |
2 | |
3 | require_once __DIR__ . "/ProblemDetails.php"; |
4 | |
5 | const FORBIDDEN = 403; |
6 | |
7 | function 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 |