From 147fd66fff50bc7768ef1af80eb1b50a16303ff8 Mon Sep 17 00:00:00 2001 From: Peter Hoppe Date: Fri, 16 Dec 2022 15:54:13 +0100 Subject: [PATCH] php jede menge --- docs/dog.sql | 26 +++---- docs/dog.sql.bak | 56 +++++++++++++++ php/php-dog/AuthMiddleware.php | 98 ++++++++++++++++++++++++++ php/php-dog/classes/Database.php | 9 ++- php/php-dog/classes/lib.php | 100 ++++++++++++++++++++++++++ php/php-dog/getDog.php | 24 ++----- php/php-dog/getUser.php | 3 +- php/php-dog/login.php | 117 +++++++++++++++---------------- php/php-dog/register.php | 37 ++++------ php/php-dog/upload.php | 83 ++++++++++++++++++++++ 10 files changed, 437 insertions(+), 116 deletions(-) create mode 100644 docs/dog.sql.bak create mode 100644 php/php-dog/AuthMiddleware.php create mode 100644 php/php-dog/classes/lib.php create mode 100644 php/php-dog/upload.php diff --git a/docs/dog.sql b/docs/dog.sql index 77fda9e..4119425 100644 --- a/docs/dog.sql +++ b/docs/dog.sql @@ -1,11 +1,11 @@ -- phpMyAdmin SQL Dump --- version 5.2.0 +-- version 5.1.3 -- https://www.phpmyadmin.net/ -- --- Host: localhost --- Erstellungszeit: 15. Dez 2022 um 22:02 --- Server-Version: 10.4.27-MariaDB --- PHP-Version: 8.1.12 +-- Host: 10.35.232.188:3306 +-- Erstellungszeit: 16. Dez 2022 um 10:38 +-- Server-Version: 8.0.31 +-- PHP-Version: 7.4.32 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; @@ -29,14 +29,14 @@ SET time_zone = "+00:00"; CREATE TABLE `dogs` ( `id` int(11) NOT NULL, - `email` varchar(255) NOT NULL, - `qr_id` char(31) NOT NULL, - `name` varchar(255) NOT NULL, - `password` varchar(255) NOT NULL, - `phone` varchar(255) NOT NULL, - `qr_code` mediumblob DEFAULT NULL, - `picture` mediumblob DEFAULT NULL -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + `email` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, + `qr_id` char(31) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, + `name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, + `password` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, + `phone` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, + `qr_code` varchar(255) COLLATE utf8mb3_unicode_ci DEFAULT NULL, + `picture` varchar(255) COLLATE utf8mb3_unicode_ci DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; -- -- Indizes der exportierten Tabellen diff --git a/docs/dog.sql.bak b/docs/dog.sql.bak new file mode 100644 index 0000000..fc915a1 --- /dev/null +++ b/docs/dog.sql.bak @@ -0,0 +1,56 @@ +-- phpMyAdmin SQL Dump +-- version 5.1.3 +-- https://www.phpmyadmin.net/ +-- +-- Host: 10.35.232.188:3306 +-- Erstellungszeit: 16. Dez 2022 um 10:38 +-- Server-Version: 8.0.31 +-- PHP-Version: 7.4.32 + +SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; +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 */; + +-- +-- Datenbank: `k200835_dog` +-- + +-- -------------------------------------------------------- + +-- +-- Tabellenstruktur für Tabelle `dogs` +-- + +CREATE TABLE `dogs` ( + `id` int NOT NULL, + `email` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, + `qr_id` char(31) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, + `name` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, + `password` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, + `phone` varchar(255) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL, + `qr_code` varchar(255) COLLATE utf8mb3_unicode_ci DEFAULT NULL, + `picture` varchar(255) COLLATE utf8mb3_unicode_ci DEFAULT NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +-- +-- Indizes der exportierten Tabellen +-- + +-- +-- Indizes für die Tabelle `dogs` +-- +ALTER TABLE `dogs` + ADD PRIMARY KEY (`id`), + ADD UNIQUE KEY `index_qr_id` (`qr_id`), + ADD UNIQUE KEY `index_email` (`email`); +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 */; diff --git a/php/php-dog/AuthMiddleware.php b/php/php-dog/AuthMiddleware.php new file mode 100644 index 0000000..27ac358 --- /dev/null +++ b/php/php-dog/AuthMiddleware.php @@ -0,0 +1,98 @@ +db = $db; + $this->headers = $headers; + } + + // public function isValid() + // { + + // if (array_key_exists('Authorization', $this->headers) && preg_match('/Bearer\s(\S+)/', $this->headers['Authorization'], $matches)) { + + // $data = $this->jwtDecodeData($matches[1]); + + // if ( + // isset($data['data']->user_id) && + // $user = $this->fetchUser($data['data']->user_id) + // ) : + // return [ + // "success" => 1, + // "user" => $user + // ]; + // else : + // return [ + // "success" => 0, + // "message" => $data['message'], + // ]; + // endif; + // } else { + // return [ + // "success" => 0, + // "message" => "Token not found in request" + // ]; + // } + // } + public function isValid() + { + if(isset($_SESSION['user'])) + { + $data = $_SESSION['user']; + + if ( + isset($data['data']->id) && + $user = $this->fetchUser($data['data']->id) + ) : + return [ + "success" => 1, + "message" => "User found", + "user" => $user + ]; + else : + return [ + "success" => 0, + "message" => $data['message'], + "user" => null + ]; + endif; + } + else + { + return [ + "success" => 0, + "message" => "User not found in request", + "user" => null + ]; + } + } + + protected function fetchUser($user_id) + { + try { + $fetch_user_by_id = "SELECT id, email, name, qr_id FROM dogs WHERE id=:id"; + $query_stmt = $this->db->prepare($fetch_user_by_id); + $query_stmt->bindValue(':id', $user_id, PDO::PARAM_INT); + $query_stmt->execute(); + + if ($query_stmt->rowCount()) : + $returnVal = $query_stmt->fetch(PDO::FETCH_ASSOC); + $returnVal->session = $_SESSION; + return $returnVal; + else : + return false; + endif; + } catch (PDOException $e) { + return null; + } + } +} \ No newline at end of file diff --git a/php/php-dog/classes/Database.php b/php/php-dog/classes/Database.php index b686705..4192822 100644 --- a/php/php-dog/classes/Database.php +++ b/php/php-dog/classes/Database.php @@ -1,5 +1,6 @@ db_host.';dbname='.$this->db_name,$this->db_username,$this->db_password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); return $conn; } - catch(PDOException $e){ + catch(PDOException $e) + { echo "Connection error ".$e->getMessage(); exit; } diff --git a/php/php-dog/classes/lib.php b/php/php-dog/classes/lib.php new file mode 100644 index 0000000..db3cc27 --- /dev/null +++ b/php/php-dog/classes/lib.php @@ -0,0 +1,100 @@ +success = $success; + $this->status = $status; + $this->message = $message; + $this->fields = $fields; + $this->data = $data; + } + + function jsonclass() + { + return json_encode($this); + } + + function jsonarray() + { + return json_encode([ + 'success' => $this->success, + 'status' => $this->status, + 'message' => $this->message, + 'fields' => $this->message, + 'data' => $this->data + ]); + } +} + +class CUser +{ + $id; + $qr_id; + $email; + $name; + + function __construct($id,$qr_id,$email,$name) + { + $this->id = $id; + $this->qr_id = $qr_id; + $this->email = $email; + $this->name = $name; + } +} + +/** + * Generate a random string, using a cryptographically secure + * pseudorandom number generator (random_int) + * + * For PHP 7, random_int is a PHP core function + * For PHP 5.x, depends on https://github.com/paragonie/random_compat + * + * @param int $length How many characters do we want? + * @param string $keyspace A string of all possible characters + * to select from + * @return string + */ +function random_str( + $length, + $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' +) +{ + $str = ''; + $max = mb_strlen($keyspace, '8bit') - 1; + if ($max < 1) + { + throw new Exception('$keyspace must be at least two characters long'); + } + for ($i = 0; $i < $length; ++$i) + { + $str .= $keyspace[random_int(0, $max)]; + } + return $str; +} + +function getNewFilename($targetDir, $fileExt, $length) +{ + $newFname = random_str($length); + $maxtries = 100000; // prevent endless loop, most unlikely + $tries = 0; + while(file_exists($targetDir . '/' . $newFname . '.' . $fileExt) && $tries < $maxtries) + { + ++$tries; + $newFname = random_str($length); + } + if($tries < $maxtries) + { + $newFname = ""; + } + return $newFname; +} + +?> \ No newline at end of file diff --git a/php/php-dog/getDog.php b/php/php-dog/getDog.php index 75ac9a8..17c568b 100644 --- a/php/php-dog/getDog.php +++ b/php/php-dog/getDog.php @@ -8,17 +8,8 @@ header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers session_start(); require __DIR__.'/classes/Database.php'; -//require __DIR__.'/classes/JwtHandler.php'; +require __DIR__.'/classes/lib.php'; -function msg($success,$status,$message,$fields,$data = []){ - return ([ - 'success' => $success, - 'status' => $status, - 'message' => $message, - 'fields' => $message, - 'data' => $data - ]); -} $db_connection = new Database(); $conn = $db_connection->dbConnection(); @@ -26,7 +17,7 @@ $conn = $db_connection->dbConnection(); $data = json_decode(file_get_contents("php://input")); // $data = json_decode('{ "qr_id": "m7MdMK" }'); -$returnData = []; +$returnData = new CMsg(0); $fields = ['fields' => ['qr_id']]; // if(true) @@ -41,7 +32,7 @@ elseif(!isset($data->qr_id) || empty(trim($data->qr_id)) ) { - $returnData = msg(0,422,'Please Fill in all Required Fields!',$fields, null); + $returnData = new CMsg(0,422,'Please Fill in all Required Fields!',$fields); } // IF THERE ARE NO EMPTY FIELDS THEN- @@ -51,7 +42,6 @@ else try { - $fetch_user_by_email = "SELECT * FROM `dogs` WHERE `qr_id`=:qr_id"; $query_stmt = $conn->prepare($fetch_user_by_email); $query_stmt->bindValue(':qr_id', $qr_id,PDO::PARAM_STR); @@ -61,13 +51,13 @@ else if($query_stmt->rowCount()) { $row = $query_stmt->fetch(PDO::FETCH_ASSOC); - $returnData = msg(1,200,'get dog',$fields,$row); + $returnData = new CMsg((1,200,'get dog',$fields,$row); } } catch(PDOException $e) { - $returnData = msg(0,500,$e->getMessage(),$fields,null); + $returnData = new CMsg((0,500,$e->getMessage(),$fields); } - } -echo json_encode($returnData); \ No newline at end of file +echo $returnData->jsonarray(); +?> \ No newline at end of file diff --git a/php/php-dog/getUser.php b/php/php-dog/getUser.php index 3a33f5e..2b9bc2e 100644 --- a/php/php-dog/getUser.php +++ b/php/php-dog/getUser.php @@ -15,4 +15,5 @@ $db_connection = new Database(); $conn = $db_connection->dbConnection(); $auth = new Auth($conn, $allHeaders); -echo json_encode($auth->isValid()); \ No newline at end of file +echo json_encode($auth->isValid()); +?> \ No newline at end of file diff --git a/php/php-dog/login.php b/php/php-dog/login.php index 5e3ce36..09ba56c 100644 --- a/php/php-dog/login.php +++ b/php/php-dog/login.php @@ -8,99 +8,96 @@ header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers session_start(); require __DIR__.'/classes/Database.php'; -//require __DIR__.'/classes/JwtHandler.php'; - -function msg($success,$status,$message,$extra = []){ - return array_merge([ - 'success' => $success, - 'status' => $status, - 'message' => $message - ],$extra); -} +require __DIR__.'/classes/lib.php'; $db_connection = new Database(); $conn = $db_connection->dbConnection(); $data = json_decode(file_get_contents("php://input")); -$returnData = []; +$returnData = new CMsg(0); // IF REQUEST METHOD IS NOT EQUAL TO POST -if($_SERVER["REQUEST_METHOD"] != "POST"): - $returnData = msg(0,404,'Page Not Found!'); - +if($_SERVER["REQUEST_METHOD"] != "POST") +{ + $returnData = new CMsg(0,404,'Page Not Found!'); +} // CHECKING EMPTY FIELDS -elseif(!isset($data->email) +elseif( + !isset($data->qr_id) || !isset($data->password) - || empty(trim($data->email)) + || empty(trim($data->qr_id)) || empty(trim($data->password)) - ): - - $fields = ['fields' => ['email','password']]; - $returnData = msg(0,422,'Please Fill in all Required Fields!',$fields); - + ) +{ + $fields = ['fields' => ['qr_id','password']]; + $returnData = new CMsg(0,422,'Please Fill in all Required Fields!',$fields); +} // IF THERE ARE NO EMPTY FIELDS THEN- -else: - $email = trim($data->email); +else +{ + $qr_id = trim($data->qr_id); $password = trim($data->password); - // CHECKING THE EMAIL FORMAT (IF INVALID FORMAT) - if(!filter_var($email, FILTER_VALIDATE_EMAIL)): - $returnData = msg(0,422,'Invalid Email Address!'); // IF PASSWORD IS LESS THAN 8 THE SHOW THE ERROR - elseif(strlen($password) < 8): - $returnData = msg(0,422,'Your password must be at least 8 characters long!'); - + if(strlen($password) < 8) + { + $returnData = new CMsg(0,422,'Your password must be at least 8 characters long!'); + } // THE USER IS ABLE TO PERFORM THE LOGIN ACTION - else: + else + { try{ - $fetch_user_by_email = "SELECT * FROM `users` WHERE `email`=:email"; - $query_stmt = $conn->prepare($fetch_user_by_email); - $query_stmt->bindValue(':email', $email,PDO::PARAM_STR); + $fetch_user_by_qrid = "SELECT id, name, qr_id, email FROM `dogs` WHERE `qr_id`=:qr_id"; + $query_stmt = $conn->prepare($fetch_user_by_qrid); + $query_stmt->bindValue(':qr_id', $qr_id,PDO::PARAM_STR); $query_stmt->execute(); // IF THE USER IS FOUNDED BY EMAIL - if($query_stmt->rowCount()): + if($query_stmt->rowCount()) + { $row = $query_stmt->fetch(PDO::FETCH_ASSOC); $check_password = password_verify($password, $row['password']); // VERIFYING THE PASSWORD (IS CORRECT OR NOT?) // IF PASSWORD IS CORRECT THEN SEND THE LOGIN TOKEN - if ($check_password): - + if ($check_password) + { // $jwt = new JwtHandler(); - $user = array( - 'id' => $row['id'], - 'vorname' => $row['vorname'], - 'nachname' => $row['nachname'], - 'email' => $row['email'] + $user = new CUser( $row['id'], + $row['qr_id'], + $row['email'], + $row['name'] ); $_SESSION['user'] = $user; - $returnData = [ - 'success' => 1, - 'message' => 'You have successfully logged in.', - 'user' => $user, - 'session' => $_SESSION - ]; - + $returnData = new CMsg( + 1, + 200, + 'You have successfully logged in.', + $fields, + $user); + } // IF INVALID PASSWORD - else: - $returnData = msg(0,422,'Invalid Password!'); - endif; + else + { + $returnData = new CMsg(0,422,'Invalid Password!'); + } // IF THE USER IS NOT FOUNDED BY EMAIL THEN SHOW THE FOLLOWING ERROR - else: - $returnData = msg(0,422,'Invalid Email Address!'); - endif; + } + else + { + $returnData = new CMsg(0,422,'Invalid Email Address!'); + } } - catch(PDOException $e){ - $returnData = msg(0,500,$e->getMessage()); + catch(PDOException $e) + { + $returnData = new CMsg(0,500,$e->getMessage()); } + } +} - endif; - -endif; - -echo json_encode($returnData); \ No newline at end of file +echo $returnData->jsonarray(); +?> \ No newline at end of file diff --git a/php/php-dog/register.php b/php/php-dog/register.php index b7f6f37..2ae7494 100644 --- a/php/php-dog/register.php +++ b/php/php-dog/register.php @@ -8,28 +8,20 @@ header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers session_start(); require __DIR__ . '/classes/Database.php'; +require __DIR__ . '/classes/lib.php'; $db_connection = new Database(); $conn = $db_connection->dbConnection(); -function msg($success, $status, $message, $extra = []) -{ - return array_merge([ - 'success' => $success, - 'status' => $status, - 'message' => $message - ], $extra); -} - // DATA FORM REQUEST $data = json_decode(file_get_contents("php://input")); -$returnData = []; - -if ($_SERVER["REQUEST_METHOD"] != "POST") : - - $returnData = msg(0, 404, 'Page Not Found!'); +$returnData = new CMsg(0); +if ($_SERVER["REQUEST_METHOD"] != "POST") +{ + $returnData = new CMsg(0, 404, 'Page Not Found!'); +} elseif ( - !isset($data->vorname) + !isset($data->qr_id) || !isset($data->nachname) || !isset($data->email) || !isset($data->password) @@ -40,7 +32,7 @@ elseif ( ) : $fields = ['fields' => ['vorname', 'nachname', 'email', 'password']]; - $returnData = msg(0, 422, 'Please Fill in all Required Fields!', $fields); + $returnData = new CMsg(0, 422, 'Please Fill in all Required Fields!', $fields); // IF THERE ARE NO EMPTY FIELDS THEN- else : @@ -53,10 +45,10 @@ else : $returnData = msg(0, 422, 'Invalid Email Address!'); elseif (strlen($password) < 8) : - $returnData = msg(0, 422, 'Your password must be at least 8 characters long!'); + $returnData = new CMsg(0, 422, 'Your password must be at least 8 characters long!'); elseif (strlen($nachname) < 3) : - $returnData = msg(0, 422, 'Your name must be at least 3 characters long!'); + $returnData = new CMsg(0, 422, 'Your name must be at least 3 characters long!'); else : try { @@ -67,7 +59,7 @@ else : $check_email_stmt->execute(); if ($check_email_stmt->rowCount()) : - $returnData = msg(0, 422, 'This E-mail already in use!'); + $returnData = new CMsg(0, 422, 'This E-mail already in use!'); else : $insert_query = "INSERT INTO `users`(`vorname`,`nachname`,`email`,`password`) VALUES(:vorname,:nachname,:email,:password)"; @@ -82,13 +74,14 @@ else : $insert_stmt->execute(); - $returnData = msg(1, 201, 'You have successfully registered.'); + $returnData = new CMsg(1, 201, 'You have successfully registered.'); endif; } catch (PDOException $e) { - $returnData = msg(0, 500, $e->getMessage()); + $returnData = new CMsg(0, 500, $e->getMessage()); } endif; endif; -echo json_encode($returnData); \ No newline at end of file +echo $returnData->jsonarray(); +?> \ No newline at end of file diff --git a/php/php-dog/upload.php b/php/php-dog/upload.php new file mode 100644 index 0000000..7853897 --- /dev/null +++ b/php/php-dog/upload.php @@ -0,0 +1,83 @@ +jsonarray(); +} + +$user = $_SESSION["user"]; +$allowTypes = array('jpg','png','jpeg','gif','pdf'); + +// File upload path +$targetDir = "uploads/".$user->qr_id; +if (!file_exists($targetDir)) +{ + mkdir($targetDir, 0755, true); +} + +$fileName = basename($_FILES["file"]["name"]); +$fileType = pathinfo($fileName,PATHINFO_EXTENSION); + +if(!in_array($fileType, $allowTypes)) +{ + $result = new CMsg( + 0, + 406, + 'Sorry, only JPG, JPEG, PNG, GIF, & PDF files are allowed to upload.'); + return $result->jsonarray(); +} + +$newFilename = getNewFilename($targetDir, $fileType, 20); +if($newFilename.strlen() == 0) +{ + $result = new CMsg( + 0, + 507, + 'Too many uploaded files on the server, try it again later'); + return $result->jsonarray(); +} + +$targetFilePath = $targetDir . '/' . $fileName; + +if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])) +{ + // Upload file to server + if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)) + { + // Insert image file name into database + $update = $db->query("UPDATE dogs SET qr_codefile_name, uploaded_on) VALUES ('".$fileName."', NOW())"); + if($update) + { + $result = new CMsg(1,200,"The file ".$fileName. " has been uploaded successfully."); + } + else + { + $result = new CMsg(0,500,"File upload failed, please try again."); + } + } + else + { + $result = new CMsg(0,500,"Sorry, there was an error uploading your file."); + } +} +else +{ + $result = new CMsg(1,204,'Please select a file to upload.'); +} + +// Display status message +echo $result->jsonarray(); +?> \ No newline at end of file