Skip to content

Commit

Permalink
Introduciendo sesiones
Browse files Browse the repository at this point in the history
  • Loading branch information
parzibyte committed Jan 7, 2019
1 parent 9778976 commit cb1fc66
Show file tree
Hide file tree
Showing 7 changed files with 208 additions and 38 deletions.
12 changes: 12 additions & 0 deletions BD.php
Expand Up @@ -14,4 +14,16 @@ public static function obtener()
$bd->query("SET NAMES 'utf8'");
return $bd;
}
public static function obtenerParaSesion()
{
$bd = new PDO(
"mysql:host=" . Comun::env("HOST_MYSQL_SESION") . ";dbname=" . Comun::env("NOMBRE_BD_MYSQL_SESION"),
Comun::env("USUARIO_MYSQL_SESION"),
Comun::env("PASS_MYSQL_SESION")
);
$bd->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$bd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$bd->query("SET NAMES 'utf8'");
return $bd;
}
}
75 changes: 75 additions & 0 deletions Sesion.php
@@ -0,0 +1,75 @@
<?php
/*
Manejador de sesiones propio
Recuerda crear una tabla así:
CREATE TABLE IF NOT EXISTS sesiones(
id VARCHAR(255) NOT NULL PRIMARY KEY,
datos TEXT NOT NULL,
ultimo_acceso BIGINT UNSIGNED NOT NULL
);
@author parzibyte
@see parzibyte.me/blog
@date 2018-06-28
*/
class Sesion implements \SessionHandlerInterface
{

/**
* @var $base_de_datos \PDO
*/
private $base_de_datos; #Aquí vamos a guardar nuestra referencia a la base de datos

public function open($ruta_de_guardado, $nombre_de_sesion)
{
$this->base_de_datos = BD::obtenerParaSesion();
return true;
}

public function close()
{
#Eliminamos referencia a la base de datos
$this->base_de_datos = null;
return true;
}

public function write($id_de_sesion, $datos_de_sesion)
{
$ultimo_acceso = time();
$sentencia = $this->base_de_datos->prepare("REPLACE INTO sesiones (id, datos, ultimo_acceso) VALUES (?, ?, ?);");
return $sentencia->execute([$id_de_sesion, $datos_de_sesion, $ultimo_acceso]);
}

public function read($id_de_sesion)
{
$sentencia = $this->base_de_datos->prepare("SELECT datos FROM sesiones WHERE id = ?;");
$sentencia->execute([$id_de_sesion]);
# Recuperar como objeto (con PDO::FETCH_OBJ), para acceder a $fila->datos
$fila = $sentencia->fetch(PDO::FETCH_OBJ);

# Si no existen datos con ese id, fetch devuelve FALSE
if ($fila === false) {
return ""; # Cadena vacía
} else {
return $fila->datos;
}
}

public function destroy($id_de_sesion)
{
$sentencia = $this->base_de_datos->prepare("DELETE FROM sesiones WHERE id = ?;");
return $sentencia->execute([$id_de_sesion]);
}

public function gc($tiempo_de_vida)
{
#Calculamos el tiempo actual menos el tiempo de vida.
$caducidad = time() - $tiempo_de_vida;

$sentencia = $this->base_de_datos->prepare("DELETE FROM sesiones WHERE ultimo_acceso < ?;");
return $sentencia->execute([$caducidad]);
}

}
67 changes: 67 additions & 0 deletions SesionService.php
@@ -0,0 +1,67 @@
<?php

class SesionService
{

public static function escribir($clave, $datos, $sobrescribir = false)
{
self::init();
if (!isset($_SESSION[$clave]) || $sobrescribir) $_SESSION[$clave] = $datos;
}

/**
* Lee una variable almacenada en la sesión.
* Devuelve la variable, o null si no existe
* @param $clave
* @return mixed|null
*/
public static function leer($clave)
{
self::init();
return $_SESSION[$clave] ?? null;
}

private static function init()
{
if (!isset($_SESSION))
session_set_save_handler(new Sesion());
if (!self::laSesionEstaIniciada()) {
session_start();
session_regenerate_id(true);
}
}

public static function propagarIdUsuario($idUsuario)
{
self::init();
$_SESSION["idUsuario"] = $idUsuario;
}

public static function obtenerIdUsuarioLogueado()
{
self::init();
return $_SESSION["idUsuario"] ?? null;
}

public static function obtenerUsuarioLogueado()
{
$id = self::obtenerIdUsuarioLogueado();
if (isset($id)) {
return Usuarios::porId($id);
}
return null;
}

private static function laSesionEstaIniciada()
{
return session_status() === PHP_SESSION_ACTIVE ? true : false;
}

public static function cerrarSesion()
{
self::init();
session_start();
session_destroy();
}
}

10 changes: 3 additions & 7 deletions Utiles.php
Expand Up @@ -30,18 +30,14 @@ public static function esTokenCSRFValido($token)
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
return hash_equals($_SESSION["token_csrf"], $token);
return hash_equals(SesionService::leer("token_csrf"), $token);
}

