php jede menge

This commit is contained in:
Peter Hoppe
2022-12-16 15:54:13 +01:00
parent accf248e3c
commit 147fd66fff
10 changed files with 437 additions and 116 deletions

View File

@ -0,0 +1,98 @@
<?php
//require __DIR__ . '/classes/JwtHandler.php';
//class Auth extends JwtHandler
class Auth
{
protected $db;
protected $headers;
protected $token;
public function __construct($db, $headers)
{
//parent::__construct();
$this->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;
}
}
}

View File

@ -1,5 +1,6 @@
<?php
class Database{
class Database
{
// CHANGE THE DB INFO ACCORDING TO YOUR DATABASE
private $db_host = 'localhost';
@ -10,12 +11,14 @@ class Database{
public function dbConnection(){
try{
try
{
$conn = new PDO('mysql:host='.$this->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;
}

100
php/php-dog/classes/lib.php Normal file
View File

@ -0,0 +1,100 @@
<?php
class CMsg
{
$success;
$status;
$message;
$fields;
$data;
function __construct($success,$status = null,$message = null,$fields = null,$data = null)
{
$this->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;
}
?>

View File

@ -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);
echo $returnData->jsonarray();
?>

View File

@ -15,4 +15,5 @@ $db_connection = new Database();
$conn = $db_connection->dbConnection();
$auth = new Auth($conn, $allHeaders);
echo json_encode($auth->isValid());
echo json_encode($auth->isValid());
?>

View File

@ -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);
echo $returnData->jsonarray();
?>

View File

@ -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);
echo $returnData->jsonarray();
?>

83
php/php-dog/upload.php Normal file
View File

@ -0,0 +1,83 @@
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: POST");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
session_start();
require __DIR__.'/classes/Database.php';
require __DIR__.'/classes/lib.php';
$result = new CMsg(0);
if(!isset($_SESSION["user"]))
{
$result = new CMsg(0, 401, "not logged in");
return $result->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();
?>