format files

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

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

@ -1,26 +1,32 @@
<?php
namespace Config;
use PDOException;
require_once __DIR__ ."/connection.php";
class DatabaseCon{
require_once __DIR__ . "/connection.php";
class DatabaseCon
{
private string $dsn;
private string $login;
private string $password;
public function __construct(){
if (getenv("SMDB_HOST") == null || getenv("SMDB_DATABASE") == null || getenv("SMDB_USER") == null || getenv("SMDB_PASSWORD") == null){
public function __construct()
{
if (getenv("SMDB_HOST") == null || getenv("SMDB_DATABASE") == null || getenv("SMDB_USER") == null || getenv("SMDB_PASSWORD") == null) {
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->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;

@ -1,25 +1,31 @@
<?php
namespace Config;
use Config\Connection;
use Config\DatabaseCon;
use PDOException;
class DatabaseInit {
class DatabaseInit
{
private Connection $con;
public function __construct() {
if(getenv("IS_DB_INIT") === false) {
#try {
public function __construct()
{
if (getenv("IS_DB_INIT") === false) {
try {
$this->con = (new DatabaseCon)->connect();
#} catch(PDOException $e) {
# throw new PDOException($e->getMessage(), $e->getCode(), $e);
$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,
@ -30,7 +36,8 @@ class DatabaseInit {
$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,

@ -1,22 +1,27 @@
<?php
namespace Gateway;
use Config\DatabaseCon;
use Config\Connection;
use PDOException;
use PDO;
class FileGateway {
class FileGateway
{
private Connection $con;
public function __construct() {
public function __construct()
{
try {
$this->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(
@ -33,7 +38,8 @@ class FileGateway {
}
// 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(
@ -46,7 +52,8 @@ class FileGateway {
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(
@ -57,12 +64,13 @@ class FileGateway {
} 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(

@ -1,25 +1,30 @@
<?php
namespace Gateway;
use Config\DatabaseCon;
use Config\Connection;
use PDOException;
use PDO;
use Config\Token;
class UserGateway {
class UserGateway
{
private Connection $con;
private Token $token;
public function __construct() {
public function __construct()
{
$this->token = new Token;
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(
@ -36,7 +41,8 @@ class UserGateway {
}
// 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;
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)

@ -1,4 +1,5 @@
<?php
declare(strict_types=1);
require_once "gateway/user_gateway.php";
require_once "gateway/file_gateway.php";
@ -40,11 +41,11 @@ return function (App $app) {
// 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:
@ -77,7 +78,7 @@ return function (App $app) {
$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,32 +111,32 @@ 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);
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'];
@ -143,7 +144,7 @@ return function (App $app) {
$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,20 +169,20 @@ 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;
});
@ -191,23 +192,23 @@ 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);
}
$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);
}
@ -219,7 +220,7 @@ return function (App $app) {
$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);
}
@ -230,16 +231,16 @@ return function (App $app) {
$filename = $file->getClientFilename();
$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.'/';
if(!is_dir($file_save_folder)) {
$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);
});

@ -1,14 +1,16 @@
<?php
namespace Config;
use Exception;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
class Token {
class Token
{
private string $key = 'passwd';
// 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()
{
@ -18,7 +20,8 @@ class Token {
}
// 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())
@ -28,7 +31,8 @@ class Token {
}
// 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,7 +43,8 @@ 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'];
}

Loading…
Cancel
Save