Sessions

Session is DB-backed — every session is a row in the sessions table, created by php mitosis setup. It's a pure data layer: Session never touches superglobals, cookies, or the HTTP layer directly. Delivering the session token as a cookie on the outgoing response is the caller's job — Clarity's Authentication and Csrf middlewares do this under the cookie name Session::COOKIE_NAME (mid).

Why user_id is nullable

A session can exist with no associated user — guest browsing, or a pre-login CSRF token that needs somewhere to live before an account exists at all. This isn't an edge case bolted on afterward; it's why the column is nullable in DDL.sql from the start.

The lifecycle

use Monad\Clarity\Services\Session;

// Start a guest session (no user yet).
$session = Session::start(userId: null, ipAddress: $request->ip(), userAgent: $request->userAgent() ?? '');
// ['id' => ..., 'token' => ..., 'expireAt' => ...] — deliver $session['token'] as the `mid` cookie.

// Resolve a token back to its session row (an expired, revoked, or nonexistent token
// all resolve to null alike — the caller can't distinguish why, by design).
$row = Session::resolve($token);

// Store and read arbitrary payload data.
Session::write($session['id'], 'cart', ['sku-1']);
$cart = Session::read($session['id'], 'cart');

Login: regenerate and assign

On successful login, rotate the session's token (defeats session fixation) and promote it from guest to authenticated — without losing whatever payload the guest session already collected:

Session::assignUser($session['id'], $userId);
$newToken = Session::regenerate($session['id']);
// Re-issue $newToken as the `mid` cookie. The old token no longer resolves — its digest
// changed — even though the row itself is untouched.

Ending a session

Session::revoke($id) marks a session invalid without deleting the row — an audit trail survives. Session::destroy($id) hard-deletes it. Session::purgeExpired() removes every expired or revoked row at once, for a scheduled maintenance task rather than the request path.

Next steps

  • Middleware Pipeline — where Authentication and Csrf apply the session cookie.
  • Caching — another DB-backed built-in table, with a different data-integrity rule.