Auth logic is completed (signin, signup, logout), Added: Middlewares, RequireAuth middleware

This commit is contained in:
Filip Rojek 2024-12-26 14:44:40 +01:00
parent 01b057986e
commit 4c44dac115
11 changed files with 112 additions and 31 deletions

View File

@ -2,7 +2,7 @@
## Auth and User stuff ## Auth and User stuff
- [x] signup - [x] signup
- [ ] signin - [x] signin
- [ ] edit user data - change password, mail... - [ ] edit user data - change password, mail...
## Core of the app ## Core of the app

View File

@ -6,6 +6,19 @@ class AuthController extends Controller {
$email = $_POST['email'] ?? ''; $email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? ''; $password = $_POST['password'] ?? '';
$validator = new Validator();
$validator->required('email', $email);
$validator->email('email', $email);
$validator->required('password', $password);
if (!$validator->passes()) {
$this->view('auth/signup', [
'error' => 'Please correct the errors below.',
'validationErrors' => $validator->errors() ?: [],
]);
return;
}
$user = new User(); $user = new User();
$result = $user->login($email, $password); $result = $user->login($email, $password);
@ -26,9 +39,7 @@ class AuthController extends Controller {
$password = $_POST['password'] ?? ''; $password = $_POST['password'] ?? '';
$password2 = $_POST['password-2'] ?? ''; $password2 = $_POST['password-2'] ?? '';
// Perform validations
$validator = new Validator(); $validator = new Validator();
$validator->required('username', $username); $validator->required('username', $username);
$validator->email('email', $email); $validator->email('email', $email);
$validator->required('password', $password); $validator->required('password', $password);
@ -65,4 +76,10 @@ class AuthController extends Controller {
]); ]);
} }
} }
public function logout() {
session_unset();
session_destroy();
$this->redirect('/auth/signin');
}
} }

View File

@ -1,22 +1,18 @@
<?php <?php
class HomeController { class HomeController extends Controller {
//private function render($view) {
// ob_start();
// require_once views . $view;
// $content = ob_get_clean();
// require_once views . 'layouts/base.php';
//}
public function index() { public function index() {
$view = new View();
$data = [ $data = [
'title' => 'Home' 'title' => 'Home'
]; ];
$view->render('home/index', $data); $this->view('home/index', $data);
//require_once views . 'home/index.php';
} }
public function home() { public function home() {
$this->index(); $this->index();
} }
public function dashboard() {
$this->view("dashboard/index");
}
} }

View File

@ -27,7 +27,6 @@ class User {
return "Email is already registered"; return "Email is already registered";
} }
// Hash the password
$hashedPassword = password_hash($password, PASSWORD_BCRYPT); $hashedPassword = password_hash($password, PASSWORD_BCRYPT);
$stmt = $this->db->prepare("INSERT INTO users (username, email, password, points, created_at) VALUES (?, ?, ?, 0, NOW())"); $stmt = $this->db->prepare("INSERT INTO users (username, email, password, points, created_at) VALUES (?, ?, ?, 0, NOW())");
@ -39,7 +38,27 @@ class User {
return "Error: " . $stmt->error; return "Error: " . $stmt->error;
} }
} }
public function login($email, $password) {
$hashedPassword = password_hash($password, PASSWORD_BCRYPT);
$stmt = $this->db->prepare("SELECT username, password FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
if ($result->num_rows === 1) {
$user = $result->fetch_assoc();
if (password_verify($password, $user['password'])) {
$_SESSION['user'] = [
'username' => $user['username'],
'email' => $email,
];
return true;
}
}
return "Invalid email or password.";
}
} }
?>

View File

@ -1,9 +1,21 @@
<section class="signin"> <section class="signin">
<form> <?php if ($this->get('error')): ?>
<label for="username">Username</label> <div class="error"><?= $this->get('error') ?></div>
<input type="text" name="username" id="username"> <?php endif; ?>
<label for="password">Password</label>
<input type="password" name="password" id="password"> <form action="/auth/signin" method="POST">
<input type="submit" value="Sign In" id="submit-signin"> <label for="email">Email</label>
</form> <input type="email" name="email" id="email" value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" required>
<?php if (isset($this->get('validationErrors')['email'])): ?>
<small class="error"><?= $this->get('validationErrors')['email'] ?></small>
<?php endif; ?>
<label for="password">Password</label>
<input type="password" name="password" id="password" required>
<?php if (isset($this->get('validationErrors')['password'])): ?>
<small class="error"><?= $this->get('validationErrors')['password'] ?></small>
<?php endif; ?>
<input type="submit" value="Sign In">
</form>
</section> </section>

View File

@ -0,0 +1 @@
<h1>Welcome <?= $_SESSION['user']['username']?>!</h1>

View File

@ -8,6 +8,7 @@
<header> <header>
<a href="/auth/signin">Log In</a> <a href="/auth/signin">Log In</a>
<a href="/auth/signup">Sign Up</a> <a href="/auth/signup">Sign Up</a>
<a href="/auth/logout">Log Out</a>
</header> </header>
<section class="content"> <section class="content">
<?= $content ?> <?= $content ?>

View File

@ -1,4 +0,0 @@
<header>
<a href="/signin">Log In</a>
<a href="/signup">Sign Up</a>
</header>

View File

@ -2,17 +2,40 @@
class Router { class Router {
private $routes = []; private $routes = [];
private $middlewares = [];
public function add($route, $action) { /**
$this->routes[$route] = $action; * Add a route with a specific action and optional middleware
*
* @param string $route
* @param string $action
* @param array $middlewares Optional middlewares for this route
*/
public function add($route, $action, $middlewares = []) {
$this->routes[$route] = ['action' => $action, 'middlewares' => $middlewares];
} }
/**
* Dispatch the current request to the correct route and execute middlewares
*/
public function dispatch() { public function dispatch() {
$uri = $_SERVER['REQUEST_URI']; $uri = $_SERVER['REQUEST_URI'];
$uri = parse_url($uri, PHP_URL_PATH); $uri = parse_url($uri, PHP_URL_PATH);
if (array_key_exists($uri, $this->routes)) { if (array_key_exists($uri, $this->routes)) {
$action = $this->routes[$uri]; $route = $this->routes[$uri];
$middlewares = $route['middlewares'];
// Execute middlewares
foreach ($middlewares as $middleware) {
$middlewareInstance = new $middleware();
if (!$middlewareInstance->handle()) {
return; // Stop execution if middleware fails
}
}
// Execute the route's controller and method
$action = $route['action'];
list($controllerName, $methodName) = explode('@', $action); list($controllerName, $methodName) = explode('@', $action);
require_once controllers . "{$controllerName}.php"; require_once controllers . "{$controllerName}.php";

View File

@ -0,0 +1,12 @@
<?php
class RequireAuth {
public function handle() {
if (!isset($_SESSION['user'])) {
header('Location: /auth/signin');
exit();
}
return true;
}
}

View File

@ -1,5 +1,6 @@
<?php <?php
// Show errors and warnings // Show errors and warnings
session_start();
ini_set('display_errors', '1'); ini_set('display_errors', '1');
ini_set('log_errors', '1'); ini_set('log_errors', '1');
ini_set('error_log', '../storage/logs/error_log.log'); ini_set('error_log', '../storage/logs/error_log.log');
@ -16,6 +17,7 @@ require_once '../core/Router.php';
require_once '../core/View.php'; require_once '../core/View.php';
require_once '../core/Controller.php'; require_once '../core/Controller.php';
require_once '../core/Database.php'; require_once '../core/Database.php';
require_once '../core/middlewares/RequireAuth.php';
require_once models . 'User.php'; require_once models . 'User.php';
@ -23,8 +25,10 @@ require_once models . 'User.php';
$router = new Router(); $router = new Router();
$router->add('/', 'HomeController@index'); $router->add('/', 'HomeController@index');
$router->add('/home', 'HomeController@home'); $router->add('/home', 'HomeController@home');
$router->add('/dashboard', 'HomeController@dashboard', ['RequireAuth']);
// auth routes // auth routes
$router->add('/auth/signin', 'AuthController@signin'); $router->add('/auth/signin', 'AuthController@signin');
$router->add('/auth/signup', 'AuthController@signup'); $router->add('/auth/signup', 'AuthController@signup');
$router->add('/auth/logout', 'AuthController@logout');
$router->dispatch(); $router->dispatch();