Authentication System – Architecture & Workflow

Deep dive into the purpose and behavior of each component in the PHP Authentication Template.

1. Technology Stack & Libraries
Primary Libraries
  • MongoDB PHP Driver – persistence (users, attempts, messages).
  • PHPMailer – SMTP transport (verification, reset, newsletter).
  • OTPHP – TOTP generation/validation.
  • phpdotenv – environment configuration management.
  • SweetAlert2 – interactive dialog & feedback.
  • Bootstrap 5 – responsive UI framework.
Native Security Primitives
  • password_hash(), password_verify()
  • random_bytes(), random_int()
  • hash_equals() (timing‑safe compares)
  • Session isolation + regeneration
  • CSRF tokens per session
2. Routing (.htaccess)

Apache rewrite rules convert human‑friendly paths into physical script executions. This produces framework‑like cleanliness without imposing a full MVC stack.

/login            → pages/login.php
/register         → pages/register.php
/admin-dashboard  → pages/admin.php
/2fa-setup        → pages/2fa-setup.php
/2fa-verify       → pages/2fa-verify.php
/request-another-email → pages/email.php

Static assets (CSS/JS) are served directly; nonexistent paths route to 404.php.

3. Core Authentication Flows
Login (User/Admin)
User submits credentials + reCAPTCHA.
If email unverified → redirected to resend path.
If 2FA active → session enters pending_2fa_user_id state.
Successful TOTP → full session (user_id or admin_id).
Password Re‑Auth (User 2FA Enrollment)

Adds friction before sensitive operation (enabling 2FA) to mitigate session‑cookie theft scenarios.

  1. User clicks “Enable 2FA”.
  2. Modal prompts for password (AJAX → server verifies hash).
  3. On success sets user_2fa_reauth_passed and redirects to enrollment.
Admin Forced 2FA Bootstrap
  1. Detect missing twofa_secret for admin.
  2. SweetAlert wizard sends 6‑digit email code (3 send cap, 10m expiry).
  3. Verification (3 tries) → session flag force2fa_email_passed.
  4. Redirect to TOTP provisioning page.
4. File Responsibilities
FilePurposeKey Actions
index.phpLanding + newsletterreCAPTCHA, rate limit, insert subscriber
pages/register.phpAccount creationHash password, issue verify token
pages/email.phpResend verificationThrottle, new token, email send
pages/verify.phpConsume tokenExpire or activate user
pages/login.phpPrimary authreCAPTCHA, pending 2FA logic
pages/2fa-verify.phpTOTP checkPromote session to full
pages/2fa-setup.phpTOTP enrollmentQR provisioning, store secret, logout
pages/dashboard.phpUser portalPassword re-auth modal
pages/admin.phpAdmin panelForced 2FA, messaging, newsletter
pages/reset.phpRequest password resetCreate reset token + email
pages/password.phpReset consumeValidate token & update hash
contact.phpPublic formStore message, send confirmation
5. Two‑Factor Authentication Lifecycle

TOTP secrets generated via OTPHP, encoded into provisioning URI for scanning. Client authenticator apps (Google / Microsoft / Authy) produce rolling codes. The server only stores the shared secret (no recovery codes yet — recommended addition).

  • Admin enforcement ensures elevated accounts are never single‑factor beyond initial login window.
  • User password re‑auth prevents silent attacker enrollment.
  • Post‑enrollment session destruction forces reissue of a clean session cookie.
6. Security Layers Overview
Prevent
  • reCAPTCHA on bots
  • CSRF tokens on forms
  • Password hashing (Argon2/Bcrypt)
  • Session segregation
Detect / Limit
  • Attempt counters (email codes)
  • Rate limiting collection
  • Expire tokens & codes
Recover / Respond
  • Password reset tokens
  • Forced logout after 2FA enable
  • Future: audit & alerts
7. Email Operations
  • Verification: 30‑minute token link (idempotent consumption).
  • Password Reset: Similar pattern; token removed after use.
  • Forced Admin 2FA: 6‑digit short‑lived code hashed server‑side.
  • Newsletter: One email → BCC fanout (optimize for large lists later).
  • Contact Confirmation: Courtesy acknowledgement email.

PHPMailer Choice: Mature, SMTP capable, robust error handling, easier debug than bare `mail()`.

8. Why HTML + Bootstrap Instead of Heavy Framework
  • Speed of Iteration: Minimal overhead; quick security prototyping.
  • Lower Hosting Requirements: Works on shared hosts without installing PHP frameworks.
  • Predictable Markup: Bootstrap components reduce CSS maintenance burden.
  • Progressive Enhancement: Core flows function without JS; JS only augments UX.
  • Dependency Transparency: Each file’s purpose is explicit—good for audits & compliance.

You can later migrate to a full MVC or SPA architecture once business needs outgrow the template.