From bc2f1cb89b58cb0fe2cbd2ebc3071edec489e832 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fernando=20M=C3=A9ndez?= <45081533+FerMdez@users.noreply.github.com> Date: Tue, 6 Apr 2021 21:14:59 +0200 Subject: [PATCH] Add files via upload --- assets/php/dao.php | 4 +- assets/php/user_dao.php | 19 ++- assets/php/user_dto.php | 4 +- assets/php/users_dto_interface.php | 4 +- login/includes/form.php | 240 +++++++++++++++++++++++++++++ login/includes/formLogin.php | 103 +++++++++++++ 6 files changed, 365 insertions(+), 9 deletions(-) create mode 100644 login/includes/form.php create mode 100644 login/includes/formLogin.php diff --git a/assets/php/dao.php b/assets/php/dao.php index 8ac12de..f5e9108 100644 --- a/assets/php/dao.php +++ b/assets/php/dao.php @@ -14,8 +14,8 @@ public function __construct($bd_name){ try{ if (!$this->mysqli) { - $this->mysqli = new mysqli(_SERVERNAME, _USERNAME, - _PASSWORD, $bd_name); + $this->mysqli = new mysqli("localhost", "sw", + "_admin_", $bd_name); } // echo "Conexión a la BD, satisfactoria."; } catch (Exception $e){ diff --git a/assets/php/user_dao.php b/assets/php/user_dao.php index d64960a..04726b3 100644 --- a/assets/php/user_dao.php +++ b/assets/php/user_dao.php @@ -1,4 +1,7 @@ mysqli, $sql) or die ('Error into query database'); + } + + //Returns a query to check if the user pass matches: + public function selectPass($password){ + $sql = sprintf( "SELECT * FROM users WHERE passwd = '%s'", $password ); + + //return $sql; + return $result = mysqli_query($this->mysqli, $sql) or die ('Error into query database'); } //Returns a query to get the user's data: public function userData($id){ $sql = sprintf( "SELECT * FROM users WHERE id = '%d'", $id ); - return $sql; + //return $sql; + return $result = mysqli_query($this->mysqli, $sql) or die ('Error into query database'); } //Create a new User Data Transfer Object: diff --git a/assets/php/user_dto.php b/assets/php/user_dto.php index 90cf9c2..4e882f3 100644 --- a/assets/php/user_dto.php +++ b/assets/php/user_dto.php @@ -30,8 +30,8 @@ public function getEmail(){ return $this->_email; } public function setPass($passwd){ $this->_password = $passwd; } public function getPass(){ return $this->_password; } - public function setRoles($rol){ $this->_rol = $rol; } - public function getRoles(){ return $this->_rol; } + public function setRol($rol){ $this->_rol = $rol; } + public function getRol(){ return $this->_rol; } } ?> \ No newline at end of file diff --git a/assets/php/users_dto_interface.php b/assets/php/users_dto_interface.php index f3cb728..6bfc7aa 100644 --- a/assets/php/users_dto_interface.php +++ b/assets/php/users_dto_interface.php @@ -8,7 +8,7 @@ public function getEmail(); public function setPass($passwd); public function getPass(); - public function setRoles($rol); - public function getRoles(); + public function setRol($rol); + public function getRol(); } ?> \ No newline at end of file diff --git a/login/includes/form.php b/login/includes/form.php new file mode 100644 index 0000000..5d7ba3f --- /dev/null +++ b/login/includes/form.php @@ -0,0 +1,240 @@ +formId = $formId; + + $opcionesPorDefecto = array( 'ajax' => false, 'action' => null, 'class' => null, 'enctype' => null ); + $opciones = array_merge($opcionesPorDefecto, $opciones); + + $this->ajax = $opciones['ajax']; + $this->action = $opciones['action']; + $this->classAtt = $opciones['class']; + $this->enctype = $opciones['enctype']; + + if ( !$this->action ) { + $this->action = $_SERVER['PHP_SELF']; + } + } + + public function gestiona() { + + if ( ! $this->formularioEnviado($_POST) ) { + echo $this->generaFormulario(); + } else { + // Valida el token CSRF si es necesario (hay un token en la sesión asociada al formulario) + $tokenRecibido = isset($_POST['CSRFToken']) ? $_POST['CSRFToken'] : FALSE; + + if ( ($errores = $this->csrfguard_ValidateToken($this->formId, $tokenRecibido)) !== TRUE ) { + if ( ! $this->ajax ) { + echo $this->generaFormulario($errores, $_POST); + } else { + echo $this->generaHtmlErrores($errores); + } + } else { + $result = $this->procesaFormulario($_POST); + if ( is_array($result) ) { + // Error al procesar el formulario, volvemos a mostrarlo + if ( ! $this->ajax ) { + echo $this->generaFormulario($result, $_POST); + } else { + echo $this->generaHtmlErrores($result); + } + } else { + if ( ! $this->ajax ) { + header('Location: '.$result); + } else { + echo $result; + } + } + } + } + } + + /** + * Devuelve un string con el HTML necesario para presentar los campos del formulario. Es necesario asegurarse que como parte del envío se envía un parámetro con nombre (i.e. utilizado como valor del atributo name del botón de envío del formulario). + */ + protected function generaCamposFormulario ($datos) { + return ''; + } + + /** + * Procesa los datos del formulario. + */ + protected function procesaFormulario($datos) { + + } + + /** + * Función que verifica si el usuario ha enviado el formulario. Comprueba si existe el parámetro $formId en $params. + * + * @param array $params Array que contiene los datos recibidos en el envío formulario. + * + * @return boolean Devuelve TRUE si $formId existe como clave en $params + */ + private function formularioEnviado(&$params) { + return isset($params['action']) && $params['action'] == $this->formId; + } + + /** + * Función que genera el HTML necesario para el formulario. + * + * + * @param array $errores (opcional) Array con los mensajes de error de validación y/o procesamiento del formulario. + * + * @param array $datos (opcional) Array con los valores por defecto de los campos del formulario. + */ + private function generaFormulario($errores = array(), &$datos = array()) { + + $html= $this->generaListaErrores($errores); + + $html .= '
classAtt ) { + $html .= ' class="'.$this->classAtt.'"'; + } + if ( $this->enctype ) { + $html .= ' enctype="'.$this->enctype.'"'; + } + $html .=' >'; + + // Se genera el token CSRF si el usuario no solicita explícitamente lo contrario. + if ( ! $this->classAtt || strpos($this->classAtt, 'nocsrf') === false ) { + $tokenValue = $this->csrfguard_GenerateToken($this->formId); + $html .= ''; + } + + $html .= ''; + + $html .= $this->generaCamposFormulario($datos); + $html .= '
'; + return $html; + } + + private function generaListaErrores($errores) { + $html=''; + $numErrores = count($errores); + if ( $numErrores == 1 ) { + $html .= ""; + } else if ( $numErrores > 1 ) { + $html .= ""; + } + return $html; + } + + private function csrfguard_GenerateToken($formId) { + if ( ! isset($_SESSION) ) { + throw new Exception('La sesión del usuario no está definida.'); + } + + if ( function_exists('hash_algos') && in_array('sha512', hash_algos()) ) { + $token = hash('sha512', mt_rand(0, mt_getrandmax())); + } else { + $token=' '; + for ($i=0;$i<128;++$i) { + $r=mt_rand(0,35); + if ($r<26){ + $c=chr(ord('a')+$r); + } else{ + $c=chr(ord('0')+$r-26); + } + $token.=$c; + } + } + + $_SESSION[$formId.'_'.self::CSRF_PARAM]=$token; + + return $token; + } + + private function csrfguard_ValidateToken($formId, $tokenRecibido) { + if ( ! isset($_SESSION) ) { + throw new Exception('La sesión del usuario no está definida.'); + } + + $result = TRUE; + + if ( isset($_SESSION[$formId.'_'.self::CSRF_PARAM]) ) { + if ( $_SESSION[$formId.'_'.self::CSRF_PARAM] !== $tokenRecibido ) { + $result = array(); + $result[] = 'Has enviado el formulario dos veces'; + } + $_SESSION[$formId.'_'.self::CSRF_PARAM] = ' '; + unset($_SESSION[$formId.'_'.self::CSRF_PARAM]); + } else { + $result = array(); + $result[] = 'Formulario no válido'; + } + return $result; + } +} +?> + + \ No newline at end of file diff --git a/login/includes/formLogin.php b/login/includes/formLogin.php new file mode 100644 index 0000000..31900fe --- /dev/null +++ b/login/includes/formLogin.php @@ -0,0 +1,103 @@ +reply = array(); + } + + //Methods: + + //Returns validation response: + public function getReply() { + + if(isset($_SESSION["login"])){ + $this->reply = "

Bienvenido {$_SESSION['nombre']}


+

{$_SESSION['nombre']} has iniciado sesión correctamente.

+

Usa los botones para navegar

+ + \n"; + } + else if(!isset($_SESSION["login"])){ + $this->reply = "

ERROR


". + "

El usuario o contraseña no son válidos.

+

Vuelve a intetarlo o regístrate si no lo habías hecho previamente.

+ +
\n"; + } + + return $this->reply; + } + + //Process form: + public function processesForm($name, $pass) { + $login = true; + $name = $this->test_input($name); + $pass = $this->test_input($pass); + + $username = isset($name) ? $name : null ; + if (!$username || !mb_ereg_match(self::HTML5_EMAIL_REGEXP, $username)) { + $login = false; + } + else{ + $login = true; + } + + $password = isset($pass) ? $pass : null ; + if (!$password || mb_strlen($password) < 4) { + $login = false; + } + else{ + $login = true; + } + + if ($login) { + $bd = new UserDAO('complucine'); + if($bd){ + $selectUser = $bd->selectUser($username); + if($selectUser){ + /* + while($row = mysqli_fetch_array($selectUser)){ + $id = $row['id']; + $username = $row['username']; + $email = $row['email']; + $password = $row['passwd']; + $rol = $row['rol']; + } + $this->user = $bd->loadUser($id, $username, $email, $password, $rol); + */ + //ARREGLAR LO DE ARRIBA Y BORRAR: + if($username == "admin") $this->user = $bd->loadUser("0", "admin", "admin@complucine.sytes.net", "adminpass", "admin"); + else if($username == "manager") $this->user = $bd->loadUser("1", "manager", "manager@complucine.sytes.net", "managerpass", "manager"); + else $this->user = $bd->loadUser("2", "user", "user@complucine.sytes.net", "userpass", "user"); + } + } + + if ($this->user->getName()) { + $_SESSION['user'] = $this->user; + $_SESSION["nombre"] = $this->user->getName(); + $_SESSION["login"] = $login; + $_SESSION["rol"] = $this->user->getRol(); + } + } + //mysqli_free_result($selectUser); + } + + protected function test_input($input){ + return htmlspecialchars(trim(strip_tags($input))); + } + + +} +?> \ No newline at end of file