format files

pull/4/head
remrem 1 year ago
parent 7bcccec826
commit 1f55f39a77

@ -1,9 +1,12 @@
<?php <?php
namespace Config; namespace Config;
use PDO; use PDO;
use PDOStatement; use PDOStatement;
class Connection extends PDO{ class Connection extends PDO
{
private PDOStatement $stmt; private PDOStatement $stmt;
public function __construct(string $dsn, string $username, string $password) public function __construct(string $dsn, string $username, string $password)

@ -1,26 +1,32 @@
<?php <?php
namespace Config; namespace Config;
use PDOException; use PDOException;
require_once __DIR__ ."/connection.php";
class DatabaseCon{ require_once __DIR__ . "/connection.php";
class DatabaseCon
{
private string $dsn; private string $dsn;
private string $login; private string $login;
private string $password; private string $password;
public function __construct(){ public function __construct()
if (getenv("SMDB_HOST") == null || getenv("SMDB_DATABASE") == null || getenv("SMDB_USER") == null || getenv("SMDB_PASSWORD") == null){ {
if (getenv("SMDB_HOST") == null || getenv("SMDB_DATABASE") == null || getenv("SMDB_USER") == null || getenv("SMDB_PASSWORD") == null) {
throw new PDOException("ENV variables not found"); throw new PDOException("ENV variables not found");
} }
$this->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->login = getenv("SMDB_USER");
$this->password = getenv("SMDB_PASSWORD"); $this->password = getenv("SMDB_PASSWORD");
} }
public function connect(): int|Connection { public function connect(): int|Connection
{
try { try {
$connection = new Connection($this->dsn,$this->login,$this->password); $connection = new Connection($this->dsn, $this->login, $this->password);
} catch (PDOException $e){ } catch (PDOException $e) {
throw new PDOException($e->getMessage(), $e->getCode(), $e); throw new PDOException($e->getMessage(), $e->getCode(), $e);
} }
return $connection; return $connection;

@ -1,36 +1,43 @@
<?php <?php
namespace Config; namespace Config;
use Config\Connection; use Config\Connection;
use Config\DatabaseCon; use Config\DatabaseCon;
use PDOException; use PDOException;
class DatabaseInit { class DatabaseInit
{
private Connection $con; private Connection $con;
public function __construct() { public function __construct()
if(getenv("IS_DB_INIT") === false) { {
#try { if (getenv("IS_DB_INIT") === false) {
try {
$this->con = (new DatabaseCon)->connect(); $this->con = (new DatabaseCon)->connect();
#} catch(PDOException $e) { $this->createUserTable();
# throw new PDOException($e->getMessage(), $e->getCode(), $e); $this->createFileTable();
$this->createUserTable(); } catch (PDOException $e) {
$this->createFileTable(); throw new PDOException($e->getMessage(), $e->getCode(), $e);
}
putenv("IS_DB_INIT=true"); putenv("IS_DB_INIT=true");
} }
} }
private function createUserTable() { private function createUserTable()
{
$query = 'CREATE TABLE IF NOT EXISTS user ( $query = 'CREATE TABLE IF NOT EXISTS user (
id UUID PRIMARY KEY, id UUID PRIMARY KEY,
email VARCHAR(100) UNIQUE, email VARCHAR(100) UNIQUE,
hash VARCHAR(255), hash VARCHAR(255),
username VARCHAR(20) DEFAULT \'Change Me!\', username VARCHAR(20) DEFAULT \'Change Me!\',
creation_date DATE);'; creation_date DATE);';
$this->con->executeQuery($query); $this->con->executeQuery($query);
} }
private function createFileTable() { private function createFileTable()
{
$query = 'CREATE TABLE IF NOT EXISTS file ( $query = 'CREATE TABLE IF NOT EXISTS file (
id UUID PRIMARY KEY, id UUID PRIMARY KEY,
user_id UUID REFERENCES `user`(`id`) ON DELETE CASCADE, user_id UUID REFERENCES `user`(`id`) ON DELETE CASCADE,

@ -1,22 +1,27 @@
<?php <?php
namespace Gateway; namespace Gateway;
use Config\DatabaseCon; use Config\DatabaseCon;
use Config\Connection; use Config\Connection;
use PDOException; use PDOException;
use PDO; use PDO;
class FileGateway { class FileGateway
{
private Connection $con; private Connection $con;
public function __construct() { public function __construct()
try { {
try {
$this->con = (new DatabaseCon)->connect(); $this->con = (new DatabaseCon)->connect();
} catch(PDOException $e) { } catch (PDOException $e) {
throw new PDOException($e->getMessage(), $e->getCode(), $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());"; $query = "INSERT INTO file VALUES(UUID(), :user_uuid, :filename, :category, :creation_date ,CURDATE());";
try { try {
$this->con->executeQuery($query, array( $this->con->executeQuery($query, array(
@ -29,11 +34,12 @@ class FileGateway {
return -1; return -1;
} }
return 0; return 0;
} }
// Delete User: (1:OK, 2:Unauthorize, 3:No User) // 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;"; $query = "DELETE FROM file WHERE id=:file_uuid;";
try { try {
$this->con->executeQuery($query, array( $this->con->executeQuery($query, array(
@ -42,11 +48,12 @@ class FileGateway {
} catch (PDOException $e) { } catch (PDOException $e) {
return -1; return -1;
} }
return 0; 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;"; $query = "SELECT filename FROM file WHERE user_id=:user_uuid and id=:file_uuid;";
try { try {
$this->con->executeQuery($query, array( $this->con->executeQuery($query, array(
@ -54,15 +61,16 @@ class FileGateway {
':file_uuid' => array($file_uuid, PDO::PARAM_STR) ':file_uuid' => array($file_uuid, PDO::PARAM_STR)
)); ));
$results = $this->con->getResults(); $results = $this->con->getResults();
} catch (PDOException) { } catch (PDOException) {
return -1; return -1;
} }
if(count($results) === 0) return -2; if (count($results) === 0) return -2;
return $results[0]['filename']; 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;"; $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 { try {
$this->con->executeQuery($query, array( $this->con->executeQuery($query, array(
@ -72,7 +80,7 @@ class FileGateway {
} catch (PDOException $e) { } catch (PDOException $e) {
return -1; return -1;
} }
$rows = []; $rows = [];
foreach ($results as $row) { foreach ($results as $row) {
$rows[] = [ $rows[] = [
@ -82,7 +90,7 @@ class FileGateway {
'creation_date' => $row['creation_date'] 'creation_date' => $row['creation_date']
]; ];
} }
return $rows; return $rows;
} }
} }

@ -1,42 +1,48 @@
<?php <?php
namespace Gateway; namespace Gateway;
use Config\DatabaseCon; use Config\DatabaseCon;
use Config\Connection; use Config\Connection;
use PDOException; use PDOException;
use PDO; use PDO;
use Config\Token; use Config\Token;
class UserGateway { class UserGateway
{
private Connection $con; private Connection $con;
private Token $token; private Token $token;
public function __construct() { public function __construct()
{
$this->token = new Token; $this->token = new Token;
try { try {
$this->con = (new DatabaseCon)->connect(); $this->con = (new DatabaseCon)->connect();
} catch(PDOException $e) { } catch (PDOException $e) {
throw new PDOException($e->getMessage(), $e->getCode(), $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;"; $query = "INSERT INTO user VALUES(UUID(), :email, :hash, :username, CURDATE()) RETURNING id;";
try { try {
$this->con->executeQuery($query, array( $this->con->executeQuery($query, array(
':email' => array($email, PDO::PARAM_STR), ':email' => array($email, PDO::PARAM_STR),
':hash' => array($hash, PDO::PARAM_STR), ':hash' => array($hash, PDO::PARAM_STR),
':username' => array($username, PDO::PARAM_STR) ':username' => array($username, PDO::PARAM_STR)
)); ));
} catch (PDOException $e) { } catch (PDOException $e) {
return -1; return -1;
} }
$results = $this->con->getResults(); $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) // 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();"; $query = "DELETE FROM user WHERE id=:uuid RETURNING row_count();";
try { try {
$this->con->executeQuery($query, array( $this->con->executeQuery($query, array(
@ -46,16 +52,17 @@ class UserGateway {
} catch (PDOException $e) { } catch (PDOException $e) {
return -2; return -2;
} }
if(count($results) === 0) return -1; if (count($results) === 0) return -1;
return 0; return 0;
} }
// Login User (get token) // 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;"; $query = "SELECT hash, id FROM user WHERE email=:email;";
try{ try {
$this->con->executeQuery($query, array( $this->con->executeQuery($query, array(
':email' => array($email, PDO::PARAM_STR) ':email' => array($email, PDO::PARAM_STR)
)); ));
@ -63,28 +70,30 @@ class UserGateway {
} catch (PDOException $e) { } catch (PDOException $e) {
return -3; return -3;
} }
if(count($results) === 0) return -1; if (count($results) === 0) return -1;
if($hash !== (string) $results[0]['hash']) return -2; if ($hash !== (string) $results[0]['hash']) return -2;
return json_encode($this->token->getNewJsonToken($results[0]['id'])); 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;"; $query = "SELECT email, username FROM user WHERE id=:uuid;";
try { try {
$this->con->executeQuery($query,array( $this->con->executeQuery($query, array(
':uuid' => array($uuid, PDO::PARAM_STR) ':uuid' => array($uuid, PDO::PARAM_STR)
)); ));
$results = $this->con->getResults(); $results = $this->con->getResults();
} catch(PDOException $e) { } catch (PDOException $e) {
return -2; return -2;
} }
if(count($results) === 0) return -1; if (count($results) === 0) return -1;
return ["email" => $results[0]['email'], "username" => $results[0]['username']]; 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;"; $query = "UPDATE user SET email=:new_email WHERE id=:uuid;";
try { try {
$this->con->executeQuery($query, array( $this->con->executeQuery($query, array(
@ -98,9 +107,10 @@ class UserGateway {
return 0; 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;"; $query = "UPDATE user SET username=:new_username WHERE id=:uuid;";
try{ try {
$this->con->executeQuery($query, array( $this->con->executeQuery($query, array(
':new_username' => array($new_username, PDO::PARAM_STR), ':new_username' => array($new_username, PDO::PARAM_STR),
':uuid' => array($uuid, PDO::PARAM_STR) ':uuid' => array($uuid, PDO::PARAM_STR)

@ -1,4 +1,5 @@
<?php <?php
declare(strict_types=1); declare(strict_types=1);
require_once "gateway/user_gateway.php"; require_once "gateway/user_gateway.php";
require_once "gateway/file_gateway.php"; require_once "gateway/file_gateway.php";
@ -26,26 +27,26 @@ return function (App $app) {
$app->add(function ($request, $handler) { $app->add(function ($request, $handler) {
$response = $handler->handle($request); $response = $handler->handle($request);
return $response return $response
->withHeader('Access-Control-Allow-Origin', '*') ->withHeader('Access-Control-Allow-Origin', '*')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization') ->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-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
}); });
$app->get('/', function (Request $req, Response $res) { $app->get('/', function (Request $req, Response $res) {
$res->getBody()->write('SmartFit-API is working!'); $res->getBody()->write('SmartFit-API is working!');
return $res; return $res;
}); });
#### ACCOUNT #### #### ACCOUNT ####
// Create User // Create User
$app->post('/user', function (Request $req, Response $res) { $app->post('/user', function (Request $req, Response $res) {
$req_body = $req->getParsedBody(); $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); return $res->withStatus(400);
} }
$code = (new UserGateway)->createUser($req_body['email'], $req_body['hash'], $req_body['username']); $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)); $res->getBody()->write(json_encode($code));
return $res; return $res;
}); });
@ -53,14 +54,14 @@ return function (App $app) {
// Delete User // Delete User
$app->delete('/user', function (Request $req, Response $res) { $app->delete('/user', function (Request $req, Response $res) {
$token = $req->getHeader('Authorization')[0]; $token = $req->getHeader('Authorization')[0];
if(!(new Token)->verifyToken($token)) { if (!(new Token)->verifyToken($token)) {
return $res->withStatus(401); return $res->withStatus(401);
} }
$uuid = (new Token)->getUuidFromToken($token); $uuid = (new Token)->getUuidFromToken($token);
$code = (new UserGateway)->deleteUser($uuid); $code = (new UserGateway)->deleteUser($uuid);
switch($code) { switch ($code) {
case 0: case 0:
return $res->withStatus(200); return $res->withStatus(200);
case -1: case -1:
@ -75,9 +76,9 @@ return function (App $app) {
$app->get('/user/login/{email}/{hash}', function (Request $req, Response $res, $args) { $app->get('/user/login/{email}/{hash}', function (Request $req, Response $res, $args) {
$email = $args['email']; $email = $args['email'];
$hash = $args['hash']; $hash = $args['hash'];
$value = (new UserGateway)->login($email, $hash); $value = (new UserGateway)->login($email, $hash);
switch($value) { switch ($value) {
case -1: case -1:
return $res->withStatus(404); return $res->withStatus(404);
case -2: case -2:
@ -90,15 +91,15 @@ return function (App $app) {
return $res; 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]; $token = $req->getHeader('Authorization')[0];
if(!(new Token)->verifyToken($token)) { if (!(new Token)->verifyToken($token)) {
return $res->withStatus(401); return $res->withStatus(401);
} }
$uuid = (new Token)->getUuidFromToken($token); $uuid = (new Token)->getUuidFromToken($token);
$code = (new UserGateway)->getInfo($uuid); $code = (new UserGateway)->getInfo($uuid);
switch($code) { switch ($code) {
case -1: case -1:
return $res->withStatus(404); return $res->withStatus(404);
case -2: case -2:
@ -110,40 +111,40 @@ return function (App $app) {
}); });
// Update Mail // 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]; $token = $req->getHeader('Authorization')[0];
if(!(new Token)->verifyToken($token)) { if (!(new Token)->verifyToken($token)) {
return $res->withStatus(401); return $res->withStatus(401);
} }
$body = $req->getParsedBody(); $body = $req->getParsedBody();
if(!isset($body['email'])) { if (!isset($body['email'])) {
return $res->withStatus(400); return $res->withStatus(400);
} }
$new_email = $req->getParsedBody()['email']; $new_email = $req->getParsedBody()['email'];
$uuid = (new Token)->getUuidFromToken($token); $uuid = (new Token)->getUuidFromToken($token);
$code = (new UserGateway)->updateMail($uuid, $new_email); $code = (new UserGateway)->updateMail($uuid, $new_email);
if($code === -1) return $res->withStatus(500); if ($code === -1) return $res->withStatus(500);
return $res->withStatus(200); return $res->withStatus(200);
}); });
// Update Username // 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]; $token = $req->getHeader('Authorization')[0];
if(!(new Token)->verifyToken($token)){ if (!(new Token)->verifyToken($token)) {
return $res->withStatus(401); return $res->withStatus(401);
} }
$body = $req->getParsedBody(); $body = $req->getParsedBody();
if(!isset($body['username'])) { if (!isset($body['username'])) {
return $res->withStatus(400); return $res->withStatus(400);
} }
$new_username = $req->getParsedBody()['username']; $new_username = $req->getParsedBody()['username'];
$uuid = (new Token)->getUuidFromToken($token); $uuid = (new Token)->getUuidFromToken($token);
$code = (new UserGateway)->updateUsername($uuid, $new_username); $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); return $res->withStatus(200);
}); });
@ -152,13 +153,13 @@ return function (App $app) {
$app->get('/user/files', function (Request $req, Response $res) { $app->get('/user/files', function (Request $req, Response $res) {
$token = $req->getHeader('Authorization')[0]; $token = $req->getHeader('Authorization')[0];
$save_folder = '/home/hel/smartfit_hdd'; $save_folder = '/home/hel/smartfit_hdd';
if(!(new Token)->verifyToken($token)) { if (!(new Token)->verifyToken($token)) {
return $res->withStatus(401); return $res->withStatus(401);
} }
$uuid = (new Token)->getUuidFromToken($token); $uuid = (new Token)->getUuidFromToken($token);
$code = (new FileGateway)->listFiles($uuid); $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)); $res->getBody()->write(json_encode($code));
return $res; return $res;
}); });
@ -168,79 +169,79 @@ return function (App $app) {
$token = $req->getHeader('Authorization')[0]; $token = $req->getHeader('Authorization')[0];
$file_uuid = $args['uuid']; $file_uuid = $args['uuid'];
$save_folder = '/home/hel/smartfit_hdd'; $save_folder = '/home/hel/smartfit_hdd';
if(!(new Token)->verifyToken($token)) { if (!(new Token)->verifyToken($token)) {
return $res->withStatus(401); return $res->withStatus(401);
} }
$user_uuid = (new Token)->getUuidFromToken($token); $user_uuid = (new Token)->getUuidFromToken($token);
$filename = (new FileGateway)->getFilename($file_uuid, $user_uuid); $filename = (new FileGateway)->getFilename($file_uuid, $user_uuid);
switch($filename) { switch ($filename) {
case -1: case -1:
return $res->withStatus(500); return $res->withStatus(500);
case -2: case -2:
return $res->withStatus(404); 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'])); $res->getBody()->write(fread($download_file, (int)fstat($download_file)['size']));
return $res; return $res;
}); });
// Delete file // Delete file
$app->delete('/user/files/{uuid}', function (Request $req, Response $res, $args) { $app->delete('/user/files/{uuid}', function (Request $req, Response $res, $args) {
$token = $req->getHeader('Authorization')[0]; $token = $req->getHeader('Authorization')[0];
$file_uuid = $args['uuid']; $file_uuid = $args['uuid'];
$save_folder = '/home/hel/smartfit_hdd'; $save_folder = '/home/hel/smartfit_hdd';
if(!(new Token)->verifyToken($token)) { if (!(new Token)->verifyToken($token)) {
return $res->withStatus(401); return $res->withStatus(401);
} }
$user_uuid = (new Token)->getUuidFromToken($token); $user_uuid = (new Token)->getUuidFromToken($token);
$filename = (new FileGateway)->getFilename($file_uuid, $user_uuid); $filename = (new FileGateway)->getFilename($file_uuid, $user_uuid);
switch($filename) { switch ($filename) {
case -1: case -1:
return $res->withStatus(500); return $res->withStatus(500);
case -2: case -2:
return $res->withStatus(404); return $res->withStatus(404);
} }
$code = (new FileGateway)->deleteFile($file_uuid, $user_uuid); $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; $file_path = $save_folder . '/' . $user_uuid . '/' . $filename;
if(file_exists($file_path)) { if (file_exists($file_path)) {
unlink($file_path); unlink($file_path);
} }
return $res->withStatus(200); return $res->withStatus(200);
}); });
// Upload file // Upload file
#file_put_contents("test_save_upload.bin", $file->getStream()->getContents()); #file_put_contents("test_save_upload.bin", $file->getStream()->getContents());
$app->post('/user/files', function (Request $req, Response $res) { $app->post('/user/files', function (Request $req, Response $res) {
$token = $req->getHeader('Authorization')[0]; $token = $req->getHeader('Authorization')[0];
$save_folder = '/home/hel/smartfit_hdd'; $save_folder = '/home/hel/smartfit_hdd';
if(!(new Token)->verifyToken($token)) { if (!(new Token)->verifyToken($token)) {
return $res->withStatus(401); return $res->withStatus(401);
} }
$uuid = (new Token)->getUuidFromToken($token); $uuid = (new Token)->getUuidFromToken($token);
$file = $req->getUploadedFiles()['file']; $file = $req->getUploadedFiles()['file'];
$category = $req->getParsedBody()['SmartFit_Category']; $category = $req->getParsedBody()['SmartFit_Category'];
$creation_date = $req->getParsedBody()['SmartFit_Date']; $creation_date = $req->getParsedBody()['SmartFit_Date'];
$filename = $file->getClientFilename(); $filename = $file->getClientFilename();
$code = (new FileGateway)->listFiles($uuid); $code = (new FileGateway)->listFiles($uuid);
if(array_search($filename, array_column($code, 'filename'), false) !== false) return $res->withStatus(409); if (array_search($filename, array_column($code, 'filename'), false) !== false) return $res->withStatus(409);
$file_save_folder = $save_folder.'/'.$uuid.'/'; $file_save_folder = $save_folder . '/' . $uuid . '/';
if(!is_dir($file_save_folder)) { if (!is_dir($file_save_folder)) {
mkdir($file_save_folder, 0777, false); 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); $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); return $res->withStatus(200);
}); });

@ -1,34 +1,38 @@
<?php <?php
namespace Config; namespace Config;
use Exception; use Exception;
use Firebase\JWT\JWT; use Firebase\JWT\JWT;
use Firebase\JWT\Key; use Firebase\JWT\Key;
class Token { class Token
{
private string $key = 'passwd'; private string $key = 'passwd';
// Need to be in a config file // Need to be in a config file
private string $path_to_key="../sym_keyfile.key"; private string $path_to_key = "../sym_keyfile.key";
public function __construct() public function __construct()
{ {
#$file = fopen($this->path_to_key, 'r'); #$file = fopen($this->path_to_key, 'r');
#$this->key = fread($file, filesize($this->path_to_key)); #$this->key = fread($file, filesize($this->path_to_key));
#fclose($file); #fclose($file);
} }
// Return json containing JWT with uuid and exp // Return json containing JWT with uuid and exp
public function getNewJsonToken(string $uuid) :array { public function getNewJsonToken(string $uuid): array
{
$payload = [ $payload = [
'uuid' => $uuid, 'uuid' => $uuid,
'exp' => strtotime("+2month", time()) 'exp' => strtotime("+2month", time())
]; ];
return ["token" => JWT::encode($payload, $this->key, 'HS256')]; return ["token" => JWT::encode($payload, $this->key, 'HS256')];
} }
// Verify the JWT authenticity // Verify the JWT authenticity
public function verifyToken(string $jwt) :bool { public function verifyToken(string $jwt): bool
{
try { try {
JWT::decode($jwt, new Key($this->key, 'HS256')); JWT::decode($jwt, new Key($this->key, 'HS256'));
} catch (Exception $e) { } catch (Exception $e) {
@ -39,8 +43,9 @@ class Token {
// Get uuid from JWT // Get uuid from JWT
// Missing error handling on bad 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')); $decoded = (array) JWT::decode($jwt, new Key($this->key, 'HS256'));
return $decoded['uuid']; return $decoded['uuid'];
} }
} }

Loading…
Cancel
Save