From 8fc7f4e3a85702ab8ffbc10fdfa1fe340af5822e Mon Sep 17 00:00:00 2001 From: Jordy van Zeeland Date: Tue, 13 Aug 2024 09:06:11 +0200 Subject: [PATCH] Template class + CSRF security --- auth.php | 11 ++++++++++- router.php | 20 ++++++++++++-------- template.php | 25 +++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 9 deletions(-) create mode 100644 template.php diff --git a/auth.php b/auth.php index 9d2ab00..ca868e3 100644 --- a/auth.php +++ b/auth.php @@ -44,7 +44,7 @@ class Auth{ ":username" => $username, ":password" => $password ]); - + $user = $query->fetch(); /** @@ -57,6 +57,7 @@ class Auth{ if($user && password_verify($password, $user['password'])){ $_SESSION['user_id'] = $user['id']; $_SESSION['username'] = $user['username']; + $_SESSION['token'] = bin2hex(random_bytes(32)); return true; } @@ -66,4 +67,12 @@ class Auth{ } +/** + * Example CSRF token in a form: + * "> + * + * Possible check for CSRF in a request: + * if (!empty($_REQUEST["csrf"]) && hash_equals($_REQUEST["csrf_token"], $_SESSION["csrf_token"])) { + */ + ?> \ No newline at end of file diff --git a/router.php b/router.php index fe14a7e..ec5440a 100644 --- a/router.php +++ b/router.php @@ -8,8 +8,7 @@ class Router{ */ public function __construct(){ - /* Parse the URL from the request and extract the path part (e.g., "/home" from "http://example.com/home") */ - $uri = parse_url($_SERVER['REQUEST_URI'])['path']; + $uri = parse_url($_SERVER['REQUEST_URI'])['path']; } /** @@ -18,12 +17,15 @@ class Router{ */ public function routeToController($routes){ - // Check if the requested URI exists in the routes array + /** + * Check if the requested URI exists in the routes array. + * If it exists, require (include and execute) the file corresponding to the route. + * If the route doesn't exist, call the abort method to handle the error + */ + if(array_key_exists($this->uri, $routes)){ - // If it exists, require (include and execute) the file corresponding to the route require $routes[$uri]; }else{ - // If the route doesn't exist, call the abort method to handle the error $this->abort(); } } @@ -34,11 +36,13 @@ class Router{ */ public function abort($code = 404){ - // Set the HTTP response code to the specified value + /** + * Set the HTTP response code to the specified value. + * Then include and execute the corresponding error view (e.g., "views/404.php") and Terminate the script execution + */ + http_response_code($code); - // Include and execute the corresponding error view (e.g., "views/404.php") require "views/{$code}.php"; - // Terminate the script execution die(); } } diff --git a/template.php b/template.php new file mode 100644 index 0000000..215f27a --- /dev/null +++ b/template.php @@ -0,0 +1,25 @@ +render('about', '['title' => 'About']'); + +?> \ No newline at end of file