Last active
August 29, 2015 14:02
-
-
Save fastcodecoq/f38761111cfe87c0f5be to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // require_once("/ruta/al/archivo/config.inc"); | |
| class auth{ | |
| protected $db; | |
| public function __construct(){ | |
| $this->db = new mysqli(db_host, db_user, db_pass, db_bd); | |
| } | |
| function auth(){ | |
| $email = $_POST['email']; | |
| $_email = md5($email); | |
| $clave = $_POST['clave']; | |
| // _email es un campo en la tabla usuarios que corresponde al mail en md5 | |
| // es un metodo para evitarnos ataques en el login a la base de datos | |
| $usr = $this->db->query("SELECT clave, nombre FROM usuarios WHERE _email = '{$_email}' LIMIT 1") or die($this->db->error); | |
| //si el query arroja mas de una fila, procederemos a validar si las claves coinciden | |
| if($usr->num_rows > 0){ | |
| $usr = $usr->fetch_assoc(); | |
| //hacemos el hash del password. Este mismo hash se usa al momento del registro | |
| $clave = password_hash($clave, PASSWORD_BCRYPT, array('cost' => 12)); | |
| if($usr['clave'] === $clave) | |
| { | |
| // el usuario es valido | |
| // procedemos a crear un token | |
| $now = time(); | |
| $token = $_SERVER['HTTP_USER_AGENT'] . $email . $now; | |
| for($i = 0; $i < 5; $i++) | |
| $token = hash($token . rand(5,75)); | |
| $this->db->query("UPDATE usuarios SET ultimo_ingreso = '{$now}' WHERE _email = '{$_email}'"); | |
| $cred = $this->db->query("SELECT id FROM credenciales WHERE usr = {$_email}"); | |
| //si el usuario seleccionó recordar | |
| //colocamos el token con tiempo de vida infinito | |
| //sino solo le damos 30 mins de vida | |
| $ttl = isset($_POST['recordar']) ? 'infinito' : $now + 1800; | |
| if($cred->num_rows > 0) | |
| $this->db->query("UPDATE credenciales SET token='{$token}', ttl='{$ttl}' WHERE usr = '{$_email}'"); | |
| else | |
| $this->db->query("INSERT INTO credenciales (usr, token, ttl) VALUES ({$_email}, {$token}, {$ttl})"); | |
| $this->db->close(); | |
| //hemos hecho todas las validaciones ahora redirigmos y enviamos en la URL el token + email | |
| echo "<script>document.location = '/?auth=true&token={$token}&usr={$email}'; </script>"; | |
| }else | |
| echo "<script>document.location = '/auth=false'; </script>"; //no es un usuario valido | |
| }else | |
| echo "<script>document.location = '/auth=false'; </script>"; //no es un usuario valido | |
| // adjunto .SQL (MySQL dump) de las tablas implicadas. El resto les corresponde a ustedes: (:p) | |
| // hacer un controlador con los siguientes metodos: | |
| // 1. protected token_expiro: debe verificar si un token no ha expirado | |
| // 2. protected refrescar_token: debe refrescar un token. | |
| // 3. public verificar_token: debe verificar que un token no corresponde a un usuario, ... | |
| // ... luego debe implementar el metodo token_expiro para validar que aun puede ser usado ... | |
| // ... y por ultimo si el token aun estaba en tiempo de vida, debe refrescarlo, en caso de ... | |
| // ... que no tenga tiempo de vida (ttl) infinito | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- Adminer 3.7.1 MySQL dump | |
| SET NAMES utf8; | |
| SET foreign_key_checks = 0; | |
| SET time_zone = '-05:00'; | |
| SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO'; | |
| DROP TABLE IF EXISTS `credenciales`; | |
| CREATE TABLE `credenciales` ( | |
| `id` int(11) NOT NULL AUTO_INCREMENT, | |
| `token` varchar(60) NOT NULL, | |
| `usr` varchar(45) NOT NULL, | |
| `ttl` time NOT NULL, | |
| PRIMARY KEY (`id`) | |
| ) ENGINE=InnoDB DEFAULT CHARSET=utf8; | |
| DROP TABLE IF EXISTS `usuarios`; | |
| CREATE TABLE `usuarios` ( | |
| `id` int(11) NOT NULL AUTO_INCREMENT, | |
| `nombre` varchar(45) NOT NULL, | |
| `email` varchar(45) NOT NULL, | |
| `_email` varchar(45) NOT NULL, | |
| `clave` varchar(60) NOT NULL, | |
| `permisos` varchar(500) NOT NULL, | |
| `fecha_creacion` date NOT NULL, | |
| `ultimo_ingreso` date NOT NULL, | |
| `clave_pendiente` int(11) NOT NULL DEFAULT '1', | |
| PRIMARY KEY (`id`) | |
| ) ENGINE=InnoDB DEFAULT CHARSET=utf8; | |
| INSERT INTO `usuarios` (`id`, `nombre`, `email`, `_email`, `clave`, `permisos`, `fecha_creacion`, `ultimo_ingreso`, `clave_pendiente`) VALUES | |
| (1, 'Javier Gomez', '[email protected]', '4625b7438f7462a568bc4fa87aac127f', '2fd0a0c53a0b06cbd51f46ff8a611165', '{\'inventario\':\'r-\', \'reportes\':\'--\',\'usuarios\':\'rw\',\'facturacion\':\'r-\',\'clientes\':\'rw\', \'info_empresa\':\'rw\'}', '2014-06-21', '0000-00-00', -1); | |
| -- 2014-06-21 10:50:26 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // require_once("/ruta/al/archivo/config.inc"); | |
| class usuarios{ | |
| protected $db; | |
| public function __construct(){ | |
| $this->db = new mysqli(db_host, db_user, db_pass, db_bd); | |
| } | |
| public function crear(){ | |
| $email = $_POST['email']; | |
| foreach ($_POST as $key => $val) | |
| $_POST[$key] = "'" . addslashes(htmlentities($val, null, 'UTF-8')) . "'"; | |
| $vals = array(); | |
| if(!isset($_POST['clave'])) | |
| { | |
| $vals['nombre'] = $_POST['nombre']; | |
| $vals['email'] = $_POST['email']; | |
| $vals['_email'] = md5($_POST['email']); | |
| $vals['permisos'] = $_POST['permisos']; | |
| }else{ | |
| $vals['nombre'] = $_POST['nombre']; | |
| $vals['clave'] = password_hash($_POST['clave'], PASSWORD_BCRYPT, array('cost' => 12)); | |
| $vals['email'] = $_POST['email']; | |
| $vals['_email'] = md5($_POST['email']); | |
| $vals['permisos'] = $_POST['permisos']; | |
| $vals['clave_pendiente'] = -1; | |
| } | |
| $vals["fecha_creacion"] = date("Y-d-m"); | |
| $vals = implode(',', $vals); | |
| $_usr = $this->db->query("SELECT id FROM usuarios WHERE email = {$_POST['email']}"); | |
| if($_usr->num_rows > 0) | |
| { | |
| echo json_encode(array('error' => true, 'message' => 'usuario_duplicado')); | |
| die; | |
| } | |
| if(!isset($_POST['clave'])) | |
| $query = "INSERT INTO usuarios (nombre, email, _email, permisos, fecha_creacion) VALUES ({$vals})"; | |
| else | |
| $query = "INSERT INTO usuarios (nombre, clave, email, _email, permisos, clave_pendiente, fecha_creacion) VALUES ({$vals})"; | |
| $this->db->query($query) or die($this->db->error); | |
| if($this->db->affected_rows > 0) | |
| echo json_encode(array('error' => false, 'message' => 'usuario_creado', 'usuarios' => $this->get())); | |
| else | |
| echo json_encode(array('error' => true, 'message' => 'usuario_no_creado', 'usuarios' => $this->get())); | |
| $this->db->close(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment