commit 4f9ea1dbfd4d6038eed3f44d2512277a4846aa77 Author: devfzn Date: Fri Mar 24 12:41:27 2023 -0300 init php rest api diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..191cbbf --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +pruebas/ +config diff --git a/.htaccess b/.htaccess new file mode 100644 index 0000000..ed19066 --- /dev/null +++ b/.htaccess @@ -0,0 +1 @@ +RedirectMatch 404 /\.git diff --git a/README.md b/README.md new file mode 100644 index 0000000..5626e87 --- /dev/null +++ b/README.md @@ -0,0 +1,98 @@ +# Apuntes PHP REST API + +### Requerimientos + +[MariaDB](https://mariadb.com/docs/), [Apache](https://httpd.apache.org/docs/) +y [PHP](https://www.php.net/docs.php). Opcional +[PhpMyAdmin](https://docs.phpmyadmin.net/en/latest/) + +```sh +sudo apt install mariadb-server apache2 php-mysql python3-mysqldb php php-cli \ + php-curl php-gd php-json php-mbstring php-mysql php-zip + +# opcional +sudo apt install phpmyadmin +``` + +```sh +sudo systemctl enable mysql +``` + +### Configuracion Apache2 + +#### Agregar user a www-data + +```sh +sudo usermod -a -G www-data $USER +``` + +#### Crear regla + +Ejemplo usando symlink `html` a `$HOME/projects/apirest` en vez de usar el +directorio `/var/www/html`. + +```sh +cd /var/www/ +sudo ln -s $HOME/projects/apirest html +``` + +`/etc/apache2/apache2.conf` + +```apache + + Options Indexes FollowSymLinks + AllowOverride All + Require all granted + + +# Para usar phpmyadmin, agregar al final +Include /etc/phpmyadmin/apache.conf +``` + +#### Activar modulo rewrite + +Para usar `.htaccess` específico del proyecto. + +```sh +sudo a2enmod rewrite +sudo systemctl restart apache2 +``` + +> ¿Como mostrar errores en php? [stackoverflow](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display). + +Agregar la sgte. linea en `.htaccess` + +```apache +php_flag display_errors 1 +``` + +O modifcar el/los parametro(s) en `/etc/php/8.1/php.ini` + +```apache +error_reporting = E_ALL +display_errors = On +``` + +#### Extension RESTED para Firefox + +![img](./imgs/firefox_rested_extension.png) + +---- + +### Inicio del proyecto + +Crear y poblar base de datos, según archivo `./original/database/apirest.sql`. + +Crear archivo de configuración en la ruta `.//clases/conexion/config`. + +```json +{ + "conexion":{ + "server" : "127.0.0.1", + "user" : "", + "password" : "", + "database" : "apirest", + "port" : "3306" + } +} +``` diff --git a/apirest_yt/.htaccess b/apirest_yt/.htaccess new file mode 100644 index 0000000..4263238 --- /dev/null +++ b/apirest_yt/.htaccess @@ -0,0 +1,19 @@ +php_flag display_errors 1 + +FallbackResource /index.php +RewriteEngine On + +# Si el archivo existe no es necesario especificar extension ".php" +RewriteCond %{REQUEST_FILENAME} !-d +RewriteCond %{REQUEST_FILENAME}.php -f +RewriteRule ^(.*)$ $1.php + +# Si el archivo existe no es necesario especificar extension ".html" +RewriteCond %{REQUEST_FILENAME} !-d +RewriteCond %{REQUEST_FILENAME}.html -f +RewriteRule ^(.*)$ $1.html + +# Si la ruta no existe redirige al index +RewriteCond %{REQUEST_FILENAME} !-f +RewriteCond %{REQUEST_FILENAME} !-d +RewriteRule ^(.+?)/?$ index.php?url=$1 [L,QSA] diff --git a/apirest_yt/auth.php b/apirest_yt/auth.php new file mode 100644 index 0000000..f315df6 --- /dev/null +++ b/apirest_yt/auth.php @@ -0,0 +1,29 @@ +login($postBody); + // respuesta + header('Content-Type: application/json'); + if(isset($datosArray["result"]["error_id"])){ + $responseCode = $datosArray["result"]["error_id"]; + http_response_code($responseCode); + }else{ + http_response_code(200); + } + echo json_encode($datosArray); +}else{ + header('Content-Type: application/json'); + $datosArray = $_respuestas->error_405(); + echo json_encode($datosArray); +} + +?> diff --git a/apirest_yt/clases/auth.class.php b/apirest_yt/clases/auth.class.php new file mode 100644 index 0000000..d29d97a --- /dev/null +++ b/apirest_yt/clases/auth.class.php @@ -0,0 +1,68 @@ +error_400(); + } else { + // echo "ok"; + $usuario = $datos['usuario']; + $password = $datos['password']; + $datos = $this->obtenerDatosUsuario($usuario); + if ($datos){ + // Usuario existe + //print_r($datos); + } else { + // Usuario no existe + //echo "Usuario no existe"; + // return $_respuestas->error_400(); + return $_respuestas->error_200("No existe el usuario $usuario"); + } + } + } + + private function obtenerDatosUsuario($correo){ + $query = "SELECT UsuarioID,Password,Estado FROM usuarios WHERE Usuario = '$correo'"; + # Llamado a método de clase padre + $datos = parent::obtenerDatos($query); + if(isset($datos[0]["UsuarioID"])){ + return $datos; + } else { + return 0; + } + } + +} + +?> + + + + + + + + + + + + + + + + + + + + + + + diff --git a/apirest_yt/clases/conexion/conexion.php b/apirest_yt/clases/conexion/conexion.php new file mode 100644 index 0000000..3bf1aca --- /dev/null +++ b/apirest_yt/clases/conexion/conexion.php @@ -0,0 +1,102 @@ +debug){ echo '
'."En constructor clase conexion".'
'; } + + $listadatos = $this->datosConexion(); + foreach ($listadatos as $key => $value) { + $this->server = $value['server']; + $this->user = $value['user']; + $this->password = $value['password']; + $this->database = $value['database']; + $this->port = $value['port']; + } + + if ($this->debug){ echo "datos constructor: SERVER: $this->server, USER: $this->user, + PASS: $this->password, DB: $this->database, PORT: $this->port".'
';} + + if ($this->debug){ echo '
'."pre conector".'
'; } + try { + $conn = new mysqli("$this->server","$this->user","$this->password","$this->database","$this->port"); + $this->conector = $conn; + if ($this->debug){ echo "todo BIEN con la conexion"; } + } catch (Exception $e) { + echo '
'."Error al intentar conectar con base de datos!".'
'; + echo "connect_errno: [$conn->connect_errno]".'
'; + echo "connect_error: [$conn->connect_error]".'
'; + echo "Exception: $e".'
'; + die(); + } + if ($this->debug){ echo '
'."post conector".'
'; } + + } + + private function datosConexion(){ + if ($this->debug){ echo '
'."En funcion datosConexion".'
'; } + + $ruta = dirname(__FILE__); + $jsondata = file_get_contents($ruta . "/" . "config"); + + if ($this->debug){ echo '
'."Ruta: $ruta".'
'.'
'; print_r($jsondata); echo '
'.'
'; } + + return json_decode($jsondata, true); + } + + private function convertirUTF8($array){ + if ($this->debug){ echo '
'."En funcion convertirUTF8".'
'; } + array_walk_recursive($array,function(&$item,$key){ + if(!mb_detect_encoding($item,'utf-8',true)){ + $item = utf8_encode($item); + } + }); + return $array; + } + + public function obtenerDatos($query){ + if ($this->debug){ echo '
'."En funcion obtenerDatos".'
'; } + $results = $this->conector->query($query); + $resultsArray = array(); + foreach ($results as $value) { + $resultsArray[] = $value; + } + if ($this->debug){ echo '
'; print_r($resultsArray); echo '
'.'
'; } + return $this->convertirUTF8($resultsArray); + } + + public function test_conector(){ + echo '
'."Funcion test_conector".'
'; + } + + public function nonQuery($sqlstr){ + $results = $this->conector->query($sqlstr); + #return $results->affected_rows; + return $this->conector->affected_rows; + } + + // INSERT + public function nonQueryId($sqlstr){ + $results = $this->conector->query($sqlstr); + $filas = $this->conector->affected_rows; + if ($filas >= 1){ + #return $results->insert_id; + return $this->conector->insert_id; + } else { + return 0; + } + } +} +?> + + + diff --git a/apirest_yt/clases/respuestas.class.php b/apirest_yt/clases/respuestas.class.php new file mode 100644 index 0000000..b7c2e3b --- /dev/null +++ b/apirest_yt/clases/respuestas.class.php @@ -0,0 +1,37 @@ + "ok", + "result" => array() + ]; + + public function error_405(){ + $this->response['status'] = "error"; + $this->response['result'] = array( + "error_id" => "405", + "error_msg" => "Metodo no permitido" + ); + return $this->response; + } + + public function error_200($mensaje = "Datos incorrectos"){ + $this->response['status'] = "error"; + $this->response['result'] = array( + "error_id" => "200", + "error_msg" => $mensaje + ); + return $this->response; + } + + public function error_400(){ + $this->response['status'] = "error"; + $this->response['result'] = array( + "error_id" => "400", + "error_msg" => "Datos recibidos incompletos o formato erroneo" + ); + return $this->response; + } +} + +?> diff --git a/apirest_yt/index.php b/apirest_yt/index.php new file mode 100644 index 0000000..e7d88d7 --- /dev/null +++ b/apirest_yt/index.php @@ -0,0 +1,20 @@ +'; + +require_once "clases/conexion/conexion.php"; + +$conector = new conexion; + +#$conector->test_conector(); + +// Prueba Select +#$query = "SELECT * FROM pacientes"; +#echo '
'; print_r($conector->obtenerDatos($query)); echo '
'; + +// Prueba insert +#$query = "INSERT INTO pacientes (DNI)value('0')"; +#echo '
'; print_r($conector->nonQuery($query)); echo '
'; +#$query = "INSERT INTO pacientes (DNI)value('1')"; +#echo '
'; print_r($conector->nonQueryId($query)); echo '
'; + +?> diff --git a/imgs/firefox_rested_extension.png b/imgs/firefox_rested_extension.png new file mode 100644 index 0000000..1ffaf6f Binary files /dev/null and b/imgs/firefox_rested_extension.png differ diff --git a/original/.htaccess b/original/.htaccess new file mode 100644 index 0000000..6f5672f --- /dev/null +++ b/original/.htaccess @@ -0,0 +1,19 @@ +#php_flag display_errors 1 +RewriteEngine On + +# esta lineas son para quitar la ext .php +RewriteCond %{REQUEST_FILENAME} !-d +RewriteCond %{REQUEST_FILENAME}.php -f +RewriteRule ^(.*)$ $1.php + +# esta lineas son para quitar la ext .html +RewriteCond %{REQUEST_FILENAME} !-d +RewriteCond %{REQUEST_FILENAME}.html -f +RewriteRule ^(.*)$ $1.html + + +# Si la ruta no es un archivo existente, ni una carpeta +# Reescribir al index +RewriteCond %{REQUEST_FILENAME} !-f +RewriteCond %{REQUEST_FILENAME} !-d +RewriteRule ^(.+?)/?$ index.php?url=$1 [L,QSA] diff --git a/original/assets/estilo.css b/original/assets/estilo.css new file mode 100644 index 0000000..4d2228a --- /dev/null +++ b/original/assets/estilo.css @@ -0,0 +1,63 @@ +body{ + color:black; + } + + + + .container { + margin: 10px; + border: 1px solid #D0D0D0; + box-shadow: 0 0 8px #D0D0D0; + } + h1{ + color: #444; + background-color: transparent; + border-bottom: 1px solid #D0D0D0; + font-size: 24px; + font-weight: normal; + margin: 0 0 14px 0; + padding: 14px 15px 10px 15px; + } + + h2 { + display: block; + font-size: 1.5em; + -webkit-margin-before: 0.83em; + -webkit-margin-after: 0.83em; + -webkit-margin-start: 0px; + -webkit-margin-end: 0px; + font-weight: bold; + } + + p { + display: block; + -webkit-margin-before: 1em; + -webkit-margin-after: 1em; + -webkit-margin-start: 0px; + -webkit-margin-end: 0px; + } + + + .divbody{ + margin: 0 15px 0 15px; + } + + p.divfooter { + text-align: right; + font-size: 16px; + border-top: 1px solid #D0D0D0; + line-height: 32px; + padding: 0 10px 0 10px; + margin: 20px 0 0 0; + } + + code { + font-family: Consolas, Monaco, Courier New, Courier, monospace; + font-size: 16px; + background-color: #f9f9f9; + border: 1px solid #D0D0D0; + color: #002166; + display: block; + margin: 14px 0 14px 0; + padding: 12px 10px 12px 10px; + } \ No newline at end of file diff --git a/original/auth.php b/original/auth.php new file mode 100644 index 0000000..82ccc8b --- /dev/null +++ b/original/auth.php @@ -0,0 +1,29 @@ +login($postBody); + //delvolvemos una respuesta + header('Content-Type: application/json'); + if(isset($datosArray["result"]["error_id"])){ + $responseCode = $datosArray["result"]["error_id"]; + http_response_code($responseCode); + }else{ + http_response_code(200); + } + echo json_encode($datosArray); +}else{ + header('Content-Type: application/json'); + $datosArray = $_respuestas->error_405(); + echo json_encode($datosArray); +} + +?> diff --git a/original/clases/auth.class.php b/original/clases/auth.class.php new file mode 100644 index 0000000..95632cc --- /dev/null +++ b/original/clases/auth.class.php @@ -0,0 +1,86 @@ +error_400(); + }else{ + //todo esta bien + $usuario = $datos['usuario']; + $password = $datos['password']; + $password = parent::encriptar($password); + $datos = $this->obtenerDatosUsuario($usuario); + if($datos){ + //verificar si la contraseña es igual + if($password == $datos[0]['Password']){ + if($datos[0]['Estado'] == "Activo"){ + //crear el token + $verificar = $this->insertarToken($datos[0]['UsuarioId']); + if($verificar){ + // si se guardo + $result = $_respustas->response; + $result["result"] = array( + "token" => $verificar + ); + return $result; + }else{ + //error al guardar + return $_respustas->error_500("Error interno, No hemos podido guardar"); + } + }else{ + //el usuario esta inactivo + return $_respustas->error_200("El usuario esta inactivo"); + } + }else{ + //la contraseña no es igual + return $_respustas->error_200("El password es invalido"); + } + }else{ + //no existe el usuario + return $_respustas->error_200("El usuaro $usuario no existe "); + } + } + } + + + + private function obtenerDatosUsuario($correo){ + $query = "SELECT UsuarioId,Password,Estado FROM usuarios WHERE Usuario = '$correo'"; + $datos = parent::obtenerDatos($query); + if(isset($datos[0]["UsuarioId"])){ + return $datos; + }else{ + return 0; + } + } + + + private function insertarToken($usuarioid){ + $val = true; + $token = bin2hex(openssl_random_pseudo_bytes(16,$val)); + $date = date("Y-m-d H:i"); + $estado = "Activo"; + $query = "INSERT INTO usuarios_token (UsuarioId,Token,Estado,Fecha)VALUES('$usuarioid','$token','$estado','$date')"; + $verifica = parent::nonQuery($query); + if($verifica){ + return $token; + }else{ + return 0; + } + } + + +} + + + + +?> \ No newline at end of file diff --git a/original/clases/conexion/conexion.php b/original/clases/conexion/conexion.php new file mode 100644 index 0000000..41faf80 --- /dev/null +++ b/original/clases/conexion/conexion.php @@ -0,0 +1,92 @@ +datosConexion(); + foreach ($listadatos as $key => $value) { + $this->server = $value['server']; + $this->user = $value['user']; + $this->password = $value['password']; + $this->database = $value['database']; + $this->port = $value['port']; + } + $this->conexion = new mysqli($this->server,$this->user,$this->password,$this->database,$this->port); + if($this->conexion->connect_errno){ + echo "algo va mal con la conexion"; + die(); + } + + } + + private function datosConexion(){ + $direccion = dirname(__FILE__); + $jsondata = file_get_contents($direccion . "/" . "config"); + return json_decode($jsondata, true); + } + + + private function convertirUTF8($array){ + array_walk_recursive($array,function(&$item,$key){ + if(!mb_detect_encoding($item,'utf-8',true)){ + $item = utf8_encode($item); + } + }); + return $array; + } + + + public function obtenerDatos($sqlstr){ + $results = $this->conexion->query($sqlstr); + $resultArray = array(); + foreach ($results as $key) { + $resultArray[] = $key; + } + return $this->convertirUTF8($resultArray); + + } + + + + public function nonQuery($sqlstr){ + $results = $this->conexion->query($sqlstr); + return $this->conexion->affected_rows; + } + + + //INSERT + public function nonQueryId($sqlstr){ + $results = $this->conexion->query($sqlstr); + $filas = $this->conexion->affected_rows; + if($filas >= 1){ + return $this->conexion->insert_id; + }else{ + return 0; + } + } + + //encriptar + + protected function encriptar($string){ + return md5($string); + } + + + + + +} + + + +?> \ No newline at end of file diff --git a/original/clases/pacientes.class.php b/original/clases/pacientes.class.php new file mode 100644 index 0000000..0426cb5 --- /dev/null +++ b/original/clases/pacientes.class.php @@ -0,0 +1,232 @@ + 1){ + $inicio = ($cantidad * ($pagina - 1)) +1 ; + $cantidad = $cantidad * $pagina; + } + $query = "SELECT PacienteId,Nombre,DNI,Telefono,Correo FROM " . $this->table . " limit $inicio,$cantidad"; + $datos = parent::obtenerDatos($query); + return ($datos); + } + + public function obtenerPaciente($id){ + $query = "SELECT * FROM " . $this->table . " WHERE PacienteId = '$id'"; + return parent::obtenerDatos($query); + + } + + public function post($json){ + $_respuestas = new respuestas; + $datos = json_decode($json,true); + + if(!isset($datos['token'])){ + return $_respuestas->error_401(); + }else{ + $this->token = $datos['token']; + $arrayToken = $this->buscarToken(); + if($arrayToken){ + + if(!isset($datos['nombre']) || !isset($datos['dni']) || !isset($datos['correo'])){ + return $_respuestas->error_400(); + }else{ + $this->nombre = $datos['nombre']; + $this->dni = $datos['dni']; + $this->correo = $datos['correo']; + if(isset($datos['telefono'])) { $this->telefono = $datos['telefono']; } + if(isset($datos['direccion'])) { $this->direccion = $datos['direccion']; } + if(isset($datos['codigoPostal'])) { $this->codigoPostal = $datos['codigoPostal']; } + if(isset($datos['genero'])) { $this->genero = $datos['genero']; } + if(isset($datos['fechaNacimiento'])) { $this->fechaNacimiento = $datos['fechaNacimiento']; } + $resp = $this->insertarPaciente(); + if($resp){ + $respuesta = $_respuestas->response; + $respuesta["result"] = array( + "pacienteId" => $resp + ); + return $respuesta; + }else{ + return $_respuestas->error_500(); + } + } + + }else{ + return $_respuestas->error_401("El Token que envio es invalido o ha caducado"); + } + } + + + + + } + + + private function insertarPaciente(){ + $query = "INSERT INTO " . $this->table . " (DNI,Nombre,Direccion,CodigoPostal,Telefono,Genero,FechaNacimiento,Correo) + values + ('" . $this->dni . "','" . $this->nombre . "','" . $this->direccion ."','" . $this->codigoPostal . "','" . $this->telefono . "','" . $this->genero . "','" . $this->fechaNacimiento . "','" . $this->correo . "')"; + $resp = parent::nonQueryId($query); + if($resp){ + return $resp; + }else{ + return 0; + } + } + + public function put($json){ + $_respuestas = new respuestas; + $datos = json_decode($json,true); + + if(!isset($datos['token'])){ + return $_respuestas->error_401(); + }else{ + $this->token = $datos['token']; + $arrayToken = $this->buscarToken(); + if($arrayToken){ + if(!isset($datos['pacienteId'])){ + return $_respuestas->error_400(); + }else{ + $this->pacienteid = $datos['pacienteId']; + if(isset($datos['nombre'])) { $this->nombre = $datos['nombre']; } + if(isset($datos['dni'])) { $this->dni = $datos['dni']; } + if(isset($datos['correo'])) { $this->correo = $datos['correo']; } + if(isset($datos['telefono'])) { $this->telefono = $datos['telefono']; } + if(isset($datos['direccion'])) { $this->direccion = $datos['direccion']; } + if(isset($datos['codigoPostal'])) { $this->codigoPostal = $datos['codigoPostal']; } + if(isset($datos['genero'])) { $this->genero = $datos['genero']; } + if(isset($datos['fechaNacimiento'])) { $this->fechaNacimiento = $datos['fechaNacimiento']; } + + $resp = $this->modificarPaciente(); + if($resp){ + $respuesta = $_respuestas->response; + $respuesta["result"] = array( + "pacienteId" => $this->pacienteid + ); + return $respuesta; + }else{ + return $_respuestas->error_500(); + } + } + + }else{ + return $_respuestas->error_401("El Token que envio es invalido o ha caducado"); + } + } + + + } + + + private function modificarPaciente(){ + $query = "UPDATE " . $this->table . " SET Nombre ='" . $this->nombre . "',Direccion = '" . $this->direccion . "', DNI = '" . $this->dni . "', CodigoPostal = '" . + $this->codigoPostal . "', Telefono = '" . $this->telefono . "', Genero = '" . $this->genero . "', FechaNacimiento = '" . $this->fechaNacimiento . "', Correo = '" . $this->correo . + "' WHERE PacienteId = '" . $this->pacienteid . "'"; + $resp = parent::nonQuery($query); + if($resp >= 1){ + return $resp; + }else{ + return 0; + } + } + + + public function delete($json){ + $_respuestas = new respuestas; + $datos = json_decode($json,true); + + if(!isset($datos['token'])){ + return $_respuestas->error_401(); + }else{ + $this->token = $datos['token']; + $arrayToken = $this->buscarToken(); + if($arrayToken){ + + if(!isset($datos['pacienteId'])){ + return $_respuestas->error_400(); + }else{ + $this->pacienteid = $datos['pacienteId']; + $resp = $this->eliminarPaciente(); + if($resp){ + $respuesta = $_respuestas->response; + $respuesta["result"] = array( + "pacienteId" => $this->pacienteid + ); + return $respuesta; + }else{ + return $_respuestas->error_500(); + } + } + + }else{ + return $_respuestas->error_401("El Token que envio es invalido o ha caducado"); + } + } + + + + + } + + + private function eliminarPaciente(){ + $query = "DELETE FROM " . $this->table . " WHERE PacienteId= '" . $this->pacienteid . "'"; + $resp = parent::nonQuery($query); + if($resp >= 1 ){ + return $resp; + }else{ + return 0; + } + } + + + private function buscarToken(){ + $query = "SELECT TokenId,UsuarioId,Estado from usuarios_token WHERE Token = '" . $this->token . "' AND Estado = 'Activo'"; + $resp = parent::obtenerDatos($query); + if($resp){ + return $resp; + }else{ + return 0; + } + } + + + private function actualizarToken($tokenid){ + $date = date("Y-m-d H:i"); + $query = "UPDATE usuarios_token SET Fecha = '$date' WHERE TokenId = '$tokenid' "; + $resp = parent::nonQuery($query); + if($resp >= 1){ + return $resp; + }else{ + return 0; + } + } + + + +} + + + + + +?> \ No newline at end of file diff --git a/original/clases/respuestas.class.php b/original/clases/respuestas.class.php new file mode 100644 index 0000000..5b4c5a8 --- /dev/null +++ b/original/clases/respuestas.class.php @@ -0,0 +1,63 @@ + "ok", + "result" => array() + ]; + + + public function error_405(){ + $this->response['status'] = "error"; + $this->response['result'] = array( + "error_id" => "405", + "error_msg" => "Metodo no permitido" + ); + return $this->response; + } + + public function error_200($valor = "Datos incorrectos"){ + $this->response['status'] = "error"; + $this->response['result'] = array( + "error_id" => "200", + "error_msg" => $valor + ); + return $this->response; + } + + + public function error_400(){ + $this->response['status'] = "error"; + $this->response['result'] = array( + "error_id" => "400", + "error_msg" => "Datos enviados incompletos o con formato incorrecto" + ); + return $this->response; + } + + + public function error_500($valor = "Error interno del servidor"){ + $this->response['status'] = "error"; + $this->response['result'] = array( + "error_id" => "500", + "error_msg" => $valor + ); + return $this->response; + } + + + public function error_401($valor = "No autorizado"){ + $this->response['status'] = "error"; + $this->response['result'] = array( + "error_id" => "401", + "error_msg" => $valor + ); + return $this->response; + } + + + +} + +?> diff --git a/original/clases/token.class.php b/original/clases/token.class.php new file mode 100644 index 0000000..c63e784 --- /dev/null +++ b/original/clases/token.class.php @@ -0,0 +1,42 @@ +escribirEntrada($verifica); + return $verifica; + }else{ + return 0; + } + } + + function crearTxt($direccion){ + $archivo = fopen($direccion, 'w') or die ("error al crear el archivo de registros"); + $texto = "------------------------------------ Registros del CRON JOB ------------------------------------ \n"; + fwrite($archivo,$texto) or die ("no pudimos escribir el registro"); + fclose($archivo); + } + + function escribirEntrada($registros){ + $direccion = "../cron/registros/registros.txt"; + if(!file_exists($direccion)){ + $this->crearTxt($direccion); + } + /* crear una entrada nueva */ + $this->escribirTxt($direccion, $registros); + } + + function escribirTxt($direccion, $registros){ + $date = date("Y-m-d H:i"); + $archivo = fopen($direccion, 'a') or die ("error al abrir el archivo de registros"); + $texto = "Se modificaron $registros registro(s) el dia [$date] \n"; + fwrite($archivo,$texto) or die ("no pudimos escribir el registro"); + fclose($archivo); + } +} + +?> \ No newline at end of file diff --git a/original/cron/actualizar_tokens.php b/original/cron/actualizar_tokens.php new file mode 100644 index 0000000..578bd18 --- /dev/null +++ b/original/cron/actualizar_tokens.php @@ -0,0 +1,6 @@ +actualizarTokens($fecha); +?> \ No newline at end of file diff --git a/original/cron/registros/registros.txt b/original/cron/registros/registros.txt new file mode 100644 index 0000000..223ff88 --- /dev/null +++ b/original/cron/registros/registros.txt @@ -0,0 +1,4 @@ +------------------------------------ Registros del CRON JOB ------------------------------------ +Se modificaron -1 el dia [2020-10-18 16:36] +Se modificaron 3 el dia [2020-10-18 16:39] +Se modificaron 2 el dia [2020-10-18 16:41] diff --git a/original/database/apirest.sql b/original/database/apirest.sql new file mode 100644 index 0000000..bba7aa5 --- /dev/null +++ b/original/database/apirest.sql @@ -0,0 +1,181 @@ +-- phpMyAdmin SQL Dump +-- version 5.0.1 +-- https://www.phpmyadmin.net/ +-- +-- Servidor: 127.0.0.1 +-- Tiempo de generación: 07-08-2020 a las 15:36:00 +-- Versión del servidor: 10.4.11-MariaDB +-- Versión de PHP: 7.2.28 + +SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; +SET AUTOCOMMIT = 0; +START TRANSACTION; +SET time_zone = "+00:00"; + + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8mb4 */; + +-- +-- Base de datos: `apirest` +-- + +-- -------------------------------------------------------- + +-- +-- Estructura de tabla para la tabla `citas` +-- + +CREATE TABLE `citas` ( + `CitaId` int(11) NOT NULL, + `PacienteId` varchar(45) DEFAULT NULL, + `Fecha` varchar(45) DEFAULT NULL, + `HoraInicio` varchar(45) DEFAULT NULL, + `HoraFIn` varchar(45) DEFAULT NULL, + `Estado` varchar(45) DEFAULT NULL, + `Motivo` varchar(45) DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +-- +-- Volcado de datos para la tabla `citas` +-- + +INSERT INTO `citas` (`CitaId`, `PacienteId`, `Fecha`, `HoraInicio`, `HoraFIn`, `Estado`, `Motivo`) VALUES +(1, '1', '2020-06-09', '08:30:00', '09:00:00', 'Confirmada', 'El paciente presenta un leve dolor de espalda'), +(2, '2', '2020-06-10', '08:30:00', '09:00:00', 'Confirmada', 'Dolor en la zona lumbar '), +(3, '3', '2020-06-18', '09:00:00', '09:30:00', 'Confirmada', 'Dolor en el cuello'); + +-- -------------------------------------------------------- + +-- +-- Estructura de tabla para la tabla `pacientes` +-- + +CREATE TABLE `pacientes` ( + `PacienteId` int(11) NOT NULL, + `DNI` varchar(45) DEFAULT NULL, + `Nombre` varchar(150) DEFAULT NULL, + `Direccion` varchar(45) DEFAULT NULL, + `CodigoPostal` varchar(45) DEFAULT NULL, + `Telefono` varchar(45) DEFAULT NULL, + `Genero` varchar(45) DEFAULT NULL, + `FechaNacimiento` date DEFAULT NULL, + `Correo` varchar(45) DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +-- +-- Volcado de datos para la tabla `pacientes` +-- + +INSERT INTO `pacientes` (`PacienteId`, `DNI`, `Nombre`, `Direccion`, `CodigoPostal`, `Telefono`, `Genero`, `FechaNacimiento`, `Correo`) VALUES +(1, 'A000000001', 'Juan Carlos Medina', 'Calle de pruebas 1', '20001', '633281515', 'M', '1989-03-02', 'Paciente1@gmail.com'), +(2, 'B000000002', 'Daniel Rios', 'Calle de pruebas 2', '20002', '633281512', 'M', '1990-05-11', 'Paciente2@gmail.com'), +(3, 'C000000003', 'Marcela Dubon', 'Calle de pruebas 3', '20003', '633281511', 'F', '2000-07-22', 'Paciente3@gmail.com'), +(4, 'D000000004', 'Maria Mendez', 'Calle de pruebas 4', '20004', '633281516', 'F', '1980-01-01', 'Paciente4@gmail.com'), +(5, 'E000000005', 'Zamuel Valladares', 'Calle de pruebas 5', '20006', '633281519', 'M', '1985-12-15', 'Paciente5@gmail.com'), +(6, 'F000000006', 'Angel Rios', 'Calle de pruebas 6', '20005', '633281510', 'M', '1988-11-30', 'Paciente6@gmail.com'); + +-- -------------------------------------------------------- + +-- +-- Estructura de tabla para la tabla `usuarios` +-- + +CREATE TABLE `usuarios` ( + `UsuarioId` int(11) NOT NULL, + `Usuario` varchar(45) DEFAULT NULL, + `Password` varchar(45) DEFAULT NULL, + `Estado` varchar(45) DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +-- +-- Volcado de datos para la tabla `usuarios` +-- + +INSERT INTO `usuarios` (`UsuarioId`, `Usuario`, `Password`, `Estado`) VALUES +(1, 'usuario1@gmail.com', 'e10adc3949ba59abbe56e057f20f883e', 'Activo'), +(2, 'usuario2@gmail.com', 'e10adc3949ba59abbe56e057f20f883e', 'Activo'), +(3, 'usuario3@gmail.com', 'e10adc3949ba59abbe56e057f20f883e', 'Activo'), +(4, 'usuario4@gmail.com', 'e10adc3949ba59abbe56e057f20f883e', 'Activo'), +(5, 'usuario5@gmail.com', 'e10adc3949ba59abbe56e057f20f883e', 'Activo'), +(6, 'usuario6@gmail.com', 'e10adc3949ba59abbe56e057f20f883e', 'Activo'), +(7, 'usuario7@gmail.com', 'e10adc3949ba59abbe56e057f20f883e', 'Inactivo'), +(8, 'usuario8@gmail.com', 'e10adc3949ba59abbe56e057f20f883e', 'Inactivo'), +(9, 'usuario9@gmail.com', 'e10adc3949ba59abbe56e057f20f883e', 'Inactivo'); + +-- -------------------------------------------------------- + +-- +-- Estructura de tabla para la tabla `usuarios_token` +-- + +CREATE TABLE `usuarios_token` ( + `TokenId` int(11) NOT NULL, + `UsuarioId` varchar(45) DEFAULT NULL, + `Token` varchar(45) DEFAULT NULL, + `Estado` varchar(45) CHARACTER SET armscii8 DEFAULT NULL, + `Fecha` datetime DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; + +-- +-- Índices para tablas volcadas +-- + +-- +-- Indices de la tabla `citas` +-- +ALTER TABLE `citas` + ADD PRIMARY KEY (`CitaId`); + +-- +-- Indices de la tabla `pacientes` +-- +ALTER TABLE `pacientes` + ADD PRIMARY KEY (`PacienteId`); + +-- +-- Indices de la tabla `usuarios` +-- +ALTER TABLE `usuarios` + ADD PRIMARY KEY (`UsuarioId`); + +-- +-- Indices de la tabla `usuarios_token` +-- +ALTER TABLE `usuarios_token` + ADD PRIMARY KEY (`TokenId`); + +-- +-- AUTO_INCREMENT de las tablas volcadas +-- + +-- +-- AUTO_INCREMENT de la tabla `citas` +-- +ALTER TABLE `citas` + MODIFY `CitaId` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; + +-- +-- AUTO_INCREMENT de la tabla `pacientes` +-- +ALTER TABLE `pacientes` + MODIFY `PacienteId` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; + +-- +-- AUTO_INCREMENT de la tabla `usuarios` +-- +ALTER TABLE `usuarios` + MODIFY `UsuarioId` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10; + +-- +-- AUTO_INCREMENT de la tabla `usuarios_token` +-- +ALTER TABLE `usuarios_token` + MODIFY `TokenId` int(11) NOT NULL AUTO_INCREMENT; +COMMIT; + +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; \ No newline at end of file diff --git a/original/index.php b/original/index.php new file mode 100644 index 0000000..8d67918 --- /dev/null +++ b/original/index.php @@ -0,0 +1,105 @@ + + + + + + API - Prubebas + + + + +
+

