diff --git a/AGENTS.md b/AGENTS.md
index 068115d..03b3f09 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -100,35 +100,77 @@ site-identity string that shows up in a shared template (as opposed to a
per-page override) should become a `config.php` key the same way, not stay
hardcoded in the template.
-`config['admin_username']` / `config['admin_password_hash']` (username
-defaults to `'admin'`, password hash defaults to `''`) gate every
-`/admin/*` route behind HTTP Basic Auth — this replaced the old
-`docs_enabled` flag entirely (removed); a single gate over all of
-`/admin/*` (docs included) made a docs-only toggle redundant. Unlike the
-Twig-global pattern above, the gate itself is enforced in `bootstrap.php`,
-before rendering: `AdminAuth::requireLogin(...)`
-(`novaconium/src/AdminAuth.php`) is called once for any resolved route
-whose path is `admin` or starts with `admin/`. **Any new admin page
-dropped under `App/pages/admin/` or `novaconium/pages/admin/` is
-automatically protected — no per-page wiring needed.** `bootstrap.php`
-also special-cases the literal path `/admin/logout` *before* router
-resolution — no page exists there — to call `AdminAuth::logout()`, which
-always issues a fresh 401 so the browser drops its cached credentials
-(there's no server-side session to invalidate). `Renderer` separately
-exposes an `admin_auth_enabled` Twig global (true when a password hash is
-set) so `admin/index.twig` can conditionally show the "Logout" link — this
-is a derived display flag, not the enforcement mechanism itself, which
-never depends on Twig. `novaconium/pages/admin/password-hash/` is a
-built-in `password_hash()` form (no CLI needed) for generating
-`admin_password_hash` — a normal admin page, so it's covered by the same
-gate: reachable while no password is set yet (to generate the first
-one), then protected like everything else under `/admin/*` afterward. It
-computes and displays the hash per-request only; nothing is persisted or
-logged. This is a single-user HTTP Basic Auth stopgap, not
-the full multi-user system tracked in `novaconium/ISSUES.md` ("Admin login & user
-management"); don't extend this class toward multi-user/session-based
-auth — that's a separate, larger feature that
-will replace it.
+`config['admin_auth_enabled']` (default `false`) gates every `/admin/*`
+route behind a session login against the `users` table on `Lib\Db`'s
+default connection (`novaconium/migrations/0002_create_users.sql`) — the
+multi-user system from `novaconium/ISSUES.md`'s "Admin login & user
+management" entry, which **replaced** the old single-user HTTP Basic Auth
+stopgap (the `admin_username`/`admin_password_hash` config keys and the
+`/admin/password-hash` page are gone; that stopgap had itself replaced
+the even older `docs_enabled` flag). Same off-by-default posture as
+`content_index_enabled`, for the same reason: it depends on SQLite, so
+when the flag is false, `/admin/*` is wide open, the three auth routes
+(`/admin/login`, `/admin/logout`, `/admin/users`) 404 as if they didn't
+exist, their sidecars check the flag (via the same self-loaded two-step
+config read `/search` uses) *before* touching `Lib\Db`, and no
+`data/novaconium.sqlite` is ever created by this feature — verified
+end-to-end. **Two roles** (`users.role`): the **first user ever created
+is `'admin'`; everyone created after is `'registered'`**, each with an
+optional single group (`users.user_group`, a plain text label — no
+groups table). Admins run the site: `/admin/*`, drafts, and every
+`Lib\Access` rule passes for them. Registered users log in at the same
+`/admin/login` and see whatever content `Lib\Access` (below) grants
+their account or group — but `/admin/*` renders a plain 404 for them
+(they're authenticated; what they lack is the role, so bouncing them to
+the login form would be wrong). Unlike the Twig-global pattern above,
+the gate itself is enforced in `bootstrap.php`, before rendering, in two
+steps: `AdminAuth::requireLogin($config['admin_auth_enabled'])`
+(`novaconium/src/AdminAuth.php`) redirects anyone not logged in, then
+`AdminAuth::isAdmin(...)` 404s logged-in non-admins — for any resolved
+route whose path is `admin` or starts with `admin/`, **except
+`admin/login` itself, which must stay reachable logged-out or the
+redirect to it would loop.** **Any new admin page dropped under
+`App/pages/admin/` or `novaconium/pages/admin/` is automatically
+protected — no per-page wiring needed.** Bootstrapping the first user:
+while the `users` table is empty, the gate deliberately returns open
+access so the first user (the admin) can be created at `/admin/users`
+(which auto-logs its creator in, closing the gate), mirroring the old
+"wide open until a password is configured" posture;
+`novaconium/bin/create-admin-user.php` creates an admin from the CLI
+instead (password via stdin), which lets a deploy create the user
+*before* flipping the flag so the open window never exists — it's also
+the lockout-recovery path (usage: ``, password via
+stdin). Every account has a **unique email address** (`users.email`),
+stored normalized via `Lib\Validate::isEmail()` (trim + lowercase) so
+the planned email-verification feature (see `novaconium/ISSUES.md`
+Backlog) can match case-insensitively — not used for login (username)
+or any mail yet. `/admin/users` is the management UI (create — always
+`'registered'` except the first / disable / enable / delete / change
+group / promote-demote / change email / change password); a disabled
+**or deleted** user fails login and any existing session dies on its
+next request (`currentUser()` re-checks the row per request), and
+disabling, demoting, *or deleting* the last **active admin** is refused
+— the empty-table setup window doesn't reopen once users exist, so that
+would be a permanent lockout. Delete is a hard delete (username/email
+become reusable); disable is the keep-but-shut-out option. `/admin/login` accepts a
+`?return=` path (how `Lib\Access` sends someone back to the gated page
+after login), validated to a local path (must start `/`, not `//`, no
+`\`) so a crafted login link can't bounce a fresh login to another
+site; with no return path, admins land on `/admin`, registered users on
+`/`. Login
+regenerates the session id (`Lib\Session::regenerate()`, added for this)
+against session fixation; logout is a real page now — the pre-router
+`/admin/logout` special case in `bootstrap.php` is gone — and it is
+**POST-only with a GET confirm form** (same shape as
+`/admin/clear-cache`), not logout-on-GET: the content-index crawl runs
+every page's sidecar as a GET, so a GET side effect there would end the
+crawling admin's own session mid-reindex. Passwords are read from `$_POST` directly, not
+`Lib\Input` (the documented exact-value exception — see `Lib\Input`'s
+doc-comment, which now points at the login/users sidecars). `Renderer`
+still exposes the `admin_auth_enabled` Twig global (now mirroring the
+config flag) so `admin/index.twig` can conditionally show the
+"Admin users"/"Logout" links — a derived display flag, not the
+enforcement mechanism itself, which never depends on Twig.
`Lib\Db` (`novaconium/lib/Db.php`) is the SQLite/MySQL groundwork tracked
in `novaconium/ISSUES.md` — a thin, no-ORM PDO wrapper, `Lib\` (not `App\`)
@@ -256,19 +298,45 @@ check (paywall content is the next one on the roadmap likely to hit this)
needs to make the same check here, not just at the point where the
request is first authorized.
-`AdminAuth::isAuthenticated(string $username, string $passwordHash): bool`
-(`novaconium/src/AdminAuth.php`) is the credential check on its own, with
-no response side effects, extracted out of `requireLogin()` (which still
-does the same check, then issues the `401` challenge on failure) so a
-different caller can react to failure differently. The draft-page gate in
-`bootstrap.php` is the first such caller: on failure it renders a plain
-404 via the same path an unmatched route takes, not a login prompt —
-prompting for credentials at a draft URL would itself reveal that
-something is gated there, which defeats the point of hiding it. Returns
-`true` (open access) when `$passwordHash` is empty, mirroring
-`requireLogin()`'s existing no-op-when-unset posture, so a draft behaves
-consistently with the rest of `/admin/*`: wide open until a password is
-configured, gated once one is.
+`AdminAuth::isAdmin(bool $enabled): bool` / `::isLoggedIn(bool
+$enabled): bool` (`novaconium/src/AdminAuth.php`) are the access checks
+on their own, with no response side effects — `requireLogin()` is
+`isLoggedIn()` plus a 303 redirect to `/admin/login` on failure, and a
+different caller can react to failure differently. The draft-page gate
+in `bootstrap.php` is the first such caller, and it uses `isAdmin()`
+(drafts are admin-only — a logged-in registered user gets the same 404
+as an anonymous visitor): on failure it renders a plain 404 via the same
+path an unmatched route takes, not a login redirect — bouncing to a
+login at a draft URL would itself reveal that something is gated there,
+which defeats the point of hiding it. Both return `true` (open access)
+when `$enabled` is false or while the `users` table is empty, mirroring
+`requireLogin()`'s posture, so a draft behaves consistently with the
+rest of `/admin/*`: wide open until the feature is enabled and a first
+user exists, gated after that.
+
+`Lib\Access` (`novaconium/lib/Access.php`) is the sidecar-level content
+gate — how a page (or a section, one line per page; a shared
+`_access.php` in the section directory is the documented pattern, since
+non-`index.*` files are invisible to the router) is assigned to a user
+or group: `Access::require('group:members', 'user:bob')` returns `null`
+(allowed — no rules at all means any logged-in user, and **admins pass
+every rule**) or a `Response` the sidecar returns as-is (anonymous → 303
+to `/admin/login?return=`; logged-in-but-not-allowed → plain-text
+404, same hide-don't-tease posture as drafts). See
+`/admin/docs/access-control`. **Public is the default, and static pages
+are always public**: a page with no sidecar can't call `Access` — and
+that's load-bearing, since only sidecar-less pages are written to the
+static HTML cache; a gated page necessarily has a sidecar, so it can
+never leak through the cache — the caching/auth standing rule below is
+satisfied by construction, with no bootstrap exclusion needed. Same
+open-until-configured / zero-DB-footprint posture as the rest of admin
+auth when the flag is off or no users exist. Deliberately **no side
+effects on deny** (the return path travels in the redirect URL, not the
+session): the content-index crawl runs every sidecar as an anonymous
+GET, so gated pages drop out of `/search`/`/sitemap.xml` automatically
+(the crawler discards `Response`s) and a crawl must never scribble on
+the visiting user's session — the same reasoning that made
+`/admin/logout` POST-only.
`App\ContentIndexer` (`novaconium/src/ContentIndexer.php`) is the shared
crawler behind `/sitemap.xml`, `/search`, and blog tag browsing (see
@@ -442,13 +510,15 @@ site behavior for the next person.
query — use PDO prepared statements once a database layer exists); don't
add an `sqlSafe()`-style method to `Input`. One documented exception: a
field needing an exact, unmodified value (e.g. a password about to be
- hashed) should read `$_POST` directly instead — see
- `novaconium/pages/admin/password-hash/index.php`. `Lib\Csrf`
+ hashed or verified) should read `$_POST` directly instead — see the
+ password fields in `novaconium/pages/admin/users/index.php` and
+ `novaconium/pages/admin/login/index.php`. `Lib\Csrf`
(`novaconium/lib/Csrf.php`) is standalone session-token CSRF protection, not
wired into `FormValidator` — a sidecar calls `Csrf::verify()` directly.
- It's the first thing in the framework to start a native PHP session (only
- lazily, when a form actually calls it), which is otherwise unrelated to
- `AdminAuth`'s own session-free Basic Auth.
+ It was the first thing in the framework to start a native PHP session
+ (only lazily, when a form actually calls it); `Lib\Session` and
+ `AdminAuth`'s session login now share that same native session, safely
+ in any order.
- Don't use Twig's `|slice` filter on a **string** (as opposed to an
array) — it unconditionally calls PHP's `mb_substr()` with no fallback
(`novaconium/vendor/twig/src/Extension/CoreExtension.php`), which
diff --git a/App/config.php b/App/config.php
index d6c7113..1d9ff8b 100644
--- a/App/config.php
+++ b/App/config.php
@@ -15,11 +15,11 @@ return [
// 'matomo_url' => 'https://matomo.example.com/',
// 'matomo_site_id' => '1',
- // Docs: /admin/docs/admin-auth — generate a hash with:
- // php -r "echo password_hash('yourpassword', PASSWORD_DEFAULT), PHP_EOL;"
- // or use the built-in /admin/password-hash form.
- // 'admin_username' => 'admin',
- // 'admin_password_hash' => '$2y$10$...',
+ // Docs: /admin/docs/admin-auth — session login for /admin/* against
+ // the SQLite-backed users table. After enabling, create the first user
+ // at /admin/users, or beforehand (safer) with:
+ // php novaconium/bin/create-admin-user.php
+ // 'admin_auth_enabled' => true,
// Docs: /admin/docs/database — adds (or overrides) named Lib\Db
// connections. This merges into db_connections by name rather than
@@ -38,9 +38,9 @@ return [
// ],
// ],
- // Docs: /admin/docs/drafts — requires admin_password_hash above to be
- // set to actually gate anything; open access otherwise, same as the
- // rest of /admin/*.
+ // Docs: /admin/docs/drafts — requires admin_auth_enabled above (and at
+ // least one user) to actually gate anything; open access otherwise,
+ // same as the rest of /admin/*.
// 'draft_routes' => ['blog/upcoming-post'],
// Docs: /admin/docs/content-index — powers /sitemap.xml, /search, and
diff --git a/App/pages/about/index.twig b/App/pages/about/index.twig
index 4f488f9..6125b4c 100644
--- a/App/pages/about/index.twig
+++ b/App/pages/about/index.twig
@@ -31,7 +31,7 @@
Everything the framework itself ships — default pages, default library classes, the root layout — lives under novaconium/, and can be overridden by placing a same-named file under App/, the only directory a site author is expected to touch. The same override mechanism covers configuration, too: any key in novaconium/config.php can be replaced piecemeal from App/config.php.
-
Beyond routing and templating, Novaconium ships with SEO meta tags (canonical links, Open Graph, Twitter Card), optional Matomo analytics with automatic 404 tracking, and an HTTP Basic Auth gate reusable across every /admin/* page — all off or sensible by default, and all documented at {{ icons.book() }}/admin/docs, rendered live from this same running instance rather than a separate website.
+
Beyond routing and templating, Novaconium ships with SEO meta tags (canonical links, Open Graph, Twitter Card), optional Matomo analytics with automatic 404 tracking, and a multi-user admin login (with browser-based user management) covering every /admin/* page — all off or sensible by default, and all documented at {{ icons.book() }}/admin/docs, rendered live from this same running instance rather than a separate website.
It's a good fit for small marketing sites, blogs, and internal tools where a full framework would be overkill but a flat-file site generator alone falls short of real server-side logic. The source is on Git if you want to see how it's put together: {{ icons.git() }}git.4lt.ca/4lt/novaconium.
Built-in analytics tracking and an HTTP Basic Auth gate for /admin/* — both off until you turn them on in App/config.php.
+
Built-in analytics tracking and a multi-user session login for /admin/* — both off until you turn them on in App/config.php.
Override anything
diff --git a/README.md b/README.md
index 5d228e7..c23d614 100644
--- a/README.md
+++ b/README.md
@@ -12,11 +12,12 @@ A tiny, Hugo-flavored PHP micro-framework. Routes are directories on disk, pages
- **Layout inheritance** — `_layout/layout.twig` directories are resolved by walking upward from the matched page, so you can override the layout for a whole subtree.
- **SEO boilerplate out of the box** — the default layout ships meta description, canonical link, robots, Open Graph, and Twitter Card tags, all overridable per-page via Twig blocks.
- **Built-in Matomo analytics** — set `matomo_url` and `matomo_site_id` in `App/config.php` to enable tracking site-wide, including automatic 404 tracking. Off by default.
-- **Admin authentication** — gate every `/admin/*` route behind HTTP Basic Auth by setting `admin_username`/`admin_password_hash` in `App/config.php`; reusable for any admin page a project adds later, with a `/admin/logout` link to clear cached credentials and a built-in `/admin/password-hash` form so generating the hash doesn't require the CLI. Off by default.
+- **Admin authentication** — gate every `/admin/*` route behind a session login with multi-user management: a SQLite-backed `users` table, `/admin/login`/`/admin/logout`, and an `/admin/users` page to create, disable, delete, group, promote/demote, and change the email or password of accounts (plus a `novaconium/bin/create-admin-user.php` CLI for the first user or deploy scripts). Two roles: the first user created is the admin; everyone after is a registered user with an optional group. Every account has a unique, normalized email address — groundwork for email verification later. Enabled with a single `admin_auth_enabled` flag in `App/config.php`; off by default, and reusable for any admin page a project adds later.
+- **Access control** — assign a page (or a section, one line per page) to a user or group from its sidecar: `Access::require('group:members')` returns `null` or a ready-made `Response` (login redirect with a return path, or a 404 for the wrong account). Public is the default — a sidecar that never calls it is untouched, and static (sidecar-less, cached) pages are always public by construction. Gated pages stay out of `/search` and `/sitemap.xml` automatically.
- **Draft pages** — list a route under `draft_routes` in `App/config.php` to make it visible only to an authenticated admin; anyone else gets a plain 404, not a login prompt. Reuses the admin auth check directly, and is excluded from static caching so a cached copy can't leak the draft to the public. See `/admin/docs/drafts`.
- **Dark/light theme toggle** — a nav button flips a `data-theme` attribute (persisted to `localStorage`) that swaps every color via CSS custom properties; both palettes live in `App/sass/_colors.sass`, same override mechanism as everything else.
- **Self-hosted spam prevention & form validation** — `Lib\SpamGuard`, a reusable class for any form: a CSS-hidden honeypot field plus a submission-timing check, no external CAPTCHA service, site key, or outbound API call. Pairs with `Lib\FormValidator` (accumulating required-field/email/length checks) and `Lib\Validate` (the underlying validation primitives — email, length, phone, postal/zip, spam-word checks). All three ship in `novaconium/lib/`, demonstrated on the contact form.
-- **Form security by default** — `Lib\Input`, a cleaning accessor for `$_POST`/`$_GET` (defense-in-depth against HTML/script injection, not a substitute for parameterized queries), and `Lib\Csrf`, standalone session-token CSRF protection called directly from a sidecar. Both ship in `novaconium/lib/`, wired into the contact form, `/admin/clear-cache`, and `/admin/password-hash`.
+- **Form security by default** — `Lib\Input`, a cleaning accessor for `$_POST`/`$_GET` (defense-in-depth against HTML/script injection, not a substitute for parameterized queries), and `Lib\Csrf`, standalone session-token CSRF protection called directly from a sidecar. Both ship in `novaconium/lib/`, wired into the contact form, `/admin/clear-cache`, `/admin/login`, and `/admin/users`.
- **SQLite/MySQL database, zero setup** — `Lib\Db`, a thin PDO wrapper (no ORM) supporting multiple named connections open at once — e.g. this site's own SQLite data plus a MySQL connection to a legacy database, usable in the same sidecar — each with its own plain-SQL migration convention, applied automatically on first use or via `php novaconium/bin/migrate.php`. SQLite data lives in a project-owned top-level `data/` directory, outside both `public/` and `novaconium/`. See `/admin/docs/database`.
- **Sessions with flash data** — `Lib\Session`, a thin wrapper around native PHP sessions with CodeIgniter-style flash values (set now, readable on exactly the next request) for post/redirect/GET flows without a query-string flag. Lazy-start, same mechanism `Lib\Csrf` already uses. See `/admin/docs/session`.
- **Content index: sitemap, search, tags** — `/sitemap.xml`, full-text `/search` (SQLite FTS5), and blog tag browsing all share one crawler that renders every page and harvests `keywords`/`tags`/`changefreq`/`priority` Twig blocks via Twig's own `renderBlock()` — no front-matter, no separate metadata files. Off by default (depends on SQLite); reindexes lazily on demand or via `php novaconium/bin/index-content.php`. See `/admin/docs/content-index`.
@@ -98,6 +99,7 @@ The full framework documentation — routing, sidecars, libraries, database, ses
- [SEO](http://127.0.0.1:8000/admin/docs/seo)
- [Matomo](http://127.0.0.1:8000/admin/docs/matomo)
- [Admin authentication](http://127.0.0.1:8000/admin/docs/admin-auth)
+- [Access control](http://127.0.0.1:8000/admin/docs/access-control)
- [Draft pages](http://127.0.0.1:8000/admin/docs/drafts)
- [Styling](http://127.0.0.1:8000/admin/docs/styling)
- [Project layout](http://127.0.0.1:8000/admin/docs/project-layout)
diff --git a/novaconium/ISSUES.md b/novaconium/ISSUES.md
index 0971bb9..2d1e98f 100644
--- a/novaconium/ISSUES.md
+++ b/novaconium/ISSUES.md
@@ -51,19 +51,17 @@ expected vs. actual behavior. For features, include the motivating use case.>
## Backlog
-Suggested build order (foundations first, since admin login builds on
-three of the others):
+Suggested build order (foundations first):
-1. **Media/file manager** — no hard dependency; usable standalone, though
- best gated behind admin login once that exists.
-2. **Admin login & user management** — SQLite groundwork and session
- handling it needed are both done; ready to build.
-3. **In-house comments** — needs admin login & user management (comments
- are tied to real user accounts, not anonymous); build right after it.
-4. **Ecommerce functionality** — needs admin login & user management
- (order/product admin, and customer accounts); SQLite groundwork and
- session handling (cart) it needed are both done.
-5. **Paywall functionality** — needs everything Ecommerce needs, plus
+1. **Media/file manager** — no hard dependency; usable standalone, and
+ already gated behind admin login the moment it exists under `/admin/*`.
+2. **In-house comments** — admin login & user management (Done
+ 2026-07-14) unblocked this; comments are tied to real user accounts,
+ not anonymous.
+3. **Ecommerce functionality** — its dependencies (SQLite groundwork,
+ session handling for the cart, admin login for order/product admin)
+ are all done now.
+4. **Paywall functionality** — needs everything Ecommerce needs, plus
Ecommerce itself for the recurring-billing/payment-gateway plumbing;
build after it rather than in parallel — also now has a concrete
precedent to follow for the "gated content must skip the static cache"
@@ -74,10 +72,30 @@ three of the others):
MySQL support, Session handling (with flash sessions), Draft pages
(admin-only preview), Blog tags/categories + Internal search + XML
sitemap (shipped together as one content index — see Done), Blog RSS
-feed, and Syntax highlighting on code blocks all shipped 2026-07-14.
+feed, Syntax highlighting on code blocks, and Admin login & user
+management all shipped 2026-07-14.
See **Won't Do** below for 404 tracking, dropped in favor of Matomo.
+### Email verification for user accounts
+
+- **Type:** Feature
+- **Status:** Backlog
+- **Priority:** Medium
+- **Depends on:** Admin login & user management (Done)
+- **Added:** 2026-07-14
+
+Verify a user's email address by sending a confirmation link — the
+groundwork is already in place: every account has a required, unique,
+normalized email (`users.email`, added the same day as user deletion —
+see User deletion & email addresses under Done). Needs a `verified_at`
+(or token) column, a token-generation/expiry scheme, a send path
+(`Lib\Mailer` is currently a log-to-file stand-in — this feature is
+probably what forces it to grow a real mail transport), and a decision
+on what an unverified account may do (log in but fail `Lib\Access`
+rules? not log in at all?). Also the natural home for password-reset-
+by-email later, which shares all the same plumbing.
+
### Media/file manager
- **Type:** Feature
@@ -97,31 +115,12 @@ wanted later, in which case that part could ride on SQLite groundwork).
Needs basic safety handling: extension allowlist, filename sanitization,
and a max upload size, since this is a file-write surface.
-### Admin login & user management
-
-- **Type:** Feature
-- **Status:** Backlog
-- **Priority:** Medium
-- **Depends on:** SQLite groundwork (Done), Session handling (with flash sessions) (Done)
-- **Added:** 2026-07-12
-
-A single-user HTTP Basic Auth stopgap now gates `/admin/*`
-(`novaconium/src/AdminAuth.php`, `admin_username`/`admin_password_hash` in
-`App/config.php` — see `/admin/docs/admin-auth`), so `/admin` is no longer
-wide open by default choice. This entry is the real, larger replacement:
-multiple accounts, a user store (the SQLite groundwork above — a `users`
-table with hashed passwords via `password_hash()`/`password_verify()`, no
-external auth library), proper sessions instead of Basic Auth (rides on
-session handling above), and basic user management (create/disable a
-user, change password). Ship this by replacing `AdminAuth::requireLogin()`
-with the new mechanism, not layering on top of it.
-
### In-house comments
- **Type:** Feature
- **Status:** Backlog
- **Priority:** Medium
-- **Depends on:** Admin login & user management, SQLite groundwork (Done)
+- **Depends on:** Admin login & user management (Done), SQLite groundwork (Done)
- **Added:** 2026-07-14
A self-hosted comments library — no third-party service (Disqus,
@@ -149,7 +148,7 @@ the same way the contact form does).
- **Type:** Feature
- **Status:** Backlog
- **Priority:** Low
-- **Depends on:** SQLite groundwork (Done), Session handling (with flash sessions) (Done), Admin login & user management
+- **Depends on:** SQLite groundwork (Done), Session handling (with flash sessions) (Done), Admin login & user management (Done)
- **Added:** 2026-07-12
Product catalog, cart, checkout, and order storage — a `products` /
@@ -169,14 +168,18 @@ planning it all up front here.
- **Type:** Feature
- **Status:** Backlog
- **Priority:** Low
-- **Depends on:** Ecommerce functionality (recurring billing/payment plumbing), SQLite groundwork (Done), Session handling (with flash sessions) (Done), Admin login & user management
+- **Depends on:** Ecommerce functionality (recurring billing/payment plumbing), SQLite groundwork (Done), Session handling (with flash sessions) (Done), Admin login & user management (Done)
- **Added:** 2026-07-12
Subscription/membership content gating, similar to OnlyFans/Patreon:
recurring billing tied to a user account, content (posts, pages, media)
marked as gated behind an active subscription, and access checks in
-sidecars (`$_SESSION`'s logged-in user + subscription status, similar to
-how admin login gates `/admin/*`). Reuses Ecommerce's payment-gateway
+sidecars (`$_SESSION`'s logged-in user + subscription status) — the
+access-check half of this now has a shipped foundation to build on:
+`Lib\Access` (see User roles, groups & page access control in Done)
+already handles login-gated/group-gated sidecar content; a paywall
+mostly adds "does this account have an active subscription" as a rule
+source on top of it. Reuses Ecommerce's payment-gateway
plumbing for the recurring-charge side rather than integrating a payment
provider a second time — build after Ecommerce rather than in parallel.
Also needs a decision on how gated content is authored (a `gated: true`
@@ -192,6 +195,133 @@ _Nothing yet._
## Done
+### User deletion & email addresses
+
+- **Type:** Feature
+- **Status:** Done
+- **Priority:** Medium
+- **Depends on:** Admin login & user management (Done)
+- **Added:** 2026-07-14
+- **Shipped:** 2026-07-14
+
+Second same-day follow-up to Admin login & user management (below),
+also pre-commit — so the `email` column went into the existing
+`0002_create_users.sql` like the roles change before it. `/admin/users`
+gained a hard-delete action (username/email become reusable; any live
+session dies on its next request via the same per-request row re-check
+disabling uses; the last-active-admin guard covers delete as well as
+disable/demote) and a change-email action. Every account now requires a
+unique email address — validated and normalized (trim + lowercase) via
+the existing `Lib\Validate::isEmail()`, so uniqueness is
+case-insensitive by construction (verified: `BOB@example.com` collides
+with `bob@example.com`) — on the create form, the change-email action,
+and `bin/create-admin-user.php` (now ``). Not used
+for login or any mail yet; it exists so the planned email-verification
+flow (new Backlog entry above) has an address for every account that
+predates it. Delete stays deliberately distinct from disable in the UI
+(inside a confirm-style `` with a warning): disable is
+keep-but-shut-out, delete is gone-for-good.
+
+### User roles, groups & page access control
+
+- **Type:** Feature
+- **Status:** Done
+- **Priority:** Medium
+- **Depends on:** Admin login & user management (Done)
+- **Added:** 2026-07-14
+- **Shipped:** 2026-07-14
+
+Follow-up to Admin login & user management (below), shipped the same day
+before any of it was committed — so the `users` schema change went into
+the existing `0002_create_users.sql` rather than a third migration. Two
+roles (`users.role`): the first user created is `'admin'`, everyone
+after is `'registered'` with an optional single group
+(`users.user_group`, a plain text label matched exactly — deliberately
+no groups table). `/admin/*` and draft preview are admin-only now — a
+logged-in registered user gets a plain 404 there (not a login redirect;
+they're authenticated, what they lack is the role) — and the
+last-active-user lockout guard became a last-active-*admin* guard,
+applied to both the disable and the new demote action (`/admin/users`
+also grew group-assignment and promote/demote).
+
+`Lib\Access` (`novaconium/lib/Access.php`) is the sidecar-level content
+gate, per the "assign a page/section to a user or group" spec:
+`Access::require('group:members', 'user:bob')` at the top of a sidecar
+returns `null` or a ready-made `Response` (anonymous → login redirect
+carrying a `?return=` path, validated against open redirects;
+wrong-account → 404, drafts' hide-don't-tease posture). No rules = any
+logged-in user; admins pass everything. Public is the default twice
+over: sidecars that never call it are untouched, and static
+(sidecar-less) pages *can't* call it — always public, which also means
+a gated page necessarily has a sidecar and is therefore never written
+to the static HTML cache: the caching/auth standing rule satisfied by
+construction, no bootstrap exclusion needed. Sections are gated by
+composition (a shared `_access.php` file `require`'d by each sidecar in
+the section), not per-directory config. `Access::require()` has no side
+effects on deny, so the content-index crawl (anonymous GET per sidecar)
+both drops gated pages from `/search`/`/sitemap.xml` automatically and
+can't touch the visiting user's session. Verified end-to-end with three
+real accounts (admin / registered-with-group / registered-without) and
+a cookie jar each: rule matrix, return-path round trip,
+`//evil.com`-style return rejection, registered-user 404s on `/admin/*`
+and drafts, promote/demote + guards, group reassignment taking effect
+immediately, crawl exclusion, and flag-off zero-footprint posture.
+Documented at `/admin/docs/access-control` (new topic, linked from the
+docs nav/index), with supporting updates to `admin-auth`, `drafts`,
+`sidecars`, `config`, and `libraries`.
+
+### Admin login & user management
+
+- **Type:** Feature
+- **Status:** Done
+- **Priority:** Medium
+- **Depends on:** SQLite groundwork (Done), Session handling (with flash sessions) (Done)
+- **Added:** 2026-07-12
+- **Shipped:** 2026-07-14
+
+Shipped as specified: the single-user HTTP Basic Auth stopgap that gated
+`/admin/*` was **replaced, not layered on** — `AdminAuth` keeps its name
+and call sites (`bootstrap.php`'s admin gate and draft gate) but is now a
+session login (`Lib\Session`, with a new `Session::regenerate()` against
+session fixation) against a `users` table
+(`novaconium/migrations/0002_create_users.sql`, the second
+framework-shipped migration) with `password_hash()`/`password_verify()`
+and no external auth library. The `admin_username`/`admin_password_hash`
+config keys and the `/admin/password-hash` page are gone, superseded by a
+single `admin_auth_enabled` flag (default `false`) plus new
+`/admin/login`, `/admin/logout` (a real page now — the pre-router special
+case in `bootstrap.php` is gone too — and POST-only with a GET confirm
+form, because the content-index crawl runs every sidecar as a GET and a
+logout-on-GET would have ended the crawling admin's own session the first
+time a lazy reindex rendered it), and `/admin/users`
+(create/disable/enable/change-password) pages, and a
+`novaconium/bin/create-admin-user.php` CLI (password via stdin, for
+deploy scripts and lockout recovery). Documented at
+`/admin/docs/admin-auth`.
+
+Decisions worth recording: same zero-footprint posture as the content
+index (flag off → the three auth routes 404 and `Lib\Db` is never
+touched, so no `data/novaconium.sqlite` appears — the route sidecars
+self-load config the same way `/search` does); first-user bootstrap keeps
+the gate open only while the `users` table is empty (creating the first
+user at `/admin/users` auto-logs you in as it and closes the gate —
+running the CLI *before* enabling the flag avoids the window entirely);
+`admin/login` is the one `/admin/*` route exempted from
+`requireLogin()`, or its redirect would loop; disabling a user kills any
+live session on its next request (`currentUser()` re-checks the row per
+request), and disabling the last active user is refused since the
+empty-table window never reopens — that would be a permanent lockout.
+Login/user passwords read `$_POST` directly, extending the documented
+`Lib\Input` exact-value exception (verified with a password containing
+`<>` end-to-end). Verified route-by-route with real HTTP requests and a
+cookie jar: flag off (404s, no DB file), setup window, first-user
+auto-login, fresh-client redirect, wrong/right password, logout,
+enable/disable/change-password, live-session lockout on disable,
+last-user guard, CSRF failure paths, CLI creation, and draft gating via
+the session cookie (including confirming a pre-existing static-cache copy
+of a page still serves after the page is marked a draft until the cache
+is cleared — the documented cache-clear step, not a new bug).
+
### Syntax highlighting on code blocks
- **Type:** Feature
diff --git a/novaconium/bin/create-admin-user.php b/novaconium/bin/create-admin-user.php
new file mode 100644
index 0000000..308b84c
--- /dev/null
+++ b/novaconium/bin/create-admin-user.php
@@ -0,0 +1,75 @@
+
+//
+// The password is read from stdin — typed at the prompt (echo suppressed
+// where the terminal supports it), or piped:
+//
+// echo 'the-password' | php novaconium/bin/create-admin-user.php admin admin@example.com
+//
+// Deliberately not gated on admin_auth_enabled: creating the row is
+// harmless while the gate is off, and doing it first is the safer order.
+
+$username = trim((string) ($argv[1] ?? ''));
+$email = Validate::isEmail((string) ($argv[2] ?? ''));
+if ($username === '' || strlen($username) > 64 || $email === false) {
+ fwrite(STDERR, "Usage: php novaconium/bin/create-admin-user.php \n");
+ exit(1);
+}
+
+// Db::connection() runs pending migrations on first touch, so the users
+// table exists after this even on a fresh clone.
+$exists = (bool) Db::query('SELECT EXISTS(SELECT 1 FROM users WHERE username = ?)', [$username])->fetchColumn();
+if ($exists) {
+ fwrite(STDERR, "A user named '{$username}' already exists.\n");
+ exit(1);
+}
+
+$emailExists = (bool) Db::query('SELECT EXISTS(SELECT 1 FROM users WHERE email = ?)', [$email])->fetchColumn();
+if ($emailExists) {
+ fwrite(STDERR, "A user with the email '{$email}' already exists.\n");
+ exit(1);
+}
+
+$interactive = stream_isatty(STDIN);
+if ($interactive) {
+ fwrite(STDOUT, "Password for '{$username}': ");
+ // Suppress echo while the password is typed; restore afterwards.
+ // shell_exec() may be unavailable/no-op on some setups — then the
+ // password just echoes, same as any basic CLI prompt.
+ shell_exec('stty -echo 2> /dev/null');
+}
+
+$password = rtrim((string) fgets(STDIN), "\r\n");
+
+if ($interactive) {
+ shell_exec('stty echo 2> /dev/null');
+ fwrite(STDOUT, "\n");
+}
+
+if (strlen($password) < 8) {
+ fwrite(STDERR, "Use a password of at least 8 characters.\n");
+ exit(1);
+}
+
+// Always role 'admin', as the script name says — /admin/users is the
+// place to create registered users; this exists for first-user setup and
+// lockout recovery, both of which need an admin.
+Db::query(
+ "INSERT INTO users (username, email, password_hash, role, user_group, is_disabled, created_at) VALUES (?, ?, ?, 'admin', '', 0, ?)",
+ [$username, $email, password_hash($password, PASSWORD_DEFAULT), gmdate('Y-m-d\TH:i:s\Z')]
+);
+
+echo "User '{$username}' created.\n";
+echo "If admin auth isn't enabled yet, set 'admin_auth_enabled' => true in App/config.php.\n";
diff --git a/novaconium/bootstrap.php b/novaconium/bootstrap.php
index 97b0db4..4bca977 100644
--- a/novaconium/bootstrap.php
+++ b/novaconium/bootstrap.php
@@ -4,11 +4,9 @@
* Front-controller wiring. Every request — via public/index.php (Apache) or
* public/router.php (php -S) — ends up require'ing this one file, which:
* 1. loads config (framework defaults + optional App/ override)
- * 2. handles the one hardcoded route (/admin/logout) that exists outside
- * the normal page tree
- * 3. resolves the URL to a page directory (Router)
- * 4. gates /admin/* behind Basic Auth, if configured (AdminAuth)
- * 5. renders the matched page, or a 404 (Renderer)
+ * 2. resolves the URL to a page directory (Router)
+ * 3. gates /admin/* behind session login, if enabled (AdminAuth)
+ * 4. renders the matched page, or a 404 (Renderer)
* There's no framework "kernel" class doing this — it's just a plain
* top-to-bottom script, deliberately, so a dev can read the whole
* request lifecycle in one file without chasing an abstraction.
@@ -37,20 +35,7 @@ if ($config['debug']) {
ini_set('display_errors', '1');
}
-// Trim the query string and any trailing slash so /admin/logout/ and
-// /admin/logout?x=1 both match the check below the same way $router does
-// internally for real page routes.
$requestUri = $_SERVER['REQUEST_URI'] ?? '/';
-$requestPath = rtrim(parse_url($requestUri, PHP_URL_PATH) ?: '/', '/');
-
-// /admin/logout isn't a real page under App/pages/ or novaconium/pages/ —
-// there's nothing to route to, so it's special-cased here before the
-// router even runs. AdminAuth::logout() always sends a fresh 401 challenge
-// (the standard trick for "logging out" of HTTP Basic Auth, which has no
-// real server-side session to invalidate) and exits immediately.
-if ($requestPath === '/admin/logout') {
- AdminAuth::logout();
-}
// Router::resolve() only answers "does a page exist at this URL, and if
// so which directory / what params?" — it never touches Twig, sidecars, or
@@ -58,36 +43,49 @@ if ($requestPath === '/admin/logout') {
$router = new Router($config['pages_dirs']);
$route = $router->resolve($requestUri);
-// Every route under /admin/* — clear-cache, docs, password-hash, and any
-// admin page a project adds later — is gated here, once, rather than in
-// each page individually. A new admin page is automatically protected the
-// moment it exists; nothing to remember to wire up. No-op (open access)
-// when admin_password_hash is empty, which is the default. See
-// novaconium/src/AdminAuth.php and /admin/docs/admin-auth.
-$isAdminRoute = $route->found && ($route->dir === 'admin' || str_starts_with((string) $route->dir, 'admin/'));
-if ($isAdminRoute) {
- AdminAuth::requireLogin($config['admin_username'], $config['admin_password_hash']);
-}
-
// Both of these are derived, request-independent config values that get
// handed to the Renderer so it can expose them to every Twig template as
// globals (matomo_url/matomo_site_id/admin_auth_enabled) — see
// Renderer::__construct(). Normalizing the trailing slash here means every
// template can safely do `matomo_url + 'matomo.php'` without checking.
$matomoUrl = $config['matomo_url'] !== '' ? rtrim($config['matomo_url'], '/') . '/' : '';
-$adminAuthEnabled = $config['admin_password_hash'] !== '';
+$adminAuthEnabled = (bool) $config['admin_auth_enabled'];
$cache = new Cache($config['cache_dir']);
$renderer = new Renderer($config['pages_dirs'], $cache, $adminAuthEnabled, $matomoUrl, $config['matomo_site_id'], $config['site_name'], $config['content_index_enabled']);
-// A route listed in draft_routes is only visible to an authenticated admin
-// — anyone else gets treated exactly like a route that doesn't exist at
-// all (a plain 404, not a login prompt), so a draft's existence isn't
-// revealed to anyone poking at the URL. See /admin/docs/drafts. Reuses the
-// same credential check /admin/* uses (AdminAuth::isAuthenticated()) —
-// in practice an admin authenticates by visiting /admin once first; the
-// browser then resends those same Basic Auth credentials to draft URLs
-// too, since they share the same origin/realm.
+// Every route under /admin/* — clear-cache, docs, users, and any admin
+// page a project adds later — is gated here, once, rather than in each
+// page individually. A new admin page is automatically protected the
+// moment it exists; nothing to remember to wire up. Two steps: nobody
+// logged in → redirect to the login form (requireLogin() exits); logged
+// in but not an admin (a 'registered' user — see /admin/docs/admin-auth)
+// → the same plain 404 an unmatched route gets, since bouncing an
+// already-authenticated user back to the login form would be a lie (what
+// they lack is the admin role, not a session). The one exemption is the
+// login form itself, which has to stay reachable logged-out or
+// requireLogin()'s redirect to it would loop forever. No-op (open access)
+// when admin_auth_enabled is false (the default), or while no users exist
+// yet (so the first user can be created at /admin/users). See
+// novaconium/src/AdminAuth.php and /admin/docs/admin-auth.
+$isAdminRoute = $route->found && ($route->dir === 'admin' || str_starts_with((string) $route->dir, 'admin/'));
+if ($isAdminRoute && $route->dir !== 'admin/login') {
+ AdminAuth::requireLogin($config['admin_auth_enabled']);
+
+ if (!AdminAuth::isAdmin($config['admin_auth_enabled'])) {
+ $renderer->renderNotFound($requestUri);
+ return;
+ }
+}
+
+// A route listed in draft_routes is only visible to a logged-in admin —
+// anyone else (including logged-in registered users) gets treated exactly
+// like a route that doesn't exist at all (a plain 404, not a login
+// prompt), so a draft's existence isn't revealed to anyone poking at the
+// URL. See /admin/docs/drafts. Reuses the same access check /admin/* uses
+// (AdminAuth::isAdmin()) — an admin logs in once at /admin/login, and the
+// session cookie covers draft URLs too, since it's scoped to the whole
+// origin.
$isDraftRoute = $route->found && in_array($route->dir, $config['draft_routes'], true);
// $route->found is false for anything Router couldn't match to a real page
@@ -103,7 +101,7 @@ $isDraftRoute = $route->found && in_array($route->dir, $config['draft_routes'],
// therefore AdminAuth::requireLogin()) ever runs again — permanently
// serving the admin panel to anyone, unauthenticated, straight from the
// static cache. See novaconium/src/Renderer.php.
-if (!$route->found || ($isDraftRoute && !AdminAuth::isAuthenticated($config['admin_username'], $config['admin_password_hash']))) {
+if (!$route->found || ($isDraftRoute && !AdminAuth::isAdmin($config['admin_auth_enabled']))) {
$renderer->renderNotFound($requestUri);
return;
}
diff --git a/novaconium/config.php b/novaconium/config.php
index ce7d8d2..e41af59 100644
--- a/novaconium/config.php
+++ b/novaconium/config.php
@@ -28,16 +28,21 @@ return [
'matomo_url' => '',
'matomo_site_id' => '',
- // Gates every /admin/* route (clear-cache, docs, and any future admin
- // page) behind HTTP Basic Auth. Leave admin_password_hash empty (the
- // default) to disable the gate entirely — matches this project's
- // existing wide-open behavior until a project opts in. Generate a hash
- // with: php -r "echo password_hash('yourpassword', PASSWORD_DEFAULT), PHP_EOL;"
- // and set both via App/config.php, e.g.:
- // 'admin_username' => 'admin',
- // 'admin_password_hash' => '$2y$10$...',
- 'admin_username' => 'admin',
- 'admin_password_hash' => '',
+ // Gates every /admin/* route (clear-cache, docs, users, and any future
+ // admin page) behind a session login against the `users` table on
+ // Lib\Db's default connection — see /admin/docs/admin-auth. The first
+ // user created is the admin; users after that are 'registered', each
+ // with an optional group, and see whatever content sidecars grant via
+ // Lib\Access (see /admin/docs/access-control) — /admin/* itself 404s
+ // for them. Off by default because it depends on SQLite (same
+ // reasoning as content_index_enabled below): when false, /admin/* is
+ // wide open, /admin/login, /admin/logout, and /admin/users 404,
+ // Access::require() allows everything, and nothing ever touches
+ // Lib\Db because of this feature. After enabling it via
+ // App/config.php, create the first user at /admin/users (open access
+ // until at least one user exists) or with:
+ // php novaconium/bin/create-admin-user.php
+ 'admin_auth_enabled' => false,
// Lib\Db (see /admin/docs/database) — named, simultaneously-usable
// connections, keyed by name; 'default' is the only one required. A
diff --git a/novaconium/lib/Access.php b/novaconium/lib/Access.php
new file mode 100644
index 0000000..9ce3391
--- /dev/null
+++ b/novaconium/lib/Access.php
@@ -0,0 +1,105 @@
+' (the user's users.user_group matches), or
+ * 'user:' (that exact account); several rules mean "any of
+ * these". No rules at all means any logged-in user. Admins always pass
+ * every rule. Returns null when the request may proceed, or a Response
+ * for the sidecar to return: a 303 to /admin/login (with a ?return= path
+ * back here) when nobody is logged in, or a plain 404 when someone *is*
+ * logged in but isn't allowed — same hide-don't-tease posture as draft
+ * pages, and the same plain-text 404 /search returns when disabled.
+ *
+ * Public is the default, twice over: a sidecar that never calls this is
+ * untouched, and a page with no sidecar at all *can't* call it — static
+ * (cached) pages are always public. That's load-bearing, not incidental:
+ * only sidecar-less pages are ever written to the static HTML cache
+ * (which .htaccess serves before PHP runs — see /admin/docs/caching), so
+ * a gated page, necessarily having a sidecar, is never cached. This
+ * satisfies the caching/auth standing rule in AGENTS.md by construction
+ * rather than by a bootstrap.php exclusion like drafts/admin need.
+ *
+ * Same open-until-configured posture as the rest of admin auth: with
+ * admin_auth_enabled off, or while no users exist yet, require() allows
+ * everything (there'd be nothing to log in as) — and never touches
+ * Lib\Db, so a site that never opted in never gets a database file.
+ *
+ * The content-index crawl runs every sidecar as an anonymous GET, so a
+ * gated page's sidecar short-circuits to the login redirect during a
+ * crawl — Renderer::renderForIndex() discards Responses, meaning gated
+ * pages are automatically absent from /search and /sitemap.xml, with no
+ * extra wiring. require() has no side effects on deny (the return path
+ * travels in the redirect URL, not the session) for the same reason: a
+ * crawl must not scribble on the visitor's session.
+ */
+final class Access
+{
+ private static ?bool $enabled = null;
+
+ public static function require(string ...$rules): ?Response
+ {
+ if (!self::enabled() || !AdminAuth::hasUsers()) {
+ return null;
+ }
+
+ $user = AdminAuth::currentUser();
+
+ if ($user === null) {
+ $path = (string) (parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');
+
+ return Response::redirect('/admin/login?return=' . rawurlencode($path), 303);
+ }
+
+ if ($user['role'] === 'admin' || $rules === []) {
+ return null;
+ }
+
+ foreach ($rules as $rule) {
+ if (str_starts_with($rule, 'user:') && substr($rule, 5) === $user['username']) {
+ return null;
+ }
+
+ if (str_starts_with($rule, 'group:') && $user['user_group'] !== '' && substr($rule, 6) === $user['user_group']) {
+ return null;
+ }
+ }
+
+ return Response::html('404 Not Found', 404);
+ }
+
+ /**
+ * Same two-step config load bootstrap.php/bin scripts and the
+ * /search sidecar use — Lib\ classes aren't handed $config, so this
+ * loads its own copy to read admin_auth_enabled (memoized per
+ * request; static state never survives across requests).
+ */
+ private static function enabled(): bool
+ {
+ if (self::$enabled === null) {
+ $config = require __DIR__ . '/../config.php';
+
+ $appConfigFile = __DIR__ . '/../../App/config.php';
+ if (is_file($appConfigFile)) {
+ $config = array_merge($config, require $appConfigFile);
+ }
+
+ self::$enabled = (bool) $config['admin_auth_enabled'];
+ }
+
+ return self::$enabled;
+ }
+}
diff --git a/novaconium/lib/Csrf.php b/novaconium/lib/Csrf.php
index 6ccd876..b4035c0 100644
--- a/novaconium/lib/Csrf.php
+++ b/novaconium/lib/Csrf.php
@@ -15,11 +15,12 @@ namespace Lib;
*
*
*
- * This is the first thing in the framework that starts a native PHP session
+ * This was the first thing in the framework to start a native PHP session
* — but only lazily, the moment token()/verify() is actually called. A page
- * that never touches Csrf never gets a session cookie. This is unrelated to
- * Lib\AdminAuth, which stays fully stateless (HTTP Basic Auth, no sessions
- * for login state) — see novaconium/src/AdminAuth.php.
+ * that never touches Csrf never gets a session cookie. Lib\Session and
+ * App\AdminAuth (session-based admin login) now touch the same native
+ * session the same lazy way — safe in any order, since ensureSession()
+ * no-ops when a session is already active.
*/
final class Csrf
{
diff --git a/novaconium/lib/Db.php b/novaconium/lib/Db.php
index 3032489..26190a6 100644
--- a/novaconium/lib/Db.php
+++ b/novaconium/lib/Db.php
@@ -89,6 +89,9 @@ final class Db
*/
private static function connectSqlite(array $config): PDO
{
+ self::requireDriver('sqlite', 'pdo_sqlite',
+ 'bundled with PHP but sometimes not enabled — Debian/Ubuntu: `apt install php-sqlite3`; Arch: uncomment `extension=pdo_sqlite` in php.ini');
+
$path = $config['path'];
$dir = dirname($path);
if (!is_dir($dir)) {
@@ -109,6 +112,9 @@ final class Db
*/
private static function connectMysql(array $config): PDO
{
+ self::requireDriver('mysql', 'pdo_mysql',
+ 'Debian/Ubuntu: `apt install php-mysql`; Arch: uncomment `extension=pdo_mysql` in php.ini');
+
$charset = $config['charset'] ?? 'utf8mb4';
$dsn = "mysql:host={$config['host']};port={$config['port']};dbname={$config['database']};charset={$charset}";
@@ -118,6 +124,23 @@ final class Db
]);
}
+ /**
+ * A missing PDO driver otherwise surfaces as a bare PDOException
+ * ("could not find driver") from deep inside a connect call — hit for
+ * real the first time this ran on a PHP install without pdo_sqlite
+ * enabled. Checking PDO::getAvailableDrivers() up front turns that
+ * into an error that names the extension and how to install it.
+ */
+ private static function requireDriver(string $driver, string $extension, string $installHint): void
+ {
+ if (!in_array($driver, PDO::getAvailableDrivers(), true)) {
+ throw new RuntimeException(
+ "PHP is missing the {$extension} extension, which this connection's '{$driver}' driver needs ({$installHint}). " .
+ 'Verify with `php -m`, and restart PHP after enabling it. See /admin/docs/database.'
+ );
+ }
+ }
+
/**
* Applies any *.sql file under $migrationsDirs not yet recorded in this
* connection's own schema_migrations table. $migrationsDirs is an
diff --git a/novaconium/lib/Input.php b/novaconium/lib/Input.php
index af7f287..4b9db62 100644
--- a/novaconium/lib/Input.php
+++ b/novaconium/lib/Input.php
@@ -22,11 +22,13 @@ namespace Lib;
* dangerous.
*
* One documented exception: a field that needs an exact, unmodified value
- * (e.g. a password about to be hashed) should read $_POST directly instead —
- * cleaning would silently strip characters like < and > before hashing,
- * producing a hash that doesn't match what the user actually typed. See
- * novaconium/pages/admin/password-hash/index.php for the one place this
- * framework does that on purpose.
+ * (e.g. a password about to be hashed or verified) should read $_POST
+ * directly instead — cleaning would silently strip characters like < and >
+ * before hashing, producing a hash that doesn't match what the user
+ * actually typed (or failing a login whose password actually matches). See
+ * the password fields in novaconium/pages/admin/users/index.php and
+ * novaconium/pages/admin/login/index.php for the places this framework
+ * does that on purpose.
*/
final class Input
{
diff --git a/novaconium/lib/Session.php b/novaconium/lib/Session.php
index fafeee2..13523a6 100644
--- a/novaconium/lib/Session.php
+++ b/novaconium/lib/Session.php
@@ -61,6 +61,20 @@ final class Session
unset($_SESSION[$key]);
}
+ /**
+ * Swaps the session id for a fresh one, keeping the session's data.
+ * Call on any privilege change — after a successful login, and on
+ * logout — so a session id an attacker planted or observed before the
+ * change is worthless after it (session fixation). App\AdminAuth does
+ * exactly this.
+ */
+ public static function regenerate(): void
+ {
+ self::ensureSession();
+
+ session_regenerate_id(true);
+ }
+
/**
* Stores $value so it's readable via getFlash($key) on the next
* request only, then gone — regardless of whether getFlash() was
diff --git a/novaconium/migrations/0002_create_users.sql b/novaconium/migrations/0002_create_users.sql
new file mode 100644
index 0000000..e24be32
--- /dev/null
+++ b/novaconium/migrations/0002_create_users.sql
@@ -0,0 +1,10 @@
+CREATE TABLE IF NOT EXISTS users (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ username TEXT NOT NULL UNIQUE,
+ email TEXT NOT NULL UNIQUE,
+ password_hash TEXT NOT NULL,
+ role TEXT NOT NULL DEFAULT 'registered',
+ user_group TEXT NOT NULL DEFAULT '',
+ is_disabled INTEGER NOT NULL DEFAULT 0,
+ created_at TEXT NOT NULL
+);
diff --git a/novaconium/pages/_layout/icons.twig b/novaconium/pages/_layout/icons.twig
index 8761aa7..833807d 100644
--- a/novaconium/pages/_layout/icons.twig
+++ b/novaconium/pages/_layout/icons.twig
@@ -92,6 +92,15 @@
{% endmacro %}
+{% macro users(class) %}
+
+{% endmacro %}
+
{% macro trash(class) %}
-
Copy-paste starter: a sidecar, three ways
+
Copy-paste starter: a sidecar, four ways
Drop this in as App/pages/example/index.php (next to an App/pages/example/index.twig using the SEO starter template) and delete whichever example you don't need:
Only one of the three returns in a real sidecar ever runs, obviously — pick one, or branch between them with an if. The IP example works with or without a sidecar-only page (no index.twig); the phpinfo() example needs noindex.twig at all, since Response::html() bypasses Twig — see the JSON-only example above for another sidecar-only page.
+// 4. Require a login — gate the page to a group, a user, or any
+// logged-in account before doing anything else. Access::require()
+// returns null when the visitor may proceed, or a ready-made Response
+// (a login redirect that comes back here afterwards, or a 404 for the
+// wrong account) for you to return as-is. Needs admin_auth_enabled and
+// at least one user — see /admin/docs/access-control for the rules and
+// /admin/docs/admin-auth for accounts and groups.
+// use Lib\Access;
+//
+// if ($denied = Access::require('group:members')) {
+// return $denied;
+// }
+//
+// return [
+// 'message' => 'Hello, member!',
+// ];{% endverbatim %}
+
+
Only one of the numbered returns in a real sidecar ever runs, obviously — pick one, or branch between them with an if. The IP example works with or without a sidecar-only page (no index.twig); the phpinfo() example needs noindex.twig at all, since Response::html() bypasses Twig — see the JSON-only example above for another sidecar-only page. The login gate in example 4 isn't really an alternative to the other three — it's a first line that composes with any of them: gate first, then return whatever the page normally would. Swap the rule for Access::require('user:bob'), several rules (any one grants access), or no rules at all for "anyone logged in"; admins always pass.
Never ship phpinfo() to production — it dumps environment variables, file paths, loaded extensions, and configuration values that are useful to an attacker mapping your server. Delete the page after you're done with it, or at minimum gate it behind admin authentication the same way /admin/* already is, so it's never reachable by the public.
Ends your admin session on the server — you'll need to log in again at /admin/login to get back in.
+ {% if securityError %}
+
Your session expired before submitting — please try again.
+ {% endif %}
+
+
+{% endblock %}
diff --git a/novaconium/pages/admin/password-hash/index.php b/novaconium/pages/admin/password-hash/index.php
deleted file mode 100644
index eba1337..0000000
--- a/novaconium/pages/admin/password-hash/index.php
+++ /dev/null
@@ -1,38 +0,0 @@
- before hashing, producing a hash that
- // doesn't match what's actually typed later at the Basic Auth prompt
- // (which does zero sanitization).
- $password = $_POST['password'] ?? '';
-
- if ($password === '') {
- $error = 'Enter a password to hash.';
- } elseif (strlen($password) < 8) {
- $error = 'Use at least 8 characters.';
- } else {
- // Computed once per request and never stored/logged — the page
- // that renders this is the only place it's ever seen.
- $hash = password_hash($password, PASSWORD_DEFAULT);
- }
-}
-
-return [
- 'hash' => $hash,
- 'error' => $error,
- 'securityError' => Input::get('error') === 'security',
- 'csrfField' => Csrf::fieldName(),
- 'csrfToken' => Csrf::token(),
-];
diff --git a/novaconium/pages/admin/password-hash/index.twig b/novaconium/pages/admin/password-hash/index.twig
deleted file mode 100644
index 1fdb801..0000000
--- a/novaconium/pages/admin/password-hash/index.twig
+++ /dev/null
@@ -1,42 +0,0 @@
-{% extends layout %}
-
-{% import '_layout/icons.twig' as icons %}
-
-{% block title %}Generate admin password hash{% endblock %}
-{% block description %}Generate a password_hash() value for admin_password_hash without using the CLI.{% endblock %}
-{% block robots %}noindex, nofollow{% endblock %}
-
-{% block content %}
-
-
{{ icons.lock() }}Generate admin password hash
-
-
A browser-based alternative to php -r "echo password_hash('yourpassword', PASSWORD_DEFAULT);". Enter a password, get back the hash App/config.php expects for admin_password_hash — see {{ icons.book() }}Admin authentication. Nothing typed here is stored, logged, or sent anywhere except computed once for this response.
-
-
-
- {% if securityError %}
-
Your session expired before submitting — please try again.
- {% endif %}
-
-{% endblock %}
diff --git a/novaconium/pages/admin/users/index.php b/novaconium/pages/admin/users/index.php
new file mode 100644
index 0000000..d77e21a
--- /dev/null
+++ b/novaconium/pages/admin/users/index.php
@@ -0,0 +1,201 @@
+ (int) Db::query(
+ "SELECT COUNT(*) FROM users WHERE is_disabled = 0 AND role = 'admin'"
+)->fetchColumn();
+
+if ($_SERVER['REQUEST_METHOD'] === 'POST') {
+ if (!Csrf::verify(Input::post('csrf_token'))) {
+ Session::flash('users_error', 'Your session expired before submitting — please try again.');
+
+ return Response::redirect('/admin/users', 303);
+ }
+
+ $action = Input::post('action', '');
+
+ if ($action === 'create') {
+ $username = trim((string) Input::post('username', ''));
+ // Validate::isEmail() returns the normalized (trimmed, lowercased)
+ // address, or false — stored normalized so the future
+ // email-verification flow (see novaconium/ISSUES.md) can match
+ // addresses case-insensitively for free.
+ $email = Validate::isEmail((string) Input::post('email', ''));
+ $group = trim((string) Input::post('group', ''));
+ // Passwords read directly, not via Input::post() — cleaning would
+ // silently strip characters like < and > before hashing, producing
+ // a hash that doesn't match what's actually typed at /admin/login
+ // later. See /admin/docs/sidecars' "Form security" section.
+ $password = (string) ($_POST['password'] ?? '');
+
+ $exists = $username !== ''
+ && (bool) Db::query('SELECT EXISTS(SELECT 1 FROM users WHERE username = ?)', [$username])->fetchColumn();
+ $emailExists = $email !== false
+ && (bool) Db::query('SELECT EXISTS(SELECT 1 FROM users WHERE email = ?)', [$email])->fetchColumn();
+
+ if ($username === '' || strlen($username) > 64) {
+ Session::flash('users_error', 'Enter a username (64 characters max).');
+ } elseif ($email === false) {
+ Session::flash('users_error', 'Enter a valid email address.');
+ } elseif ($emailExists) {
+ Session::flash('users_error', 'That email address is already in use.');
+ } elseif (strlen($group) > 64) {
+ Session::flash('users_error', 'Group names are 64 characters max.');
+ } elseif ($exists) {
+ Session::flash('users_error', 'That username is already taken.');
+ } elseif (strlen($password) < 8) {
+ Session::flash('users_error', 'Use a password of at least 8 characters.');
+ } else {
+ // The first user ever created is the admin; everyone after is
+ // a registered user (optionally in a group) — Lib\Access rules
+ // decide what content they can see, and /admin/* 404s for
+ // them. See /admin/docs/admin-auth and
+ // /admin/docs/access-control.
+ $wasFirstUser = !AdminAuth::hasUsers();
+ $role = $wasFirstUser ? 'admin' : 'registered';
+
+ Db::query(
+ 'INSERT INTO users (username, email, password_hash, role, user_group, is_disabled, created_at) VALUES (?, ?, ?, ?, ?, 0, ?)',
+ [$username, $email, password_hash($password, PASSWORD_DEFAULT), $role, $group, gmdate('Y-m-d\TH:i:s\Z')]
+ );
+
+ // Creating the first user is what closes the open setup gate —
+ // log its creator in as it, or their very next request would
+ // bounce them to the login form they were just typing into.
+ if ($wasFirstUser) {
+ AdminAuth::attempt($username, $password);
+ }
+
+ Session::flash('users_notice', "User \u{201C}{$username}\u{201D} created.");
+ }
+ } elseif ($action === 'disable' || $action === 'enable') {
+ $id = (int) Input::post('id', '0');
+ $target = Db::query('SELECT id, username, role, is_disabled FROM users WHERE id = ?', [$id])->fetch(PDO::FETCH_ASSOC);
+
+ if ($target === false) {
+ Session::flash('users_error', 'No such user.');
+ } elseif ($action === 'disable' && (int) $target['is_disabled'] === 0 && $target['role'] === 'admin' && $activeAdminCount() <= 1) {
+ Session::flash('users_error', 'Cannot disable the last active admin — that would lock everyone out of /admin.');
+ } else {
+ Db::query('UPDATE users SET is_disabled = ? WHERE id = ?', [$action === 'disable' ? 1 : 0, $id]);
+ Session::flash('users_notice', sprintf("User \u{201C}%s\u{201D} %sd.", $target['username'], $action));
+ }
+ } elseif ($action === 'role') {
+ $id = (int) Input::post('id', '0');
+ $role = Input::post('role', '');
+ $target = Db::query('SELECT id, username, role, is_disabled FROM users WHERE id = ?', [$id])->fetch(PDO::FETCH_ASSOC);
+
+ if ($target === false) {
+ Session::flash('users_error', 'No such user.');
+ } elseif (!in_array($role, ['admin', 'registered'], true)) {
+ Session::flash('users_error', 'No such role.');
+ } elseif ($role === 'registered' && $target['role'] === 'admin' && (int) $target['is_disabled'] === 0 && $activeAdminCount() <= 1) {
+ Session::flash('users_error', 'Cannot demote the last active admin — that would lock everyone out of /admin.');
+ } else {
+ Db::query('UPDATE users SET role = ? WHERE id = ?', [$role, $id]);
+ Session::flash('users_notice', "User \u{201C}{$target['username']}\u{201D} is now {$role}.");
+ }
+ } elseif ($action === 'delete') {
+ $id = (int) Input::post('id', '0');
+ $target = Db::query('SELECT id, username, role, is_disabled FROM users WHERE id = ?', [$id])->fetch(PDO::FETCH_ASSOC);
+
+ if ($target === false) {
+ Session::flash('users_error', 'No such user.');
+ } elseif ((int) $target['is_disabled'] === 0 && $target['role'] === 'admin' && $activeAdminCount() <= 1) {
+ Session::flash('users_error', 'Cannot delete the last active admin — that would lock everyone out of /admin.');
+ } else {
+ // A hard delete, not a soft one — is_disabled already covers
+ // "keep the account but shut it out", so delete is for
+ // accounts that shouldn't exist at all. Any live session dies
+ // on its next request (currentUser() re-checks the row).
+ Db::query('DELETE FROM users WHERE id = ?', [$id]);
+ Session::flash('users_notice', "User \u{201C}{$target['username']}\u{201D} deleted.");
+ }
+ } elseif ($action === 'email') {
+ $id = (int) Input::post('id', '0');
+ $email = Validate::isEmail((string) Input::post('email', ''));
+ $target = Db::query('SELECT id, username FROM users WHERE id = ?', [$id])->fetch(PDO::FETCH_ASSOC);
+ $emailExists = $email !== false
+ && (bool) Db::query('SELECT EXISTS(SELECT 1 FROM users WHERE email = ? AND id != ?)', [$email, $id])->fetchColumn();
+
+ if ($target === false) {
+ Session::flash('users_error', 'No such user.');
+ } elseif ($email === false) {
+ Session::flash('users_error', 'Enter a valid email address.');
+ } elseif ($emailExists) {
+ Session::flash('users_error', 'That email address is already in use.');
+ } else {
+ Db::query('UPDATE users SET email = ? WHERE id = ?', [$email, $id]);
+ Session::flash('users_notice', "Email changed for \u{201C}{$target['username']}\u{201D}.");
+ }
+ } elseif ($action === 'group') {
+ $id = (int) Input::post('id', '0');
+ $group = trim((string) Input::post('group', ''));
+ $target = Db::query('SELECT id, username FROM users WHERE id = ?', [$id])->fetch(PDO::FETCH_ASSOC);
+
+ if ($target === false) {
+ Session::flash('users_error', 'No such user.');
+ } elseif (strlen($group) > 64) {
+ Session::flash('users_error', 'Group names are 64 characters max.');
+ } else {
+ Db::query('UPDATE users SET user_group = ? WHERE id = ?', [$group, $id]);
+ Session::flash('users_notice', $group === ''
+ ? "User \u{201C}{$target['username']}\u{201D} removed from their group."
+ : "User \u{201C}{$target['username']}\u{201D} assigned to group \u{201C}{$group}\u{201D}.");
+ }
+ } elseif ($action === 'password') {
+ $id = (int) Input::post('id', '0');
+ $password = (string) ($_POST['password'] ?? '');
+ $target = Db::query('SELECT id, username FROM users WHERE id = ?', [$id])->fetch(PDO::FETCH_ASSOC);
+
+ if ($target === false) {
+ Session::flash('users_error', 'No such user.');
+ } elseif (strlen($password) < 8) {
+ Session::flash('users_error', 'Use a password of at least 8 characters.');
+ } else {
+ Db::query('UPDATE users SET password_hash = ? WHERE id = ?', [password_hash($password, PASSWORD_DEFAULT), $id]);
+ Session::flash('users_notice', "Password changed for \u{201C}{$target['username']}\u{201D}.");
+ }
+ }
+
+ return Response::redirect('/admin/users', 303);
+}
+
+return [
+ 'users' => Db::query('SELECT id, username, email, role, user_group, is_disabled, created_at FROM users ORDER BY username')->fetchAll(PDO::FETCH_ASSOC),
+ 'currentUserId' => AdminAuth::currentUser()['id'] ?? null,
+ 'notice' => Session::getFlash('users_notice'),
+ 'error' => Session::getFlash('users_error'),
+ 'csrfField' => Csrf::fieldName(),
+ 'csrfToken' => Csrf::token(),
+];
diff --git a/novaconium/pages/admin/users/index.twig b/novaconium/pages/admin/users/index.twig
new file mode 100644
index 0000000..0597e3b
--- /dev/null
+++ b/novaconium/pages/admin/users/index.twig
@@ -0,0 +1,145 @@
+{% extends layout %}
+
+{% import '_layout/icons.twig' as icons %}
+
+{% block title %}Users{% endblock %}
+
+{% block description %}Create, disable, and manage user accounts, roles, and groups.{% endblock %}
+
+{% block robots %}noindex, nofollow{% endblock %}
+
+{% block content %}
+
+
{{ icons.users() }}Users
+
+
Accounts that can log in at /admin/login. The first user created is the admin; everyone after is registered — able to log in and see whatever pages Lib\Access assigns to their account or group (see {{ icons.lock() }}Access control), but not the admin area. A disabled user can't log in, and any session they already had is locked out on its next request.
+
+ {% if notice %}
+
{{ notice }}
+ {% endif %}
+
+ {% if error %}
+
{{ error }}
+ {% endif %}
+
+ {% if users is empty %}
+
No users exist yet, so the admin area is open to anyone who can reach it. Create the first user below to close the gate — it becomes the admin account, and you'll be logged in as it automatically.
+
+
+
+{% endblock %}
diff --git a/novaconium/src/AdminAuth.php b/novaconium/src/AdminAuth.php
index 54ebf8d..0194149 100644
--- a/novaconium/src/AdminAuth.php
+++ b/novaconium/src/AdminAuth.php
@@ -2,76 +2,195 @@
namespace App;
+use Lib\Db;
+use Lib\Session;
+use PDO;
+
/**
- * Reusable HTTP Basic Auth gate for /admin/*. A single check, called once
- * from bootstrap.php for any route under admin/, so protecting a new admin
- * page (clear-cache today, anything future) needs no per-page wiring.
+ * Session-based login backed by the `users` table
+ * (novaconium/migrations/0002_create_users.sql) on Lib\Db's default
+ * connection. This replaced the single-user HTTP Basic Auth stopgap that
+ * originally shipped under this same class name — same call sites
+ * (bootstrap.php's admin gate and draft gate), new mechanism, per the
+ * "replace it, don't layer on top of it" plan in novaconium/ISSUES.md.
*
- * Deliberately not a full user system — no sessions, no user table, no
- * password reset. It's a stopgap until proper multi-user admin login
- * (see novaconium/ISSUES.md) lands; that feature will replace this, not extend it.
+ * Two roles: 'admin' (full /admin/* access, sees drafts, passes every
+ * Lib\Access rule) and 'registered' (can log in, and sees whatever
+ * content Lib\Access grants their account or their group — see
+ * /admin/docs/access-control — but /admin/* 404s for them). The first
+ * user ever created is the admin; users created after that are
+ * registered, each optionally assigned one group (users.user_group, a
+ * plain text label — no groups table).
*
- * Note: Lib\Csrf (unrelated to login state here) does start a native PHP
- * session when a form calls it — so "no sessions" above is specifically
- * about this class's own login check, not a framework-wide guarantee.
+ * Gated by config['admin_auth_enabled'] (default false — same off-by-
+ * default posture as the content index, and for the same reason: this
+ * depends on SQLite, a real dependency plenty of sites won't want).
+ * Every method that touches Lib\Db is only reachable when the flag is
+ * true, so a site that never enables it never gets a data/ database file
+ * created just because this class exists.
+ *
+ * Bootstrap posture while enabled but with zero users yet: open access,
+ * so the first user can be created at /admin/users (or with
+ * `php novaconium/bin/create-admin-user.php`) — the same window the old
+ * Basic Auth had between deciding to enable it and pasting a hash into
+ * App/config.php. Enabling the flag alone protects nothing; creating the
+ * first user is what closes the gate.
*/
final class AdminAuth
{
+ private const SESSION_KEY = '_admin_user_id';
+
/**
- * Exits with a 401 challenge if the request isn't authenticated.
- * A no-op (auth disabled) when $passwordHash is empty.
+ * Per-request memo for currentUser() — static state never survives
+ * across requests (same guarantee Lib\Session's flash swap relies on),
+ * so this only saves repeat lookups within one request.
+ *
+ * @var array|null
*/
- public static function requireLogin(string $username, string $passwordHash): void
+ private static ?array $currentUser = null;
+
+ private static bool $currentUserLoaded = false;
+
+ /**
+ * Redirects to /admin/login and exits if nobody is logged in. A no-op
+ * (open access) when $enabled is false, or while no users exist yet
+ * (see the class docblock). bootstrap.php calls this for every
+ * /admin/* route except admin/login itself — which must stay
+ * reachable logged-out, or the redirect would loop — and then
+ * separately 404s admin routes for logged-in non-admins (a registered
+ * user is *authenticated*, so bouncing them back to the login form
+ * would be a lie; what they lack is the admin role).
+ */
+ public static function requireLogin(bool $enabled): void
{
- if (self::isAuthenticated($username, $passwordHash)) {
+ if (self::isLoggedIn($enabled)) {
return;
}
- header('WWW-Authenticate: Basic realm="Admin"');
- http_response_code(401);
- header('Content-Type: text/plain; charset=utf-8');
- echo "401 Unauthorized\n";
+ http_response_code(303);
+ header('Location: /admin/login');
exit;
}
/**
- * The credential check on its own, with no response side effects —
- * reused by requireLogin() above (401 challenge on failure) and by
- * novaconium/bootstrap.php's draft-page gate (see /admin/docs/drafts),
- * which needs a *different* response on failure: a plain 404, not a
- * login prompt, so an unauthenticated visitor can't tell a draft
- * exists at all. Returns true (open access) when $passwordHash is
- * empty, matching requireLogin()'s existing no-op-when-unset posture —
- * a draft behaves like the rest of /admin/*: wide open until a
- * password is configured, gated once one is.
+ * Whether the request has any logged-in user at all, admin or
+ * registered. Returns true (open access) when $enabled is false or no
+ * users exist yet.
*/
- public static function isAuthenticated(string $username, string $passwordHash): bool
+ public static function isLoggedIn(bool $enabled): bool
{
- if ($passwordHash === '') {
+ if (!$enabled || !self::hasUsers()) {
return true;
}
- $providedUser = $_SERVER['PHP_AUTH_USER'] ?? null;
- $providedPass = $_SERVER['PHP_AUTH_PW'] ?? null;
-
- return $providedUser === $username
- && $providedPass !== null
- && password_verify($providedPass, $passwordHash);
+ return self::currentUser() !== null;
}
/**
- * HTTP Basic Auth has no real server-side "log out" — the browser just
- * keeps resending the cached credentials. The standard workaround: always
- * issue a fresh 401 challenge here regardless of what was sent, which
- * makes the browser discard the credentials it had cached for this realm
- * and prompt again next time /admin is visited.
+ * Whether the request is by a logged-in admin, with no response side
+ * effects — the check behind /admin/* and the draft-page gate in
+ * novaconium/bootstrap.php (see /admin/docs/drafts), which reacts to
+ * failure with a plain 404, not a login redirect, so an
+ * unauthenticated visitor can't tell a draft exists at all. Returns
+ * true (open access) when $enabled is false or no users exist yet, so
+ * a draft behaves consistently with the rest of /admin/*: wide open
+ * until the feature is enabled and a first user exists, gated after
+ * that.
+ */
+ public static function isAdmin(bool $enabled): bool
+ {
+ if (!$enabled || !self::hasUsers()) {
+ return true;
+ }
+
+ $user = self::currentUser();
+
+ return $user !== null && $user['role'] === 'admin';
+ }
+
+ /**
+ * Verifies a username/password against the users table and, on
+ * success, logs the session in. Disabled users fail exactly like a
+ * wrong password — the response never distinguishes "no such user",
+ * "disabled", and "bad password".
+ */
+ public static function attempt(string $username, string $password): bool
+ {
+ if ($username === '' || $password === '') {
+ return false;
+ }
+
+ $user = Db::query(
+ 'SELECT id, username, email, password_hash, role, user_group, is_disabled FROM users WHERE username = ?',
+ [$username]
+ )->fetch(PDO::FETCH_ASSOC);
+
+ if ($user === false || (int) $user['is_disabled'] === 1 || !password_verify($password, $user['password_hash'])) {
+ return false;
+ }
+
+ // Fresh session id on login so a pre-login session id (which an
+ // attacker could have planted or observed) never becomes an
+ // authenticated one — see Session::regenerate().
+ Session::regenerate();
+ Session::set(self::SESSION_KEY, (int) $user['id']);
+
+ unset($user['password_hash']);
+ self::$currentUser = $user;
+ self::$currentUserLoaded = true;
+
+ return true;
+ }
+
+ /**
+ * A real server-side logout (unlike the Basic Auth predecessor's
+ * 401-challenge trick): drop the logged-in user id from the session
+ * and regenerate the session id.
*/
public static function logout(): void
{
- header('WWW-Authenticate: Basic realm="Admin"');
- http_response_code(401);
- header('Content-Type: text/html; charset=utf-8');
- echo '