46 Commits

Author SHA1 Message Date
Johannes Kantz
7c185b6987 late fix 2023-01-25 08:02:59 +01:00
Johannes Kantz
b607934c8d db pw 2023-01-24 09:01:58 +01:00
Johannes Kantz
62ac1011cc update documentation 2023-01-24 09:01:42 +01:00
Johannes Kantz
c8582c8813 add: delete items from list 2023-01-24 09:01:23 +01:00
Johannes Kantz
b2ce4f829d add: add items to list 2023-01-24 08:47:05 +01:00
Johannes Kantz
9ca46b9b3e add: update and delete units 2023-01-24 04:10:30 +01:00
Johannes Kantz
9a00e7eb16 add: update and delete ingredients 2023-01-24 04:05:15 +01:00
Johannes Kantz
e465ed9e95 add: Documentation 2023-01-23 05:34:13 +01:00
Johannes Kantz
09ab443622 add: test data & slight adjustments 2023-01-23 05:33:21 +01:00
Johannes Kantz
e8775385cf fix: refactor 2023-01-23 05:31:35 +01:00
Johannes Kantz
c717e5c4e9 add: List 2023-01-23 05:26:12 +01:00
Johannes Kantz
67912410d9 add: unit and more simple http status codes 2023-01-23 01:12:43 +01:00
Johannes Kantz
83019b999c add: include http status codes in json response 2023-01-23 01:08:14 +01:00
Johannes Kantz
288dbd6d4c add: Ingredient Route 2023-01-23 00:33:56 +01:00
Johannes Kantz
92f539fa14 fix: typo 2023-01-21 14:10:02 +01:00
Johannes Kantz
c110825140 fix: ignore trailing / at the end of uri 2023-01-21 13:49:59 +01:00
Johannes Kantz
1034dd30f9 add: json error message 2023-01-21 13:25:49 +01:00
Johannes Kantz
464a9c7dbc fix: select fetchAll 2023-01-19 18:37:48 +01:00
Johannes Kantz
082ab46590 Merge branch 'don' of https://git.bib.de/Italienische-Mafia/DirektiveDesDons into don 2023-01-19 17:31:47 +01:00
70c3a61103 add: createunits 2023-01-19 14:36:32 +01:00
7c4ab54f45 add: createIngredients 2023-01-19 14:27:30 +01:00
e666991b60 better select 2023-01-18 10:51:28 +01:00
b93e0c8e5a change: signup 2023-01-18 09:51:43 +01:00
66a9311cae fix 2023-01-18 09:13:01 +01:00
c754569143 Merge remote-tracking branch 'origin/don' into don 2023-01-18 09:09:54 +01:00
71ab5b8dae partial fix 2023-01-18 09:09:39 +01:00
0d811dd059 add: wordbook for easier use of the DB 2023-01-18 09:08:23 +01:00
d28b3fac90 Merge pull request 'Login' (#1) from feat/login into don
Reviewed-on: #1
2023-01-18 08:40:25 +01:00
fbfeeb7679 trying to resolve conflict 2023-01-18 08:39:45 +01:00
Johannes Kantz
2860a01cf8 fix: login with Token 2023-01-12 15:29:58 +01:00
Johannes Kantz
a887921e5d quick safe 2023-01-12 15:22:32 +01:00
Johannes Kantz
a2178733da fix: remove print 2023-01-12 15:09:39 +01:00
Johannes Kantz
5fea5ad15f fix: update vales with quotes 2023-01-12 15:09:08 +01:00
Johannes Kantz
fe5efbe8f1 fix: remove test 2023-01-12 15:04:49 +01:00
Johannes Kantz
f25b2a72f7 add: user login with password 2023-01-12 15:04:15 +01:00
af0d895227 fixed: foreignkeys 2023-01-12 14:56:50 +01:00
da0445ccf6 add: DB removing ALTER TABLE ADD Primary Key 2023-01-12 14:51:44 +01:00
Johannes Kantz
7b5672d36b quick safe 2023-01-12 14:44:52 +01:00
Johannes Kantz
21ebecac54 fix: select fetch 2023-01-12 14:41:51 +01:00
Johannes Kantz
acfae23029 fix: remove print 2023-01-12 14:37:11 +01:00
Johannes Kantz
e1a0f112a2 fix: select values with single quotes 2023-01-12 14:36:37 +01:00
Johannes Kantz
23cf1b54e4 fix: insert vales with single quotes 2023-01-12 14:28:40 +01:00
Johannes Kantz
95a2c3e3fe fix: add Body to Post request 2023-01-12 14:09:02 +01:00
Johannes Kantz
148f95087d add: login begin 2023-01-11 14:45:18 +01:00
Johannes Kantz
81cdae85b0 add: user 2023-01-11 14:45:18 +01:00
Johannes Kantz
1038deded0 fix: redirect everything to index.php 2022-12-08 18:01:23 +01:00
9 changed files with 623 additions and 63 deletions

View File

@@ -1 +1,5 @@
FallbackResource /DirektiveDesDons/index.php # Redirect everything to index.php
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /DirektiveDesDons/index.php [L,QSA]

View File

@@ -3,66 +3,99 @@ SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET SET
time_zone = "+00:00"; time_zone = "+00:00";
CREATE TABLE `folla`
( /*Menge*/
`id` int auto_increment NOT NULL PRIMARY KEY,
`unita` varchar(200) UNIQUE NOT NULL, /*Einheit*/
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `ingredienti` CREATE TABLE `ingredienti`
( /*Zutaten*/ ( /*Zutaten*/
`id` int auto_increment NOT NULL PRIMARY KEY, `id` int auto_increment NOT NULL PRIMARY KEY,
`cognome` varchar(200) NOT NULL, /*Name*/ `cognome` varchar(200) NOT NULL, /*Name*/
`caloriePerCento` integer(5) NOT NULL, /*Kalorien pro Gramm*/ `calorie` integer(5) NOT NULL, /*Kalorien*/
`ilPeso` integer(5) NULL, /*Gewicht*/ `quantita` integer(5) NOT NULL, /*Anzahl*/
`prezzo` decimal(4, 2) NOT NULL, /*Preis*/ `prezzo` decimal(8, 2) NOT NULL, /*Preis*/
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP `follaID` int NOT NULL, /*MengeID*/
) ENGINE=InnoDB DEFAULT CHARSET=utf8; `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
CREATE TABLE `folla`
( /*Menge*/
`id` int auto_increment NOT NULL PRIMARY KEY,
`unita` varchar(200) NOT NULL, /*Einheit*/
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `elenco` CREATE TABLE `elenco`
( /*Liste*/ ( /*Liste*/
`id` int auto_increment NOT NULL PRIMARY KEY, `id` int auto_increment NOT NULL PRIMARY KEY,
`creatore` varchar(200) NOT NULL, /*Ersteller*/ `utenteID` int NOT NULL, /*ErstellerID*/
`coloreDiSfondo` integer(10) NOT NULL, /*Hintergrundfarbe*/ `cognome` varchar(200) NOT NULL, /*Name*/
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP `coloreDiSfondo` varchar(200), /*Hintergrundfarbe*/
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `utente` CREATE TABLE `utente`
( /*Benutzer*/ ( /*Benutzer*/
`id` int auto_increment NOT NULL PRIMARY KEY, `id` int auto_increment NOT NULL PRIMARY KEY,
`email` varchar(200) NOT NULL, /*Email*/ `email` varchar(200) NOT NULL, /*Email*/
`parolaDordine` varchar(255) NOT NULL, /*Passwort*/ `parolaDordine` varchar(255) NOT NULL, /*Passwort*/
`nomeUtente` varchar(50) UNIQUE NOT NULL, /*Benutzernamen*/ `nomeUtente` varchar(50) UNIQUE NOT NULL, /*Benutzernamen*/
`gettone` varchar(255), /*Token für Session*/ `gettone` varchar(255), /*Token für Session*/
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `elencoIngredienti` CREATE TABLE `elencoIngredienti`
( /*Liste_Zutaten*/ ( /*Liste_Zutaten*/
`id` int auto_increment NOT NULL PRIMARY KEY, `id` int auto_increment NOT NULL PRIMARY KEY,
`ingredientiID` varchar(36) NOT NULL, /*ZutatenID*/ `ingredientiID` int NOT NULL, /*ZutatenID*/
`elencoID` varchar(36) NOT NULL, /*ListeID*/ `elencoID` int NOT NULL, /*ListeID*/
`follaID` varchar(36) NOT NULL, /*MengeID*/ `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `utenteElenco` CREATE TABLE `utenteElenco`
( /*Benutzer_Liste*/ ( /*Benutzer_Liste*/
`id` int auto_increment NOT NULL PRIMARY KEY, `id` int auto_increment NOT NULL PRIMARY KEY,
`elencoID` varchar(36) NOT NULL, /*ListeID*/ `elencoID` int NOT NULL, /*ListeID*/
`utenteID` varchar(36) NOT NULL, /*BenutzerID*/ `utenteID` int NOT NULL, /*BenutzerID*/
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8; ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `elencoIngredienti` /*Liste_Zutaten*/ ALTER TABLE `elencoIngredienti` /*Liste_Zutaten*/
ADD PRIMARY KEY (`id`),
ADD CONSTRAINT `FK_ElencoIngredienti_Ingredienti` FOREIGN KEY (`ingredientiID`) REFERENCES `ingredienti`(`id`), /*Liste_Zutaten hat Foreignkey von Zutaten(id)*/ ADD CONSTRAINT `FK_ElencoIngredienti_Ingredienti` FOREIGN KEY (`ingredientiID`) REFERENCES `ingredienti`(`id`), /*Liste_Zutaten hat Foreignkey von Zutaten(id)*/
ADD CONSTRAINT `FK_ElencoIngredienti_Elenco` FOREIGN KEY (`elencoID`) REFERENCES `elenco`(`id`), /*Liste_Zutaten hat Foreignkey von Liste(id)*/ ADD CONSTRAINT `FK_ElencoIngredienti_Elenco` FOREIGN KEY (`elencoID`) REFERENCES `elenco`(`id`); /*Liste_Zutaten hat Foreignkey von Liste(id)*/
ADD CONSTRAINT `FK_ElencoIngredienti_Folla` FOREIGN KEY (`follaID`) REFERENCES `folla`(`id`); /*Liste_Zutaten hat Foreignkey von Menge(id)*/
ALTER TABLE `utenteElenco` /*Benutzer_Liste*/ ALTER TABLE `utenteElenco` /*Benutzer_Liste*/
ADD PRIMARY KEY (`id`),
ADD CONSTRAINT `FK_UtenteElenco_Utente` FOREIGN KEY (`utenteId`) REFERENCES `utente`(`id`), /*Benutzer_Liste hat Foreignkey von Benutzer(id)*/ ADD CONSTRAINT `FK_UtenteElenco_Utente` FOREIGN KEY (`utenteId`) REFERENCES `utente`(`id`), /*Benutzer_Liste hat Foreignkey von Benutzer(id)*/
ADD CONSTRAINT `FK_UtenteElenco_Elenco` FOREIGN KEY (`elencoId`) REFERENCES `elenco`(`id`); /*Benutzer_Liste hat Foreignkey von Liste(id)*/ ADD CONSTRAINT `FK_UtenteElenco_Elenco` FOREIGN KEY (`elencoId`) REFERENCES `elenco`(`id`); /*Benutzer_Liste hat Foreignkey von Liste(id)*/
ALTER TABLE `ingredienti`
ADD CONSTRAINT `FK_Ingredienti_Folla` FOREIGN KEY (`follaID`) REFERENCES `folla`(`id`); /*Zutaten hat Foreignkey von Menge(id)*/
ALTER TABLE `elenco`
ADD CONSTRAINT `FK_Elenco_Utente` FOREIGN KEY (`utenteId`) REFERENCES `utente`(`id`); /*Liste hat Foreignkey von Benutzer(id)*/
/*Test Data*/
INSERT INTO `utente` (email, parolaDordine, nomeUtente) VALUES ('test@test.com', 'password', "testuser");
INSERT INTO `utente` (email, parolaDordine, nomeUtente) VALUES ('test1@test.com', 'hunter2', "testuser1");
INSERT INTO `folla` (unita) VALUES ('st');
INSERT INTO `folla` (unita) VALUES ('g');
INSERT INTO `folla` (unita) VALUES ('kg');
INSERT INTO `folla` (unita) VALUES ('mg');
INSERT INTO `folla` (unita) VALUES ('l');
INSERT INTO `folla` (unita) VALUES ('ml');
INSERT INTO `folla` (unita) VALUES ('TL');
INSERT INTO `folla` (unita) VALUES ('EL');
INSERT INTO `ingredienti` (cognome, calorie, quantita, prezzo, follaID) VALUES ('Raffinierter Zucker', 3870, 1000, 5, 2);
INSERT INTO `ingredienti` (cognome, calorie, quantita, prezzo, follaID) VALUES ('Die Chips von der Tanke', 843, 375, 4.30, 2);
INSERT INTO `ingredienti` (cognome, calorie, quantita, prezzo, follaID) VALUES ('Reines Copium', 420, 1337, 6.9, 4);
INSERT INTO `ingredienti` (cognome, calorie, quantita, prezzo, follaID) VALUES ('Maggi', 420, 1337, 6.9, 4);
INSERT INTO `ingredienti` (cognome, calorie, quantita, prezzo, follaID) VALUES ('Eine große Pommes Frites mit Pommes Frites', 4200, 1, 6.9, 3);
INSERT INTO `elenco` (utenteID, cognome) VALUES (1, 'Liste für den Einkauf bei Netto');
INSERT INTO `elencoIngredienti` (ingredientiID, elencoID) VALUES (1, 1);
INSERT INTO `elencoIngredienti` (ingredientiID, elencoID) VALUES (2, 1);

View File

@@ -22,6 +22,7 @@ class BancaDati {
, $this->pw , $this->pw
, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); , array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch (PDOException $e) { } catch (PDOException $e) {
var_dump($e);
die; die;
} }
} }
@@ -44,7 +45,7 @@ class BancaDati {
$value = ""; $value = "";
$column = ""; $column = "";
foreach ($values as $col => $v){ foreach ($values as $col => $v){
$value .= $v . ","; $value .= "'" . $v . "',";
$column .= $col . ","; $column .= $col . ",";
} }
$value = trim($value, ","); $value = trim($value, ",");
@@ -54,8 +55,10 @@ class BancaDati {
try { try {
$sth = $this->pdo->prepare($sql); $sth = $this->pdo->prepare($sql);
$sth->execute(); $sth->execute();
return $this->pdo->lastInsertId();
}catch (PDOException $e){ }catch (PDOException $e){
die; return false;
//die;
} }
} }
@@ -70,7 +73,7 @@ class BancaDati {
public function update(string $table, string $id, array $values){ public function update(string $table, string $id, array $values){
$value = ""; $value = "";
foreach ($values as $col => $v){ foreach ($values as $col => $v){
$value .= $col . "=" . $v . ","; $value .= $col . "='" . $v . "',";
} }
$value = trim($value, ","); $value = trim($value, ",");
@@ -91,7 +94,7 @@ class BancaDati {
* @author Malte Schulze Hobeling * @author Malte Schulze Hobeling
*/ */
public function delete(string $table, string $id){ public function delete(string $table, string $id){
$sql = "DELETE FROM " . $table . " WHERE `id` = " . $id . ";"; $sql = "DELETE FROM " . $table . " WHERE `id` = '" . $id . "';";
try { try {
$sth = $this->pdo->prepare($sql); $sth = $this->pdo->prepare($sql);
$sth->execute(); $sth->execute();
@@ -102,29 +105,32 @@ class BancaDati {
/** /**
* einheitliche Select Funktion * einheitliche Select Funktion
* kann sortiert werden durch ["by"]=>"col" und ["order"]=>"ASC|DESC"
* @param string $table * @param string $table
* @param array $where ["column"]=>"value" es wird mit LIKE verglichen und mit AND verbunden * @param array $where ["column"]=>"value" es wird mit LIKE verglichen und mit AND verbunden
* @param array|null $order ["by"]=>"column"; ["order"]=>"ASC|DESC"
* @return void * @return void
* @author Malte Schulze Hobeling * @author Malte Schulze Hobeling
*/ */
public function select(string $table, array $where, array $order = null){ public function select(string $table, array $where = []){
$whereString = ""; $whereString = "";
$orderString = "";
if(isset($where["by"])){
$orderString = " ORDER BY " . $where["by"];
unset($where["by"]);
if(isset($where["order"])){
$orderString .= " " . $where["order"];
unset($where["order"]);
}
}
foreach ($where as $col => $v) { foreach ($where as $col => $v) {
if($whereString != ""){ if($whereString != ""){
$whereString .= " AND "; $whereString .= " AND ";
} }
$whereString .= $col . " LIKE " . $v; $whereString .= "`" . $col . "` LIKE '" . $v . "'";
}
$sql = "SELECT * FROM ".$table." WHERE ".$whereString;
if(isset($order["by"])){
$sql .= " ORDER BY ".$order["by"];
}
if(isset($order["order"])){
$sql .= $order["order"];
} }
$sql = "SELECT * FROM " . $table . ((count($where) > 0) ? " WHERE ".$whereString.$orderString : "") .";";
try { try {
return $this->pdo->query($sql); return $this->pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
}catch (PDOException $e){ }catch (PDOException $e){
die; die;
} }

View File

@@ -0,0 +1,156 @@
# Dokumentation
Eine auflistung von allen Funktionen und API-Endpunkten mit Erklärung.
- User
- Einkaufsliste
- Zutaten
- Einheiten
---
## User
### User erstellen
```shell
POST 127.0.0.1/DirektiveDesDons/signup
BODY
{
"username": "Benutzername",
"email": "email",
"password": "Passwort"
}
```
### Aktueller User ausgeben
```shell
GET 127.0.0.1/DirektiveDesDons/user
```
### Login
```shell
POST 127.0.0.1/DirektiveDesDons/login
BODY
{
"username": "Benutzername",
"password": "Passwort"
}
```
---
## Einkaufsliste
### Einkaufsliste erstellen
```shell
POST 127.0.0.1/DirektiveDesDons/list
BODY
{
"name": "Einkaufsliste 1",
"backgoundColor": "#123"
}
```
### Einkauslisten ausgeben
```shell
GET 127.0.0.1/DirektiveDesDons/list
```
### Einkaufsliste ausgeben
```shell
GET 127.0.0.1/DirektiveDesDons/list/1
```
### Einkaufsliste löschen
```shell
DELETE 127.0.0.1/DirektiveDesDons/list/1
```
### Zutat zu Einkaufsliste hinzufügen
```shell
POST 127.0.0.1/DirektiveDesDons/list/1
BODY
{
"ingredientId": 1
}
```
### Zutat von Liste löschen
```shell
DELETE 127.0.0.1/DirektiveDesDons/list/1/4
```
---
## Zutaten
### Zutaten erstellen
```shell
POST 127.0.0.1/DirektiveDesDons/ingredient
BODY
{
"name": "Nüsse",
"calories": "123",
"quantity": "5",
"unit": "st",
"price": "12.5"
}
```
### Zutaten ausgeben
```shell
GET 127.0.0.1/DirektiveDesDons/ingredient
```
### Zutat ausgeben
```shell
GET 127.0.0.1/DirektiveDesDons/ingredient/1
```
### Zutat löschen
```shell
DELETE 127.0.0.1/DirektiveDesDons/ingredient/1
```
### Zutat ändern
```shell
POST 127.0.0.1/DirektiveDesDons/ingredient/3
BODY
{
"name": "Nüsse",
"calories": "123",
"quantity": "5",
"unit": "st",
"price": "13.5"
}
```
---
## MengenEinheiten
### Einheiten auflisten
```shell
GET 127.0.0.1/DirektiveDesDons/unit
```
### Einheit Erstellen
```shell
POST 127.0.0.1/DirektiveDesDons/unit
BODY
{
"name": "lbs"
}
```
### Einheit löschen
```shell
DELETE 127.0.0.1/DirektiveDesDons/unit/4
```

View File

@@ -31,6 +31,7 @@ class Response
http_response_code($status); http_response_code($status);
} }
header('Content-Type: application/json; charset=utf-8'); header('Content-Type: application/json; charset=utf-8');
$data["status"] = http_response_code();
echo json_encode($data); echo json_encode($data);
} }

View File

@@ -20,8 +20,9 @@ class Router
*/ */
public function __construct(string $pathname) public function __construct(string $pathname)
{ {
$this->uri = is_countable($_SERVER['REQUEST_URI']) && count($_SERVER['REQUEST_URI']) > 1 ? rtrim($_SERVER['REQUEST_URI'], "/") : $_SERVER['REQUEST_URI']; $this->uri = str_replace($pathname, "", $_SERVER['REQUEST_URI']);
$this->uri = str_replace($pathname, "", $this->uri); $this->uri = strlen($this->uri) > 1 ? rtrim($this->uri, "/") : $this->uri;
$this->requestType = $_SERVER['REQUEST_METHOD']; $this->requestType = $_SERVER['REQUEST_METHOD'];
$this->routes = []; $this->routes = [];
$this->middleware = []; $this->middleware = [];
@@ -30,9 +31,9 @@ class Router
$this->request = $_SERVER; $this->request = $_SERVER;
} }
if (isset($_POST)) { if (isset($_POST)) {
$this->request["body"] = $_POST; $this->request["body"] = json_decode(file_get_contents('php://input'), true);
} }
if (isset($_POST)) { if (isset($_GET)) {
$this->request["params"] = $_GET; $this->request["params"] = $_GET;
} }
@@ -235,7 +236,7 @@ class Router
if ($controller) { if ($controller) {
$controller($this->request, $this->response); $controller($this->request, $this->response);
} else { } else {
echo "404"; $this->response->json(["status" => "404", "message" => "Not found"], 404);
} }
} }
} }

53
User.php Normal file
View File

@@ -0,0 +1,53 @@
<?php
require_once("BancaDati/BancaDati.php");
use BancaDati\BancaDati;
class User {
public string $id;
public string $username;
public string $email;
public string $token;
private string $password;
private BancaDati $db;
public function __construct() {
$this->db = new BancaDati();
return $this;
}
public function exists() {
return true;
}
public function loginWithUsername(string $username, string $password) : string {
$userObject = $this->db->select("utente", ["nomeUtente" => $username])[0];
if(!$userObject){
return false;
}
$this->id = $userObject["id"];
$this->username = $userObject["nomeUtente"];
$this->email = $userObject["email"];
$this->password = $userObject["parolaDordine"];
$this->token = $this->db->createUUID();
if($this->password != $password){
return false; // ungültiges password
}
$this->db->update("utente", $this->id, ["gettone" => $this->token]);
return $this->token;
}
public function loginWithToken(string $token){
$userObject = $this->db->select("utente", ["gettone" => $token])[0];
if(!$userObject){
return false;
}
$this->id = $userObject["id"];
$this->username = $userObject["nomeUtente"];
$this->email = $userObject["email"];
$this->password = $userObject["parolaDordine"];
$this->token = $token;
return $this;
}
}

291
index.php
View File

@@ -2,25 +2,304 @@
require_once("Router/Router.php"); require_once("Router/Router.php");
require_once("Router/Response.php"); require_once("Router/Response.php");
require_once("Router/Route.php");
require_once("BancaDati/BancaDati.php"); require_once("BancaDati/BancaDati.php");
require_once("User.php");
use Router\Response; use Router\Response;
use Router\Router; use Router\Router;
use Router\Route;
use BancaDati\BancaDati; use BancaDati\BancaDati;
abstract class HTTP_STATUS_CODE {
const OK = 200;
const CREATED = 201;
const BAD_REQUEST = 400;
const FORBIDDEN = 403;
const NOT_FOUNT = 404;
}
$app = new Router("/DirektiveDesDons"); $app = new Router("/DirektiveDesDons");
$db = new BancaDati(); $db = new BancaDati();
$app->get("/", function (array $req, Response $res) { /*
$res->send("Hello World"); * Middleware
*/
$app->use("/", function (array &$req, Response $res) {
if (isset($_COOKIE["TOKEN"])) {
$user = new User();
if ($user->loginWithToken($_COOKIE["TOKEN"])) {
$req["user"] = $user;
}
}
}); });
$app->get("/user", function (array $req, Response $res) { /*
$res->send("user"); * Home
*/
$app->get("/", function (array $req, Response $res) use ($db) {
$res->json(["message" => "Die Einkaufsliste des Don",
"name" => "Shopping List",
"authors" => "Simon Bock, Johannes Kantz & Malte Schulze Hobeling"]);
}); });
$app->get("/user/:id", function (array $req, Response $res) {
$res->send("user " . $req["params"]["id"]); /*
* User
*/
$app->get("/user", function (array $req, Response $res) {
if (isset($req["user"])) {
$res->json(["id" => $req["user"]->id, "username" => $req["user"]->username, "email" => $req["user"]->email]);
} else {
$res->json(["status" => HTTP_STATUS_CODE::FORBIDDEN, "message" => "You are not logged in. Goto '/login' to login"]);
}
});
$app->post("/signup", function (array $req, Response $res) use ($db) {
$newUsername = $req["body"]["username"];
$newPassword = $req["body"]["password"];
$newEmail = $req["body"]["email"];
$db->insert("utente", ["email" => "$newEmail", "parolaDordine" => "$newPassword", "nomeUtente" => "$newUsername"]);
$res->send("Account Created", HTTP_STATUS_CODE::CREATED);
});
$app->post("/login", function (array $req, Response $res) use ($db) {
$username = $req["body"]["username"];
$password = $req["body"]["password"];
$user = new User();
$usertoken = $user->loginWithUsername($username, $password);
if ($usertoken) {
setcookie("TOKEN", $usertoken, time() + 3600); // 1h
$res->json(["message" => "Login successful", "token" => $usertoken]);
} else {
$res->json(["message" => "Login failed"], HTTP_STATUS_CODE::FORBIDDEN);
}
});
/*
* Ingredients
*/
$app->route("/ingredient")
->get(function (array $req, Response $res) use ($db) {
$res->json(["data" => $db->select("ingredienti")]);
})
->post(function (array $req, Response $res) use ($db) {
$name = $req["body"]["name"];
$calories = $req["body"]["calories"];
$quantity = $req["body"]["quantity"];
$unit = $req["body"]["unit"];
$price = $req["body"]["price"];
$unitInTable = $db->select("folla", ["unita" => $unit]);
if (count($unitInTable) > 1) {
$res->json(["message" => "Unit: " . $unit . " does not exist. Please create unit first"], HTTP_STATUS_CODE::BAD_REQUEST);
return;
}
$unitId = $unitInTable[0]["id"];
$id = $db->insert("ingredienti", ["cognome" => "$name", "calorie" => "$calories", "quantita" => "$quantity", "follaID" => $unitId, "prezzo" => "$price"]);
if (!$id) {
$res->json(["message" => "Something went wrong when creating the Ingredient"], HTTP_STATUS_CODE::BAD_REQUEST);
return;
}
$res->json(["message" => "New ingredient has been listed",
"ingredient" => $db->select("ingredienti", ["id" => $id])]);
});
$app->route("/ingredient/:id")
->get(function (array $req, Response $res) use ($db) {
$id = $req["params"]["id"];
$query = $db->select("ingredienti", ["id" => $id]);
if(count($query) < 1){
$res->json(["message" => "Item does not exists"]);
return;
}
$ingredient = $query[0];
$res->json(["data" => $ingredient]);
})
->put(function (array $req, Response $res) use ($db) {
$id = $req["params"]["id"];
$name = $req["body"]["name"];
$calories = $req["body"]["calories"];
$quantity = $req["body"]["quantity"];
$unit = $req["body"]["unit"];
$price = $req["body"]["price"];
$unitInTable = $db->select("folla", ["unita" => $unit]);
if (count($unitInTable) > 1) {
$res->json(["message" => "Unit: " . $unit . " does not exist. Please create unit first"], HTTP_STATUS_CODE::BAD_REQUEST);
return;
}
$unitId = $unitInTable[0]["id"];
$db->update("ingredienti", $id, ["cognome" => "$name", "calorie" => "$calories", "quantita" => "$quantity", "follaID" => $unitId, "prezzo" => "$price"]);
$res->json(["message" => "Ingredient has been updated", "data" => $db->select("ingredienti", ["id" => $id])[0]]);
})
->delete(function (array $req, Response $res) use ($db) {
$id = $req["params"]["id"];
$db->delete("ingredienti", $id);
$res->json(["message" => "Ingredient has been deleted"]);
});
/*
* Unit
*/
$app->route("/unit")
->get(function (array $req, Response $res) use ($db) {
$res->json(["data" => $db->select("folla")]);
})
->post(function (array $req, Response $res) use ($db) {
$name = $req["body"]["name"];
if (!isset($name) || strlen($name) < 1 || strlen($name) > 200) {
$res->json(["message" => "Invalid Request. Please follow the Documentation", HTTP_STATUS_CODE::BAD_REQUEST]);
return;
}
$selectWithSameName = $db->select("folla", ["unita" => $name]);
if (count($selectWithSameName) >= 1) {
$res->json(["message" => "Unit: " . $name . " already exists", "data" => $selectWithSameName[0]], HTTP_STATUS_CODE::BAD_REQUEST);
return;
}
$newUnitId = $db->insert("folla", ["unita" => $name]);
$res->json(["message" => "Unit: '" . $name . "' created", "data" => $db->select("folla", ["id" => $newUnitId])[0]], HTTP_STATUS_CODE::CREATED);
});
$app->route("/unit/:id")
->get(function (array $req, Response $res) use ($db) {
$id = $req["params"]["id"];
$query = $db->select("folla", ["id" => $id]);
if(count($query) < 1){
$res->json(["message" => "Unit does not exists"]);
return;
}
$unit = $query[0];
$res->json(["data" => $unit]);
})
->put(function (array $req, Response $res) use ($db) {
$id = $req["params"]["id"];
$name = $req["body"]["name"];
if (!isset($name) || strlen($name) < 1 || strlen($name) > 200) {
$res->json(["message" => "Invalid Request. Please follow the Documentation", HTTP_STATUS_CODE::BAD_REQUEST]);
return;
}
$db->update("folla", $id, ["unita" => $name]);
$res->json(["message" => "Unit has been updated", "data" => $db->select("folla", ["id" => $id])]);
})
->delete(function (array $req, Response $res) use ($db) {
$id = $req["params"]["id"];
$db->delete("folla", $id);
$res->json(["message" => "Unit has been deleted"]);
});
/*
* List
*/
$app->use("/list", function (array $req, Response $res) {
if (!isset($req["user"])) {
$res->json(["message" => "You need to be signed in to use lists"], HTTP_STATUS_CODE::FORBIDDEN);
die;
}
});
$app->route("/list")
->get(function (array $req, Response $res) use ($db) {
$lists = $db->select("elenco", ["utenteID" => $req["user"]->id]);
// add items to list
foreach ($lists as &$list) {
$listId = $list["id"];
$ingredients = $db->select("elencoIngredienti", ["elencoId" => $listId]);
$ingredientData = [];
foreach ($ingredients as &$ingredient) {
$ingredientData[] = $db->select("Ingredienti", ["id" => $ingredient["ingredientiID"]]);
}
$list["inredients"] = $ingredientData;
}
$res->json(["data" => $lists]);
})
->post(function (array $req, Response $res) use ($db) {
$name = $req["body"]["name"];
$bgColor = $req["body"]["backgoundColor"] ?? "#fff";
if (!isset($name) || strlen($name) < 1) {
$res->json(["message" => "Invalid Request. Please follow the Documentation"], HTTP_STATUS_CODE::BAD_REQUEST);
return;
}
$lastListId = $db->insert("elenco", ["cognome" => $name, "coloreDiSfondo" => $bgColor, "utenteID" => $req["user"]->id]);
$res->json(["message" => "New List '" . $name . "' created", "data" => $db->select("elenco", ["id" => $lastListId])], HTTP_STATUS_CODE::CREATED);
});
$app->route("/list/:id")
->get(function (array $req, Response $res) use ($db) {
$id = $req["params"]["id"];
$query = $db->select("elenco", ["id" => $id, "utenteID" => $req["user"]->id]);
if (count($query) < 1) {
$res->json(["message" => "List does not exists or you dont have permissions to view it"]);
return;
}
$list = $query[0];
$listId = $list["id"];
$ingredients = $db->select("elencoIngredienti", ["elencoId" => $listId]);
$ingredientData = [];
foreach ($ingredients as &$ingredient) {
$ingredientData[] = $db->select("Ingredienti", ["id" => $ingredient["ingredientiID"]]);
}
$list["inredients"] = $ingredientData;
$res->json(["data" => $list]);
})
->post(function (array $req, Response $res) use ($db) {
$id = $req["params"]["id"];
$ingredientId = $req["body"]["ingredientId"];
if (!isset($ingredientId)) {
$res->json(["message" => "You need to set a valid 'ingredientId'", HTTP_STATUS_CODE::BAD_REQUEST]);
return;
}
$newId = $db->insert("elencoIngredienti", ["ingredientiID" => $ingredientId, "elencoID" => $id]);
if(!$newId){
$res->json(["message" => "Cannot insert item in list"], HTTP_STATUS_CODE::BAD_REQUEST);
return;
}
$res->json(["message" => "Item has been added"]);
})
->delete(function (array $req, Response $res) use ($db) {
$id = $req["params"]["id"];
$list = $db->select("elenco", ["id" => $id]);
if (count($list) < 1) {
$res->json(["message" => "List does not exist"]);
return;
}
if ($list[0]["utenteID"] != $req["user"]->id) {
$res->json(["message" => "You have no permissions the delete this list"], HTTP_STATUS_CODE::FORBIDDEN);
return;
}
$db->delete("elenco", $id);
$res->json(["message" => "List has been deleted"]);
});
$app->delete("/list/:id/:item", function (array $req, Response $res) use ($db) {
$listId = $req["params"]["id"];
$itemId = $req["params"]["item"];
$list = $db->select("elenco", ["id" => $listId, "utenteID" => $req["user"]->id]);
if(count($list) < 1){
$res->json(["message" => "List does not exist or you dont have the permissions to edit the list"]);
return;
}
$db->delete("elencoIngredienti", $itemId);
$res->json(["message" => "Item has been deleted"]);
}); });
$app->start(); $app->start();

27
italienIntoGerman.txt Normal file
View File

@@ -0,0 +1,27 @@
ingredienti = Zutaten
cognome = Name
caloriePerCento = Kalorien pro Gramm
ilPeso = Gewicht
prezzo = Preis
folla = Menge
unita = Einheit
elenco = Liste
creatore = Ersteller
coloreDiSfondo = Hintergrundfarbe
utente = Benutzer
email = Email
parolaDordine = Passwort
nomeUtente = Benutzernamen
gettone = Token (für die Session)
elencoIngredienti = Liste_Zutaten
ingredientiID = ZutatenID
elencoID = ListeID
follaID = MengeID
utenteElenco = Benutzer_Liste
elencoID = ListeID
utenteID = BenutzerID