From bc54c8c31e7f50a7a365f9b4d22fe8c74a29f61a Mon Sep 17 00:00:00 2001
From: Thomas Vanbesien
Date: Sat, 21 Mar 2026 21:35:51 +0100
Subject: Add user authentication with email verification and password reset
Implements registration, login/logout, email verification via token,
and password reset flow. Includes CSRF protection, flash messages,
MailPit for dev email testing, and security docs in README.
---
README.md | 42 ++++++
docker-compose.yml | 6 +
docker/php/Dockerfile | 10 ++
src/app/Controllers/AuthController.php | 229 +++++++++++++++++++++++++++++++++
src/app/Csrf.php | 33 +++++
src/app/Flash.php | 25 ++++
src/app/Mail.php | 42 ++++++
src/app/Models/User.php | 118 +++++++++++++++++
src/app/Views/auth/forgot-password.php | 13 ++
src/app/Views/auth/login.php | 17 +++
src/app/Views/auth/register.php | 23 ++++
src/app/Views/auth/reset-password.php | 17 +++
src/app/Views/layouts/main.php | 2 +-
src/app/Views/partials/flash.php | 8 ++
src/config/routes.php | 12 ++
src/public/css/style.css | 74 +++++++++++
16 files changed, 670 insertions(+), 1 deletion(-)
create mode 100644 src/app/Controllers/AuthController.php
create mode 100644 src/app/Csrf.php
create mode 100644 src/app/Flash.php
create mode 100644 src/app/Mail.php
create mode 100644 src/app/Models/User.php
create mode 100644 src/app/Views/auth/forgot-password.php
create mode 100644 src/app/Views/auth/login.php
create mode 100644 src/app/Views/auth/register.php
create mode 100644 src/app/Views/auth/reset-password.php
create mode 100644 src/app/Views/partials/flash.php
diff --git a/README.md b/README.md
index 4bea6c5..2019f4e 100644
--- a/README.md
+++ b/README.md
@@ -92,6 +92,48 @@ The autoloader in `bootstrap.php` uses `spl_autoload_register` to automatically
4. `Router::dispatch()` matches the URL against registered patterns and calls the matching controller method
5. The controller fetches data via models and renders a view inside the layout
+## Security concepts
+
+### CSRF (Cross-Site Request Forgery)
+
+Imagine you're logged into Camagru. A malicious website could contain a hidden form that submits a request to `camagru.local/delete-account` — and your browser would automatically send your session cookie along with it, so the server thinks *you* made that request. This is a CSRF attack: the attacker forges a request that rides on your existing session.
+
+**How tokens prevent it:** every form on Camagru includes a hidden field with a random token that was generated server-side and stored in the user's session. When the form is submitted, the server checks that the token in the request matches the one in the session. The attacker's malicious site can't know this token (it's unique per session and never exposed in a URL), so their forged request will be rejected.
+
+In the code, `App\Csrf` handles this:
+- `Csrf::generate()` creates a random token (via `random_bytes()`) and stores it in `$_SESSION`
+- `Csrf::field()` outputs a hidden `` to embed in forms
+- `Csrf::validate()` checks the submitted token against the session using `hash_equals()` — a constant-time comparison that prevents timing attacks (where an attacker measures response times to guess the token character by character)
+
+### Password hashing
+
+Passwords are never stored in plain text. PHP's `password_hash()` uses bcrypt by default, which:
+1. Generates a random **salt** (so two users with the same password get different hashes)
+2. Runs the password through a deliberately slow hashing algorithm (to make brute-force attacks impractical)
+3. Produces a string that embeds the algorithm, cost factor, salt, and hash — so `password_verify()` can check a password without needing to know the salt separately
+
+### Prepared statements
+
+SQL injection happens when user input is concatenated directly into a query: `"SELECT * FROM users WHERE name = '$name'"` — if `$name` is `' OR 1=1 --`, the attacker gets all users. Prepared statements separate the query structure from the data: the database compiles the query first, then plugs in the values, so user input can never be interpreted as SQL. PDO's `prepare()` + `execute()` handle this.
+
+### XSS (Cross-Site Scripting)
+
+If user-generated content (usernames, comments) is rendered directly into HTML, an attacker could inject `` and it would execute in other users' browsers. `htmlspecialchars()` escapes characters like `<`, `>`, `&`, `"` into their HTML entities (`<`, `>`, etc.) so the browser displays them as text instead of interpreting them as code. Every piece of user data rendered in a view must be escaped this way.
+
+### Sessions
+
+HTTP is stateless — the server doesn't inherently know that two requests come from the same person. PHP sessions solve this: `session_start()` generates a unique session ID, stores it in a cookie on the client, and creates a server-side data store (`$_SESSION`) keyed by that ID. On every request, the browser sends the cookie, PHP looks up the matching session data, and the server knows who you are. This is how login state, CSRF tokens, and flash messages persist across page loads.
+
+### Session fixation
+
+A session fixation attack works like this: the attacker visits the site and gets a session ID (say `abc123`). They then trick the victim into using that same session ID — for example by sending a link like `http://camagru.local/?PHPSESSID=abc123`. If the victim clicks the link, logs in, and the server keeps using `abc123`, the attacker now has a valid logged-in session because they already know the ID.
+
+`session_regenerate_id(true)` prevents this by generating a brand-new session ID the moment a user logs in. The old ID (`abc123`) is destroyed and becomes useless. Even if the attacker planted it, they can't use it after the victim authenticates — the real session now lives under a new, unknown ID.
+
+### User enumeration
+
+When a login fails, our error message says "Invalid username or password" rather than "Username not found" or "Wrong password". Similarly, the forgot-password form always says "If that email is registered, a reset link has been sent." This is deliberate: if the server told you *which* part was wrong, an attacker could probe the system to build a list of valid usernames or emails, then target those accounts specifically with brute-force or phishing attacks.
+
## Image format choices
- **Overlays** are PNG (alpha channel required for transparency)
diff --git a/docker-compose.yml b/docker-compose.yml
index a173959..1c6968f 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -16,6 +16,12 @@ services:
- .env
depends_on:
- mariadb
+ - mailpit
+
+ mailpit:
+ image: axllent/mailpit:v1.24
+ ports:
+ - "8025:8025"
mariadb:
image: mariadb:10.11.11
diff --git a/docker/php/Dockerfile b/docker/php/Dockerfile
index 8626073..375e3a7 100644
--- a/docker/php/Dockerfile
+++ b/docker/php/Dockerfile
@@ -9,6 +9,16 @@ RUN apt-get update && apt-get install -y \
&& docker-php-ext-install -j$(nproc) gd pdo_mysql \
&& rm -rf /var/lib/apt/lists/*
+# Tell PHP to use msmtp as sendmail, and configure msmtp to relay through mailpit
+RUN echo "sendmail_path = /usr/bin/msmtp -t" > /usr/local/etc/php/conf.d/mail.ini
+
+RUN echo "account default\n\
+host mailpit\n\
+port 1025\n\
+from noreply@camagru.local\n\
+auth off\n\
+tls off" > /etc/msmtprc
+
RUN echo "upload_max_filesize = 10M" > /usr/local/etc/php/conf.d/uploads.ini \
&& echo "post_max_size = 10M" >> /usr/local/etc/php/conf.d/uploads.ini
diff --git a/src/app/Controllers/AuthController.php b/src/app/Controllers/AuthController.php
new file mode 100644
index 0000000..ae94295
--- /dev/null
+++ b/src/app/Controllers/AuthController.php
@@ -0,0 +1,229 @@
+user = new User();
+ }
+
+ // ── Registration ──
+
+ public function registerForm(): void
+ {
+ $content = __DIR__ . '/../Views/auth/register.php';
+ include __DIR__ . '/../Views/layouts/main.php';
+ }
+
+ public function register(): void
+ {
+ if (!Csrf::validate($_POST['csrf_token'] ?? '')) {
+ Flash::set('error', 'Invalid CSRF token.');
+ header('Location: /register');
+ return;
+ }
+
+ $username = trim($_POST['username'] ?? '');
+ $email = trim($_POST['email'] ?? '');
+ $password = $_POST['password'] ?? '';
+ $passwordConfirm = $_POST['password_confirm'] ?? '';
+
+ // Validation
+ $errors = [];
+
+ if ($username === '' || $email === '' || $password === '') {
+ $errors[] = 'All fields are required.';
+ }
+ if (!preg_match('/^[a-zA-Z0-9_]{3,20}$/', $username)) {
+ $errors[] = 'Username must be 3-20 characters (letters, numbers, underscores).';
+ }
+ if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
+ $errors[] = 'Invalid email address.';
+ }
+ if (\strlen($password) < 8) {
+ $errors[] = 'Password must be at least 8 characters.';
+ }
+ if ($password !== $passwordConfirm) {
+ $errors[] = 'Passwords do not match.';
+ }
+ if ($this->user->findByUsername($username)) {
+ $errors[] = 'Username is already taken.';
+ }
+ if ($this->user->findByEmail($email)) {
+ $errors[] = 'Email is already registered.';
+ }
+
+ if ($errors) {
+ Flash::set('error', implode(' ', $errors));
+ header('Location: /register');
+ return;
+ }
+
+ $userId = $this->user->create($username, $email, $password);
+ $token = $this->user->getVerificationToken($userId);
+ Mail::sendVerification($email, $token);
+
+ Flash::set('success', 'Account created! Check your email to verify.');
+ header('Location: /login');
+ }
+
+ // ── Email verification ──
+
+ public function verify(): void
+ {
+ $token = $_GET['token'] ?? '';
+ $user = $this->user->findByVerificationToken($token);
+
+ if (!$user) {
+ Flash::set('error', 'Invalid or expired verification link.');
+ header('Location: /login');
+ return;
+ }
+
+ $this->user->verify($user['id']);
+ Flash::set('success', 'Email verified! You can now log in.');
+ header('Location: /login');
+ }
+
+ // ── Login / Logout ──
+
+ public function loginForm(): void
+ {
+ $content = __DIR__ . '/../Views/auth/login.php';
+ include __DIR__ . '/../Views/layouts/main.php';
+ }
+
+ public function login(): void
+ {
+ if (!Csrf::validate($_POST['csrf_token'] ?? '')) {
+ Flash::set('error', 'Invalid CSRF token.');
+ header('Location: /login');
+ return;
+ }
+
+ $username = trim($_POST['username'] ?? '');
+ $password = $_POST['password'] ?? '';
+
+ $user = $this->user->findByUsername($username);
+
+ // Use the same error message for wrong username or wrong password
+ // to avoid revealing which usernames exist (user enumeration)
+ if (!$user || !password_verify($password, $user['password_hash'])) {
+ Flash::set('error', 'Invalid username or password.');
+ header('Location: /login');
+ return;
+ }
+
+ if (!$user['is_verified']) {
+ Flash::set('error', 'Please verify your email before logging in.');
+ header('Location: /login');
+ return;
+ }
+
+ // Regenerate session ID to prevent session fixation attacks
+ session_regenerate_id(true);
+ $_SESSION['user_id'] = $user['id'];
+ $_SESSION['username'] = $user['username'];
+
+ header('Location: /');
+ }
+
+ public function logout(): void
+ {
+ session_destroy();
+ header('Location: /');
+ }
+
+ // ── Password reset ──
+
+ public function forgotPasswordForm(): void
+ {
+ $content = __DIR__ . '/../Views/auth/forgot-password.php';
+ include __DIR__ . '/../Views/layouts/main.php';
+ }
+
+ public function forgotPassword(): void
+ {
+ if (!Csrf::validate($_POST['csrf_token'] ?? '')) {
+ Flash::set('error', 'Invalid CSRF token.');
+ header('Location: /forgot-password');
+ return;
+ }
+
+ $email = trim($_POST['email'] ?? '');
+
+ // Always show the same message whether the email exists or not
+ // to prevent user enumeration
+ Flash::set('success', 'If that email is registered, a reset link has been sent.');
+
+ $user = $this->user->findByEmail($email);
+ if ($user) {
+ $token = $this->user->setResetToken($user['id']);
+ Mail::sendPasswordReset($email, $token);
+ }
+
+ header('Location: /login');
+ }
+
+ public function resetPasswordForm(): void
+ {
+ $token = $_GET['token'] ?? '';
+ $user = $this->user->findByResetToken($token);
+
+ if (!$user) {
+ Flash::set('error', 'Invalid or expired reset link.');
+ header('Location: /login');
+ return;
+ }
+
+ $content = __DIR__ . '/../Views/auth/reset-password.php';
+ include __DIR__ . '/../Views/layouts/main.php';
+ }
+
+ public function resetPassword(): void
+ {
+ if (!Csrf::validate($_POST['csrf_token'] ?? '')) {
+ Flash::set('error', 'Invalid CSRF token.');
+ header('Location: /login');
+ return;
+ }
+
+ $token = $_POST['token'] ?? '';
+ $password = $_POST['password'] ?? '';
+ $passwordConfirm = $_POST['password_confirm'] ?? '';
+
+ $user = $this->user->findByResetToken($token);
+ if (!$user) {
+ Flash::set('error', 'Invalid or expired reset link.');
+ header('Location: /login');
+ return;
+ }
+
+ if (\strlen($password) < 8) {
+ Flash::set('error', 'Password must be at least 8 characters.');
+ header('Location: /reset-password?token=' . urlencode($token));
+ return;
+ }
+ if ($password !== $passwordConfirm) {
+ Flash::set('error', 'Passwords do not match.');
+ header('Location: /reset-password?token=' . urlencode($token));
+ return;
+ }
+
+ $this->user->updatePassword($user['id'], $password);
+ Flash::set('success', 'Password updated! You can now log in.');
+ header('Location: /login');
+ }
+}
diff --git a/src/app/Csrf.php b/src/app/Csrf.php
new file mode 100644
index 0000000..a18c5d9
--- /dev/null
+++ b/src/app/Csrf.php
@@ -0,0 +1,33 @@
+ to embed in HTML forms
+ $token = htmlspecialchars(self::generate());
+ return '';
+ }
+}
diff --git a/src/app/Flash.php b/src/app/Flash.php
new file mode 100644
index 0000000..6e8e78a
--- /dev/null
+++ b/src/app/Flash.php
@@ -0,0 +1,25 @@
+ $type, 'message' => $message];
+ }
+
+ public static function get(): ?array
+ {
+ if (isset($_SESSION['flash'])) {
+ $flash = $_SESSION['flash'];
+ unset($_SESSION['flash']);
+ return $flash;
+ }
+ return null;
+ }
+}
diff --git a/src/app/Mail.php b/src/app/Mail.php
new file mode 100644
index 0000000..054c6e0
--- /dev/null
+++ b/src/app/Mail.php
@@ -0,0 +1,42 @@
+Click the link below to verify your email address: