Sessions & Permissions
Who is making the request, what account they are, and what they may do — four core classes and one permission table.
The Classes
| Class | What it is | Tables |
|---|---|---|
Zero\Core\Session |
Who is making this request | none ($_SESSION) |
Zero\Core\Access\User |
An account | users, user_profile, user_settings |
Zero\Core\Access\Group |
A group of users | user_group, user_group_member |
Zero\Core\Access\Permission |
Who may do what | permission |
User and Group are both Zero\Core\Model row objects, and both implement Zero\Core\Access\Holder: something a permission can be granted to.
Every class on this page except the session accessors reads the tables created by core/sql/core.sql. Load it once into an empty database — mysql <database> < core/sql/core.sql — before using any of it; core/sql/README.md lists what it creates. A site with no database, like this one, can use none of the gates that read a user.
Users, groups and permissions belong to core. A module does not keep a group or permission table of its own and does not query core's; it goes through User, Group and Permission. Group is the only class that reads or writes user_group and user_group_member.
Session
core/Session.php. Every method is static and answers for the current request only.
| Method | Returns |
|---|---|
Session::isLoggedIn(): bool |
True when the session holds an email and a truthy verified flag — signed in and verified |
Session::userId(): ?int |
The current user's id from $_SESSION['user_id'], or null. Anything that is not a positive integer is null |
Session::user(): ?User |
The current user as a User, built from $_SESSION without a query and memoized for the request |
Session::can(string $key): bool |
Does the logged-in user hold the capability? False when nobody is logged in |
Session::establish(User $user, ?array $identity = null): void |
Builds the login session. The single writer: it rotates the session id and sets user_id, name, email, verified, pic and created_at |
Session::end(): void |
Tears the session down: clears $_SESSION, expires the cookie, destroys the session |
Session::endIfDisabled(): void |
Ends the session if its account is disabled. Application::run() calls it on every request |
use Zero\Core\Session;
// A public endpoint that behaves differently for a signed-in visitor
public function index() {
$name = Session::isLoggedIn() ? Session::user()->name : null;
$this->respond($this->viewPath . 'index.php');
}
isLoggedIn() is for a branch like that one. If the branch would end in a redirect, an error or an early return, it is a gate and belongs in #[RequireLogin], which uses the same predicate.
Session::user() can be changed and save()d. Never delete() it: the row goes and the session stays.
Users
core/access/User.php. A User answers for the row it was loaded from and never reads the session. Its columns are name, email, verified, disabled and pic.
use Zero\Core\Access\User;
$user = User::find($userId); // ?User
$user = User::findByEmail($email); // ?User; the address is normalized first
$user->can('allow.polly'); // capability check
$user->capabilities(); // every capability key the user has
$user->groups(); // the active groups the user belongs to
$user->settings(); // user_settings, keyed by setting_key
$user->setSetting('theme', 'dark');
$user->removeSetting('theme');
A setting is a value, not a permission. Settings live in user_settings; capabilities do not.
Disabled users
An account is closed by disabling it, not by deleting it. $user->disable() sets users.disabled and $user->enable() clears it; the account's data stays.
Session::endIfDisabled()runs inApplication::run()before the module is built, so an open session ends at the account's next request.#[AllowWithToken]refuses a token whose owner is disabled with a 401.- Read
$user->isDisabled()on a user loaded from the database.Session::user()is built from the session and does not carry the flag. - If the database cannot be read,
endIfDisabled()logs the failure and leaves the session in place.
$user->delete() exists — it removes the user's group memberships, grants, settings and profile along with the row — but no page calls it. It is for tests and manual clean-up.
Groups
core/access/Group.php. A group has members, each with a role, and can be active or inactive. An inactive group grants nothing.
use Zero\Core\Access\Group; $group = Group::create(['group_name' => 'Campaign 12']); // created_by: the logged-in user $group = Group::find($groupId); // ?Group $group->add($userId, 'owner'); // role defaults to 'member' $group->setRole($userId, 'admin'); $group->remove($userId); $group->has($userId); // a member, and the group is active $group->usableBy($userId); // may share with it: has(), or holds allow.admin $group->role($userId); // ?string $group->members(); $group->memberCount(); Group::forUser($userId); // the user's active groups Group::idsForUser($userId); Group::all(); // every group; Group::all(true) for active only $group->deactivate(); // stops granting; rows stay $group->activate(); $group->delete(); // gone, with its members and every grant made to it
Wherever a user is expected, an int id or a User works. find(), all() and members() include inactive groups so a management screen can show them; forUser(), idsForUser() and has() leave them out.
Two Kinds of Permission
Both are rows in the permission table. They answer different questions and are checked in different places.
| Capabilities | Sharing | |
|---|---|---|
| Question | May this user use this feature at all? | May this user read, update or delete this item? |
| Key | allow.* — allow.polly, allow.receipt.view |
{module}.{entity} — lists.list, kanban.board |
| Held on | Entity 0 |
An item id (or 0 for every item under the key) |
| Checked by | #[RequirePermission], Session::can(), $user->can() |
Permission::can() / sqlCan(), in the endpoint body |
| Granted with | $holder->grant($key) |
$perm->grant($id, $holder, ...) |
Rows only grant. There is no deny row: revoking deletes the row. In both systems a user holds what was granted to them directly plus what was granted to every active group they belong to.
Capabilities
User and Group share the capability methods through the HoldsCapabilities trait (core/access/HoldsCapabilities.php).
$user->can('allow.polly'); // does this user have it?
Session::can('allow.polly'); // does the logged-in user?
$user->capabilities(); // every key the user has
$user->grant('allow.polly', $adminId); // $adminId is recorded as the granter
$user->revoke('allow.polly');
$group->grant('allow.polly'); // every active member has it
$group->revoke('allow.polly');
$group->can('allow.polly'); // was it granted to the group itself?
- A key is
allow.and then lowercase words joined by dots, at most 100 characters.Permission::capabilityKey()validates it. can()reads the database once per object and caches nothing in the session, so a grant or revocation takes effect on the user's next request. A failed lookup denies.grant()andrevoke()returnfalsewhen the write fails or is refused; they log the reason and do not throw.revoke()removes the holder's own row. A capability a user has through a group stays until the group loses it.
To gate an endpoint on a capability, declare #[RequirePermission('allow.polly')] — see PHP Attributes. Use Session::can() in a body or a view only to vary what is shown, not to refuse the request.
Sharing
A module that lets users share its items creates a Permission for its key and asks it. Permission never reads the module's tables, so ownership stays the module's business: the owner of an item needs no row, and the module checks “is the owner, or can()”.
use Zero\Core\Access\Group;
use Zero\Core\Access\Permission;
use Zero\Core\Exception\HTTPError;
$perm = new Permission('lists', 'list'); // key: lists.list
// One item
if ($list['user_id'] != $userId && !$perm->can($listId, $userId, 'update')) {
throw new HTTPError(403);
}
// A listing: every list the user owns or can read
[$canRead, $params] = $perm->sqlCan('l.list_id', $userId, 'read');
$stmt = $db->prepare("SELECT l.* FROM lists l WHERE l.user_id = ? OR $canRead");
$stmt->execute([$userId, ...$params]);
// Sharing with a group chosen in a form
$group = Group::find($groupId) ?? throw new HTTPError(404, 'Group not found');
if (!$group->usableBy($userId)) {
throw new HTTPError(403, 'You can only share with a group you belong to');
}
$perm->grant($listId, $group, true, true, false); // read + update
$perm->grant($listId, $otherUser); // one user: read
$perm->revoke($listId, $group);
// Deleting the item
$perm->forget($listId);
| Method | Answers |
|---|---|
can($id, $user, $action = 'read') |
Does the user hold read / update / delete on the item? |
sqlCan($idColumn, $user, $action = 'read') |
[sql, params]: an EXISTS (...) condition for the module's own query |
ids($user, $action = 'read') |
Ids of the items granted one by one |
canAll($user, $action = 'read') |
Does the user hold it on every item (a row on entity 0)? |
grant($id, $holder, $canRead = true, $canUpdate = false, $canDelete = false, $by = null) |
Insert or replace a holder's rights. All three flags false removes the row |
batchGrant($id, [groupId => flags], $by = null) |
The same for several groups from a form |
revoke($id, $holder) |
Remove a holder's row |
forget($id) |
Remove every grant on an item |
groups($id), users($id) |
The active groups granted; everyone with rights |
availableGroups($id, $user) |
The user's active groups with no grant on the item yet |
- The module name in the key is the module's name as it appears in its URL: lowercase, words joined by hyphens.
Permission::key()validates it and refusesallow, so a sharing key can never be mistaken for a capability. - A user shares only with a group they belong to.
grant()to a group throws\DomainExceptionunless the granter is a member of the active group or holdsallow.admin.$group->usableBy($user)is that test; check it first. sqlCan()uses positional?placeholders, so the query it goes into must too.$idColumnmust be a plain column name, never user input.can()returnsfalseon a database error and logs it. An unknown action throws\InvalidArgumentException.- Nothing cascades in the database. A module deleting an item calls
forget().
Auth Levels
$user->authLevel() still exists: it returns the auth.level setting from user_settings as an integer, 0 when unset. It is a setting, not a capability, and #[RequireAuthLevel], the attribute that reads it, is shelved. Use a capability for new work; PHP Attributes has the reasons.
API Tokens
An API client authenticates with Authorization: Bearer zk_... on an endpoint that declares #[AllowWithToken]. The attribute looks up the token's SHA-256 hash in api_tokens, checks its expiry and its owner, and calls Session::establish() for the owner — so #[RequireLogin], #[RequirePermission] and everything on this page then behave exactly as they do for a browser. A token carries its owner's permissions; it has none of its own.
The bundled User module issues and revokes tokens (core/modules/User/User.php: tokens(), createToken(), deleteToken()). Only the hash is stored, so the token itself is returned once, at creation. See Bundled Modules.
Because establish() writes an ordinary login session, the response to a token request carries a session cookie that is a full login for the token's owner, and that session outlives the token being revoked. core/docs/TOKEN_ISSUE.md describes the problem and a proposed fix that is not implemented. A client that discards response cookies is not affected.