Api de pruebas

+
+

Auth - login

+ + POST /auth +
+ { +
+ "usuario" :"", -> REQUERIDO +
+ "password": "" -> REQUERIDO +
+ } + +
+
+
+

Pacientes

+ + GET /pacientes?page=$numeroPagina +
+ GET /pacientes?id=$idPaciente +
+ + + POST /pacientes +
+ { +
+ "nombre" : "", -> REQUERIDO +
+ "dni" : "", -> REQUERIDO +
+ "correo":"", -> REQUERIDO +
+ "codigoPostal" :"", +
+ "genero" : "", +
+ "telefono" : "", +
+ "fechaNacimiento" : "", +
+ "token" : "" -> REQUERIDO +
+ } + +
+ + PUT /pacientes +
+ { +
+ "nombre" : "", +
+ "dni" : "", +
+ "correo":"", +
+ "codigoPostal" :"", +
+ "genero" : "", +
+ "telefono" : "", +
+ "fechaNacimiento" : "", +
+ "token" : "" , -> REQUERIDO +
+ "pacienteId" : "" -> REQUERIDO +
+ } + +
+ + DELETE /pacientes +
+ { +
+ "token" : "", -> REQUERIDO +
+ "pacienteId" : "" -> REQUERIDO +
+ } + +
+
+ + +
+ + + + diff --git a/original/pacientes.php b/original/pacientes.php new file mode 100644 index 0000000..c9b79b6 --- /dev/null +++ b/original/pacientes.php @@ -0,0 +1,90 @@ +listaPacientes($pagina); + header("Content-Type: application/json"); + echo json_encode($listaPacientes); + http_response_code(200); + }else if(isset($_GET['id'])){ + $pacienteid = $_GET['id']; + $datosPaciente = $_pacientes->obtenerPaciente($pacienteid); + header("Content-Type: application/json"); + echo json_encode($datosPaciente); + http_response_code(200); + } + +}else if($_SERVER['REQUEST_METHOD'] == "POST"){ + //recibimos los datos enviados + $postBody = file_get_contents("php://input"); + //enviamos los datos al manejador + $datosArray = $_pacientes->post($postBody); + //delvovemos una respuesta + header('Content-Type: application/json'); + if(isset($datosArray["result"]["error_id"])){ + $responseCode = $datosArray["result"]["error_id"]; + http_response_code($responseCode); + }else{ + http_response_code(200); + } + echo json_encode($datosArray); + +}else if($_SERVER['REQUEST_METHOD'] == "PUT"){ + //recibimos los datos enviados + $postBody = file_get_contents("php://input"); + //enviamos datos al manejador + $datosArray = $_pacientes->put($postBody); + //delvovemos una respuesta + header('Content-Type: application/json'); + if(isset($datosArray["result"]["error_id"])){ + $responseCode = $datosArray["result"]["error_id"]; + http_response_code($responseCode); + }else{ + http_response_code(200); + } + echo json_encode($datosArray); + +}else if($_SERVER['REQUEST_METHOD'] == "DELETE"){ + + $headers = getallheaders(); + if(isset($headers["token"]) && isset($headers["pacienteId"])){ + //recibimos los datos enviados por el header + $send = [ + "token" => $headers["token"], + "pacienteId" =>$headers["pacienteId"] + ]; + $postBody = json_encode($send); + }else{ + //recibimos los datos enviados + $postBody = file_get_contents("php://input"); + } + + //enviamos datos al manejador + $datosArray = $_pacientes->delete($postBody); + //delvovemos una respuesta + header('Content-Type: application/json'); + if(isset($datosArray["result"]["error_id"])){ + $responseCode = $datosArray["result"]["error_id"]; + http_response_code($responseCode); + }else{ + http_response_code(200); + } + echo json_encode($datosArray); + + +}else{ + header('Content-Type: application/json'); + $datosArray = $_respuestas->error_405(); + echo json_encode($datosArray); +} + + +?> \ No newline at end of file