public static function obtenerTokenCSRF()
{
# Sólo iniciamos la sesión si no la iniciamos antes
if (session_status() !== PHP_SESSION_ACTIVE) {
session_start();
}
$token = self::generar_token_seguro(40);
$_SESSION["token_csrf"] = $token;
return $_SESSION["token_csrf"];
SesionService::escribir("token_csrf", $token, true);
return SesionService::leer("token_csrf");
}

}
8 changes: 8 additions & 0 deletions env.ejemplo.php
Expand Up @@ -14,9 +14,17 @@
; Las líneas en blanco y aquellas que comienzan
; con un punto y coma (;) son ignoradas

; URL base del proyecto, algo como https://sitio.com
BASE_URL = "http://localhost/cotizaciones"


USUARIO_MYSQL = ""
PASS_MYSQL = ""
NOMBRE_BD_MYSQL = ""
HOST_MYSQL = ""


USUARIO_MYSQL_SESION = ""
PASS_MYSQL_SESION = ""
NOMBRE_BD_MYSQL_SESION = ""
HOST_MYSQL_SESION = ""
25 changes: 16 additions & 9 deletions index.php
@@ -1,7 +1,20 @@
<?php
date_default_timezone_set("America/Mexico_City");
define("BASE_URL", "http://localhost/cotizaciones");
define("BASE_PATH", __DIR__);

# Cargar todos los controladores y útiles

include_once BASE_PATH . "/BD.php";
include_once BASE_PATH . "/Utiles.php";
include_once BASE_PATH . "/Comun.php";
include_once BASE_PATH . "/Sesion.php";
include_once BASE_PATH . "/SesionService.php";
include_once BASE_PATH . "/controllers/Clientes.php";
include_once BASE_PATH . "/controllers/Cotizaciones.php";
include_once BASE_PATH . "/controllers/Ajustes.php";
include_once BASE_PATH . "/controllers/Usuarios.php";

define("BASE_URL", Comun::env("BASE_URL"));
define("LISTA_BLANCA_PAGINAS", [
# Clientes
"clientes", "nuevo_cliente", "guardar_cliente",
Expand All @@ -24,20 +37,14 @@
"editar_ajustes", "actualizar_ajustes",
# Acerca de
"creditos",
"login", "registro", "guardar_usuario",
"iniciar_sesion", "logout",
]);
$pagina = $_GET["p"] ?? "cotizaciones";
if (!in_array($pagina, LISTA_BLANCA_PAGINAS)) {
exit("No permitido. Este incidente será reportado");
}

# Cargar todos los controladores y útiles

include_once BASE_PATH . "/BD.php";
include_once BASE_PATH . "/Utiles.php";
include_once BASE_PATH . "/Comun.php";
include_once BASE_PATH . "/controllers/Clientes.php";
include_once BASE_PATH . "/controllers/Cotizaciones.php";
include_once BASE_PATH . "/controllers/Ajustes.php";

# Ahora la vista
include_once BASE_PATH . "/encabezado.php";
Expand Down
49 changes: 27 additions & 22 deletions navegacion.php
@@ -1,25 +1,30 @@
<?php if(SesionService::obtenerIdUsuarioLogueado() !== NULL){ ?>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="<?php echo BASE_URL ?>">Cotizaciones</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
aria-controls="navbarNav"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item <?php echo $_GET["p"] === "clientes" ? 'active' : '' ?>">
<a class="nav-link" href="<?php echo BASE_URL ?>/?p=clientes">Clientes</a>
</li>
<li class="nav-item <?php echo $_GET["p"] === "cotizaciones" ? 'active' : '' ?>">
<a class="nav-link" href="<?php echo BASE_URL ?>/?p=cotizaciones">Cotizaciones</a>
</li>
<li class="nav-item <?php echo $_GET["p"] === "editar_ajustes" ? 'active' : '' ?>">
<a class="nav-link" href="<?php echo BASE_URL ?>/?p=editar_ajustes">Ajustes</a>
</li>
<li class="nav-item <?php echo $_GET["p"] === "creditos" ? 'active' : '' ?>">
<a class="nav-link" href="<?php echo BASE_URL ?>/?p=creditos">Acerca de</a>
</li>
</ul>
</div>
<a class="navbar-brand" href="<?php echo BASE_URL ?>">Cotizaciones</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav"
aria-controls="navbarNav"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav">
<li class="nav-item <?php echo $_GET["p"] === "clientes" ? 'active' : '' ?>">
<a class="nav-link" href="<?php echo BASE_URL ?>/?p=clientes">Clientes</a>
</li>
<li class="nav-item <?php echo $_GET["p"] === "cotizaciones" ? 'active' : '' ?>">
<a class="nav-link" href="<?php echo BASE_URL ?>/?p=cotizaciones">Cotizaciones</a>
</li>
<li class="nav-item <?php echo $_GET["p"] === "editar_ajustes" ? 'active' : '' ?>">
<a class="nav-link" href="<?php echo BASE_URL ?>/?p=editar_ajustes">Ajustes</a>
</li>
<li class="nav-item <?php echo $_GET["p"] === "creditos" ? 'active' : '' ?>">
<a class="nav-link" href="<?php echo BASE_URL ?>/?p=creditos">Acerca de</a>
</li>
<li class="nav-item">
<a class="nav-link" href="<?php echo BASE_URL ?>/?p=logout">Salir (<?php echo htmlentities(SesionService::obtenerUsuarioLogueado()->correo) ?>)</a>
</li>
</ul>
</div>
</nav>
<?php } ?>
<div class="container">

0 comments on commit cb1fc66

Please sign in to comment.