From 1f55f39a7758c6292ffbe381feb6b3c90f9b2ce0 Mon Sep 17 00:00:00 2001 From: RemRem Date: Tue, 14 Nov 2023 14:50:01 +0100 Subject: [PATCH] format files --- app/connection.php | 5 +- app/database_con.php | 22 ++++--- app/database_init.php | 29 +++++---- app/gateway/file_gateway.php | 40 +++++++----- app/gateway/user_gateway.php | 66 +++++++++++-------- app/routes.php | 121 ++++++++++++++++++----------------- app/token.php | 23 ++++--- 7 files changed, 173 insertions(+), 133 deletions(-) diff --git a/app/connection.php b/app/connection.php index 80d3fc8..fb02db4 100644 --- a/app/connection.php +++ b/app/connection.php @@ -1,9 +1,12 @@ dsn = "mysql:host=".getenv("SMDB_HOST").";dbname=".getenv("SMDB_DATABASE").";charset=UTF8"; + $this->dsn = "mysql:host=" . getenv("SMDB_HOST") . ";dbname=" . getenv("SMDB_DATABASE") . ";charset=UTF8"; $this->login = getenv("SMDB_USER"); $this->password = getenv("SMDB_PASSWORD"); } - public function connect(): int|Connection { + public function connect(): int|Connection + { try { - $connection = new Connection($this->dsn,$this->login,$this->password); - } catch (PDOException $e){ + $connection = new Connection($this->dsn, $this->login, $this->password); + } catch (PDOException $e) { throw new PDOException($e->getMessage(), $e->getCode(), $e); } return $connection; diff --git a/app/database_init.php b/app/database_init.php index eeb6c36..8df2e5d 100644 --- a/app/database_init.php +++ b/app/database_init.php @@ -1,36 +1,43 @@ con = (new DatabaseCon)->connect(); - #} catch(PDOException $e) { - # throw new PDOException($e->getMessage(), $e->getCode(), $e); - $this->createUserTable(); - $this->createFileTable(); + $this->createUserTable(); + $this->createFileTable(); + } catch (PDOException $e) { + throw new PDOException($e->getMessage(), $e->getCode(), $e); + } putenv("IS_DB_INIT=true"); } } - private function createUserTable() { + private function createUserTable() + { $query = 'CREATE TABLE IF NOT EXISTS user ( id UUID PRIMARY KEY, email VARCHAR(100) UNIQUE, hash VARCHAR(255), username VARCHAR(20) DEFAULT \'Change Me!\', creation_date DATE);'; - + $this->con->executeQuery($query); } - private function createFileTable() { + private function createFileTable() + { $query = 'CREATE TABLE IF NOT EXISTS file ( id UUID PRIMARY KEY, user_id UUID REFERENCES `user`(`id`) ON DELETE CASCADE, diff --git a/app/gateway/file_gateway.php b/app/gateway/file_gateway.php index c4d249f..1a0ba32 100644 --- a/app/gateway/file_gateway.php +++ b/app/gateway/file_gateway.php @@ -1,22 +1,27 @@ con = (new DatabaseCon)->connect(); - } catch(PDOException $e) { + } catch (PDOException $e) { throw new PDOException($e->getMessage(), $e->getCode(), $e); } } - public function createFile(string $filename, string $user_uuid, string $category, string $creation_date) { + public function createFile(string $filename, string $user_uuid, string $category, string $creation_date) + { $query = "INSERT INTO file VALUES(UUID(), :user_uuid, :filename, :category, :creation_date ,CURDATE());"; try { $this->con->executeQuery($query, array( @@ -29,11 +34,12 @@ class FileGateway { return -1; } - return 0; + return 0; } // Delete User: (1:OK, 2:Unauthorize, 3:No User) - public function deleteFile(string $file_uuid) : int { + public function deleteFile(string $file_uuid): int + { $query = "DELETE FROM file WHERE id=:file_uuid;"; try { $this->con->executeQuery($query, array( @@ -42,11 +48,12 @@ class FileGateway { } catch (PDOException $e) { return -1; } - + return 0; } - public function getFilename(string $file_uuid, string $user_uuid) { + public function getFilename(string $file_uuid, string $user_uuid) + { $query = "SELECT filename FROM file WHERE user_id=:user_uuid and id=:file_uuid;"; try { $this->con->executeQuery($query, array( @@ -54,15 +61,16 @@ class FileGateway { ':file_uuid' => array($file_uuid, PDO::PARAM_STR) )); $results = $this->con->getResults(); - } catch (PDOException) { - return -1; + } catch (PDOException) { + return -1; } - if(count($results) === 0) return -2; - + if (count($results) === 0) return -2; + return $results[0]['filename']; } - public function listFiles(string $user_uuid) { + public function listFiles(string $user_uuid) + { $query = "SELECT f.id, f.filename, f.category, f.creation_date FROM file f, user u WHERE f.user_id=u.id and u.id=:user_uuid;"; try { $this->con->executeQuery($query, array( @@ -72,7 +80,7 @@ class FileGateway { } catch (PDOException $e) { return -1; } - + $rows = []; foreach ($results as $row) { $rows[] = [ @@ -82,7 +90,7 @@ class FileGateway { 'creation_date' => $row['creation_date'] ]; } - + return $rows; } } diff --git a/app/gateway/user_gateway.php b/app/gateway/user_gateway.php index 1f75dbd..3576df7 100644 --- a/app/gateway/user_gateway.php +++ b/app/gateway/user_gateway.php @@ -1,42 +1,48 @@ token = new Token; - try { + try { $this->con = (new DatabaseCon)->connect(); - } catch(PDOException $e) { + } catch (PDOException $e) { throw new PDOException($e->getMessage(), $e->getCode(), $e); } } - public function createUser(string $email, string $hash, string $username) { + public function createUser(string $email, string $hash, string $username) + { $query = "INSERT INTO user VALUES(UUID(), :email, :hash, :username, CURDATE()) RETURNING id;"; try { - $this->con->executeQuery($query, array( - ':email' => array($email, PDO::PARAM_STR), - ':hash' => array($hash, PDO::PARAM_STR), - ':username' => array($username, PDO::PARAM_STR) - )); + $this->con->executeQuery($query, array( + ':email' => array($email, PDO::PARAM_STR), + ':hash' => array($hash, PDO::PARAM_STR), + ':username' => array($username, PDO::PARAM_STR) + )); } catch (PDOException $e) { return -1; } $results = $this->con->getResults(); - - return $this->token->getNewJsonToken($results[0]['id']); + + return $this->token->getNewJsonToken($results[0]['id']); } // Delete User: (1:OK, 2:Unauthorize, 3:No User) - public function deleteUser(string $uuid) : int { + public function deleteUser(string $uuid): int + { $query = "DELETE FROM user WHERE id=:uuid RETURNING row_count();"; try { $this->con->executeQuery($query, array( @@ -46,16 +52,17 @@ class UserGateway { } catch (PDOException $e) { return -2; } - if(count($results) === 0) return -1; + if (count($results) === 0) return -1; return 0; } // Login User (get token) - public function login(string $email, string $hash) { + public function login(string $email, string $hash) + { $query = "SELECT hash, id FROM user WHERE email=:email;"; - - try{ + + try { $this->con->executeQuery($query, array( ':email' => array($email, PDO::PARAM_STR) )); @@ -63,28 +70,30 @@ class UserGateway { } catch (PDOException $e) { return -3; } - if(count($results) === 0) return -1; - if($hash !== (string) $results[0]['hash']) return -2; - - return json_encode($this->token->getNewJsonToken($results[0]['id'])); + if (count($results) === 0) return -1; + if ($hash !== (string) $results[0]['hash']) return -2; + + return json_encode($this->token->getNewJsonToken($results[0]['id'])); } - public function getInfo(string $uuid) { + public function getInfo(string $uuid) + { $query = "SELECT email, username FROM user WHERE id=:uuid;"; try { - $this->con->executeQuery($query,array( + $this->con->executeQuery($query, array( ':uuid' => array($uuid, PDO::PARAM_STR) )); $results = $this->con->getResults(); - } catch(PDOException $e) { + } catch (PDOException $e) { return -2; } - if(count($results) === 0) return -1; + if (count($results) === 0) return -1; return ["email" => $results[0]['email'], "username" => $results[0]['username']]; } - public function updateMail(string $uuid, string $new_email) { + public function updateMail(string $uuid, string $new_email) + { $query = "UPDATE user SET email=:new_email WHERE id=:uuid;"; try { $this->con->executeQuery($query, array( @@ -98,9 +107,10 @@ class UserGateway { return 0; } - public function updateUsername(string $uuid, string $new_username) { + public function updateUsername(string $uuid, string $new_username) + { $query = "UPDATE user SET username=:new_username WHERE id=:uuid;"; - try{ + try { $this->con->executeQuery($query, array( ':new_username' => array($new_username, PDO::PARAM_STR), ':uuid' => array($uuid, PDO::PARAM_STR) diff --git a/app/routes.php b/app/routes.php index d5c4a4b..3226181 100644 --- a/app/routes.php +++ b/app/routes.php @@ -1,4 +1,5 @@ add(function ($request, $handler) { $response = $handler->handle($request); return $response - ->withHeader('Access-Control-Allow-Origin', '*') - ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization') - ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS'); + ->withHeader('Access-Control-Allow-Origin', '*') + ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization') + ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS'); }); - + $app->get('/', function (Request $req, Response $res) { $res->getBody()->write('SmartFit-API is working!'); return $res; }); - + #### ACCOUNT #### // Create User $app->post('/user', function (Request $req, Response $res) { $req_body = $req->getParsedBody(); - if(!array_key_exists('email',$req_body) || !array_key_exists('hash', $req_body) || !array_key_exists('username', $req_body)) { + if (!array_key_exists('email', $req_body) || !array_key_exists('hash', $req_body) || !array_key_exists('username', $req_body)) { return $res->withStatus(400); } $code = (new UserGateway)->createUser($req_body['email'], $req_body['hash'], $req_body['username']); - if($code === -1) return $res->withStatus(409); - + if ($code === -1) return $res->withStatus(409); + $res->getBody()->write(json_encode($code)); return $res; }); @@ -53,14 +54,14 @@ return function (App $app) { // Delete User $app->delete('/user', function (Request $req, Response $res) { $token = $req->getHeader('Authorization')[0]; - if(!(new Token)->verifyToken($token)) { + if (!(new Token)->verifyToken($token)) { return $res->withStatus(401); } - + $uuid = (new Token)->getUuidFromToken($token); $code = (new UserGateway)->deleteUser($uuid); - switch($code) { + switch ($code) { case 0: return $res->withStatus(200); case -1: @@ -75,9 +76,9 @@ return function (App $app) { $app->get('/user/login/{email}/{hash}', function (Request $req, Response $res, $args) { $email = $args['email']; $hash = $args['hash']; - + $value = (new UserGateway)->login($email, $hash); - switch($value) { + switch ($value) { case -1: return $res->withStatus(404); case -2: @@ -90,15 +91,15 @@ return function (App $app) { return $res; }); - $app->get('/user/info', function(Request $req, Response $res) { + $app->get('/user/info', function (Request $req, Response $res) { $token = $req->getHeader('Authorization')[0]; - if(!(new Token)->verifyToken($token)) { + if (!(new Token)->verifyToken($token)) { return $res->withStatus(401); } $uuid = (new Token)->getUuidFromToken($token); $code = (new UserGateway)->getInfo($uuid); - switch($code) { + switch ($code) { case -1: return $res->withStatus(404); case -2: @@ -110,40 +111,40 @@ return function (App $app) { }); // Update Mail - $app->put('/user/email', function(Request $req, Response $res) { + $app->put('/user/email', function (Request $req, Response $res) { $token = $req->getHeader('Authorization')[0]; - if(!(new Token)->verifyToken($token)) { + if (!(new Token)->verifyToken($token)) { return $res->withStatus(401); } - + $body = $req->getParsedBody(); - if(!isset($body['email'])) { + if (!isset($body['email'])) { return $res->withStatus(400); - } + } $new_email = $req->getParsedBody()['email']; - + $uuid = (new Token)->getUuidFromToken($token); $code = (new UserGateway)->updateMail($uuid, $new_email); - if($code === -1) return $res->withStatus(500); - return $res->withStatus(200); + if ($code === -1) return $res->withStatus(500); + return $res->withStatus(200); }); // Update Username - $app->put('/user/username', function(Request $req, Response $res) { + $app->put('/user/username', function (Request $req, Response $res) { $token = $req->getHeader('Authorization')[0]; - if(!(new Token)->verifyToken($token)){ + if (!(new Token)->verifyToken($token)) { return $res->withStatus(401); } $body = $req->getParsedBody(); - if(!isset($body['username'])) { + if (!isset($body['username'])) { return $res->withStatus(400); } $new_username = $req->getParsedBody()['username']; - - + + $uuid = (new Token)->getUuidFromToken($token); $code = (new UserGateway)->updateUsername($uuid, $new_username); - if($code === -1) return $res->withStatus(500); + if ($code === -1) return $res->withStatus(500); return $res->withStatus(200); }); @@ -152,13 +153,13 @@ return function (App $app) { $app->get('/user/files', function (Request $req, Response $res) { $token = $req->getHeader('Authorization')[0]; $save_folder = '/home/hel/smartfit_hdd'; - if(!(new Token)->verifyToken($token)) { + if (!(new Token)->verifyToken($token)) { return $res->withStatus(401); } - + $uuid = (new Token)->getUuidFromToken($token); $code = (new FileGateway)->listFiles($uuid); - if($code === -1) return $res->withStatus(500); + if ($code === -1) return $res->withStatus(500); $res->getBody()->write(json_encode($code)); return $res; }); @@ -168,79 +169,79 @@ return function (App $app) { $token = $req->getHeader('Authorization')[0]; $file_uuid = $args['uuid']; $save_folder = '/home/hel/smartfit_hdd'; - if(!(new Token)->verifyToken($token)) { + if (!(new Token)->verifyToken($token)) { return $res->withStatus(401); } - + $user_uuid = (new Token)->getUuidFromToken($token); $filename = (new FileGateway)->getFilename($file_uuid, $user_uuid); - switch($filename) { + switch ($filename) { case -1: return $res->withStatus(500); case -2: return $res->withStatus(404); } - - $download_file = fopen($save_folder.'/'.$user_uuid.'/'.$filename, 'r'); + + $download_file = fopen($save_folder . '/' . $user_uuid . '/' . $filename, 'r'); $res->getBody()->write(fread($download_file, (int)fstat($download_file)['size'])); return $res; }); - + // Delete file $app->delete('/user/files/{uuid}', function (Request $req, Response $res, $args) { $token = $req->getHeader('Authorization')[0]; $file_uuid = $args['uuid']; $save_folder = '/home/hel/smartfit_hdd'; - if(!(new Token)->verifyToken($token)) { + if (!(new Token)->verifyToken($token)) { return $res->withStatus(401); } - + $user_uuid = (new Token)->getUuidFromToken($token); $filename = (new FileGateway)->getFilename($file_uuid, $user_uuid); - switch($filename) { + switch ($filename) { case -1: return $res->withStatus(500); case -2: return $res->withStatus(404); } $code = (new FileGateway)->deleteFile($file_uuid, $user_uuid); - if($code === -1) return $res->withStatus(500); + if ($code === -1) return $res->withStatus(500); - $file_path = $save_folder.'/'.$user_uuid.'/'.$filename; - if(file_exists($file_path)) { + $file_path = $save_folder . '/' . $user_uuid . '/' . $filename; + if (file_exists($file_path)) { unlink($file_path); } - + return $res->withStatus(200); - }); - + }); + // Upload file #file_put_contents("test_save_upload.bin", $file->getStream()->getContents()); $app->post('/user/files', function (Request $req, Response $res) { $token = $req->getHeader('Authorization')[0]; $save_folder = '/home/hel/smartfit_hdd'; - if(!(new Token)->verifyToken($token)) { + if (!(new Token)->verifyToken($token)) { return $res->withStatus(401); } - + $uuid = (new Token)->getUuidFromToken($token); $file = $req->getUploadedFiles()['file']; $category = $req->getParsedBody()['SmartFit_Category']; $creation_date = $req->getParsedBody()['SmartFit_Date']; $filename = $file->getClientFilename(); - + $code = (new FileGateway)->listFiles($uuid); - if(array_search($filename, array_column($code, 'filename'), false) !== false) return $res->withStatus(409); - - $file_save_folder = $save_folder.'/'.$uuid.'/'; - if(!is_dir($file_save_folder)) { + if (array_search($filename, array_column($code, 'filename'), false) !== false) return $res->withStatus(409); + + $file_save_folder = $save_folder . '/' . $uuid . '/'; + if (!is_dir($file_save_folder)) { mkdir($file_save_folder, 0777, false); - } - $file->moveTo($file_save_folder.'/'.$filename); - + } + $file->moveTo($file_save_folder . '/' . $filename); + $code = (new FileGateway)->createFile($filename, $uuid, $category, $creation_date); - if($code === -1) return $res->withStatus(500); - + if ($code === -1) return $res->withStatus(500); + return $res->withStatus(200); }); diff --git a/app/token.php b/app/token.php index 0123ae8..cf7d365 100644 --- a/app/token.php +++ b/app/token.php @@ -1,34 +1,38 @@ path_to_key, 'r'); + #$file = fopen($this->path_to_key, 'r'); #$this->key = fread($file, filesize($this->path_to_key)); #fclose($file); } // Return json containing JWT with uuid and exp - public function getNewJsonToken(string $uuid) :array { + public function getNewJsonToken(string $uuid): array + { $payload = [ 'uuid' => $uuid, 'exp' => strtotime("+2month", time()) ]; - + return ["token" => JWT::encode($payload, $this->key, 'HS256')]; } // Verify the JWT authenticity - public function verifyToken(string $jwt) :bool { + public function verifyToken(string $jwt): bool + { try { JWT::decode($jwt, new Key($this->key, 'HS256')); } catch (Exception $e) { @@ -39,8 +43,9 @@ class Token { // Get uuid from JWT // Missing error handling on bad JWT - public function getUuidFromToken(string $jwt) :string { + public function getUuidFromToken(string $jwt): string + { $decoded = (array) JWT::decode($jwt, new Key($this->key, 'HS256')); return $decoded['uuid']; } -} \ No newline at end of file +}