Skip to content
Syone edited this page Nov 20, 2026 · 1 revision

Overview

The user subsystem covers four related concerns:

Concern Stored in Main API
Account profile t_user Service\User (retrieve, update, account components)
Roles t_user_role, t_user.role Model\User::hasRole()
Permissions t_user_permission, t_user_role_has_permission, t_user_has_permission Model\User::hasPermission(), hasPermissionAmong()
Settings t_user_setting Model\User::getSetting(), setSetting()

It is implemented as three layers:

Component / Application       forms, pages, API endpoints
        │
        ▼
Service\User                  business logic, session, account lifecycle
  ├── extends Service\Crud    generic CRUD delegation
  └── builds Model\User       current user wrapper
        │
        ▼
Db\User                       SQL queries, permissions, settings
  ├── extends Db\Crud         t_user CRUD
  └── internal Crud           t_user_setting CRUD
        │
        ▼
MySQL                         project/protected/sql

Source files:

File Responsibility
bootstrap/src/Db/User.php Permission resolution SQL, settings read/write
bootstrap/src/Service/User.php Sign in/up/out, activation, password reset, session, CSRF
bootstrap/src/Model/User.php Current user wrapper and access checks
bootstrap/src/Db/Container.php Resolves the user database service
bootstrap/src/Service/Container.php Resolves the user business service
bootstrap/src/Component/User/ Sign in, sign up, password forms, connect panel
bootstrap/src/Application/User.php signout, activate, report actions
bootstrap/src/Application/Page.php user-connection and user-password pages
project/protected/src/Application/Page.php user-account page
project/protected/src/Component/User/ Account settings, password change, account deletion

Data model

t_user_role ─────┐
   │ id          │ role (FK, SET NULL)
   │             ▼
   │          t_user ──────────────< t_user_setting
   │             │ id                    user_id + key
   │             │
   │             └──< t_user_has_permission ──> t_user_permission
   │                        id + permission          │ id
   │                                                  │
   └──< t_user_role_has_permission ───────────────────┘
              id_role + id_permission

t_user

Column Type Notes
id int unsigned Primary key, auto increment
role varchar(32) FK → t_user_role.id, default user, ON DELETE SET NULL
firstname, lastname varchar(64) Default empty string
description varchar(512) Default empty string
email varchar(128) Unique
phone varchar(24) Default empty string
language varchar(2) Display language code
password varchar(255) password_hash() output
last_connection_at datetime Nullable
status enum('inactive','active') Default inactive
ip int unsigned sprintf('%u', ip2long($_SERVER['REMOTE_ADDR'])) at sign-up, nullable (DEFAULT NULL)
token varchar(45) Activation or password-reset token

The account is created with status = inactive and the default role user. The role is a single value: a user has exactly one role (or none if the role row was deleted).

t_user_role

Column Type Notes
id varchar(32) Primary key, used as permission identifier
description varchar(255) Human-readable label

Roles are flat. There is no parent role, no inheritance, and no implicit superuser flag.

t_user_permission

Column Type Notes
id varchar(32) Primary key, convention: <domain>-<action>
description varchar(255) Human-readable label

t_user_role_has_permission

Column Type Notes
id_role varchar(32) FK → t_user_role.id, cascade on delete
id_permission varchar(32) FK → t_user_permission.id, cascade on delete

Primary key: (id_role, id_permission).

t_user_has_permission

Column Type Notes
id int unsigned FK → t_user.id, cascade on delete
permission varchar(32) FK → t_user_permission.id, cascade on delete

Primary key: (id, permission). This table grants permissions directly to one user, in addition to the role.

t_user_setting

Column Type Notes
user_id int unsigned FK → t_user.id, cascade on delete
key varchar(32) Setting name
value varchar(32) Setting value, stored as a string

Primary key: (user_id, key).

Schema ownership and seeds

The core tables are created by project/protected/sql/V1__init.sql. Roles and permissions are seeded by repeatable migrations:

Repository Migration Adds
sy/project R__user_roles_and_permissions.sql Roles admin, blacklisted, super-admin, user; permissions page-create, page-delete, page-code, page-update
sy/bootstrap-cms R__page_and_user_permissions.sql Permissions content-*; roles content-admin, content-manager; grants to admin
sy/bootstrap-article R__page_and_user_permissions.sql Permissions article-*; role article-admin; grants to admin

Core seed result:

Role Description Core permissions
super-admin Super administrator page-create, page-delete, page-code, page-update
admin Administrator None in core; receives module permissions
user Simple user None
blacklisted Blacklisted user None

admin is not a superuser. It only has the permissions explicitly granted by plugin migrations.

The core repeatable migration truncates t_user_role, t_user_permission, and t_user_role_has_permission before inserting the core seeds. Custom roles and grants created manually in these tables are therefore lost the next time Flyway runs that repeatable migration. Direct user grants in t_user_has_permission are not truncated, but can become orphaned.

Roles

Checking a role

$service = \Project\Service\Container::getInstance();
$user = $service->user->getCurrentUser();

if ($user->hasRole('blacklisted')) {
	// deny access
}

hasRole() is a strict equality check on t_user.role:

public function hasRole($role) {
	if (!$this->data) return false;
	return ($this->data['role'] === $role);
}

Consequences:

  • hasRole('admin') does not imply any permission.
  • A user cannot have two roles.
  • If a role row is deleted, t_user.role becomes NULL; the user keeps only direct permissions.
  • Role names are application-level identifiers. Renaming a role requires updating t_user.role rows and every hasRole() call.

Using blacklisted

blacklisted is a role, but it is used as an application-level status:

  • Project\Application\Page::userAccountAction() redirects blacklisted users.
  • bootstrap-message excludes blacklisted users from message recipient lists.
  • sybootstrap excludes blacklisted users from rating queries.

This is not a permission. A blacklisted user still has their direct permissions in the database; the code must explicitly check the role.

Adding a role

INSERT INTO t_user_role (id, description)
VALUES ('moderator', 'Moderator');

Then grant permissions:

INSERT INTO t_user_role_has_permission (id_role, id_permission) VALUES
	('moderator', 'content-read'),
	('moderator', 'content-update');

Finally assign the role:

UPDATE t_user SET role = 'moderator' WHERE id = 42;

Role and permission changes take effect on the next request. Within a request, Model\User caches the permission list.

Permissions

Resolution algorithm

A user's effective permissions are the union of:

  1. permissions granted to their current role;
  2. permissions granted directly to the user.
permissions(user) = permissions(user.role) ∪ permissions(user.id)

Db\User::getPermissions() performs this in one query:

(SELECT t_user_role_has_permission.id_permission AS permission
 FROM t_user
 INNER JOIN t_user_role_has_permission ON t_user.role = t_user_role_has_permission.id_role
 WHERE t_user.id = :id)
UNION
(SELECT permission
 FROM t_user_has_permission
 WHERE id = :id)

UNION (not UNION ALL) removes duplicates when a permission is granted both through the role and directly.

There is no wildcard, no negation, and no hierarchy. A permission is present or absent.

Checking a permission

$service = \Project\Service\Container::getInstance();
$user = $service->user->getCurrentUser();

if ($user->hasPermission('page-update')) {
	// show the page update form
}

Check one permission among a list:

if ($user->hasPermissionAmong(['content-create', 'content-update', 'content-delete'])) {
	// show the content toolbar
}

Retrieve the full list:

$permissions = $user->getPermissions();
// ['page-create', 'page-update', ...]

Typical checks in the framework and plugins:

Location Check
bootstrap/src/Application/Page.php page-create, page-update, page-delete, page-code
bootstrap/src/Application/Api/Page.php page-update before the API endpoint runs
bootstrap-cms/src/Component/Cms/Content.php content-*
bootstrap-article/src/Component/Article/Content.php article-* plus ownership (user->id === article.user_id)
sybootstrap place-update, reservation, review-delete

Naming convention

Permission identifiers follow <domain>-<action>, for example:

page-create
page-update
content-history-restore
article-status
review-delete

Keep the identifier under 32 characters (column limit). Use the permission in code and the description column for the human-readable label.

Adding a permission

INSERT INTO t_user_permission (id, description)
VALUES ('article-publish', 'Publish an article');

Grant it to a role:

INSERT INTO t_user_role_has_permission (id_role, id_permission)
VALUES ('article-admin', 'article-publish');

Or grant it directly to a user:

INSERT INTO t_user_has_permission (id, permission)
VALUES (42, 'article-publish');

Direct grants are useful for one-off exceptions, but they are harder to audit than role grants. Prefer roles for durable access policies.

Listing effective permissions

SELECT permission FROM (
	SELECT rp.id_permission AS permission
	FROM t_user u
	INNER JOIN t_user_role_has_permission rp ON rp.id_role = u.role
	WHERE u.id = 42
	UNION
	SELECT up.permission
	FROM t_user_has_permission up
	WHERE up.id = 42
) AS effective
ORDER BY permission;

Protecting an API endpoint

Endpoint sub-controllers implement security():

namespace Sy\Bootstrap\Application\Api;

class Page extends \Sy\Bootstrap\Component\Api {

	public function security() {
		$service = \Project\Service\Container::getInstance();
		if (!$service->user->getCurrentUser()->hasPermission('page-update')) {
			throw new \Sy\Bootstrap\Component\Api\ForbiddenException('Permission denied');
		}
	}

}

See the API page for the full endpoint security model.

User settings

There are two distinct notions of "settings".

Profile fields

t_user.firstname, lastname, description, and language are profile fields. They are read through Model\User magic properties and updated through the CRUD service:

$service = \Project\Service\Container::getInstance();
$user = $service->user->getCurrentUser();

$name = $user->firstname;
$lang = $user->language;

$service->user->update(['id' => $user->id], [
	'firstname' => 'Ada',
	'lastname'  => 'Lovelace',
	'language'  => 'en',
]);

The account page (Project\Application\Page::userAccountAction(), sections index, change, delete) edits these fields. It does not use t_user_setting.

Key/value settings

t_user_setting provides per-user arbitrary values:

$service = \Project\Service\Container::getInstance();
$user = $service->user->getCurrentUser();

// Read one setting
$theme = $user->getSetting('theme'); // string|null

// Write one setting (insert or update)
$user->setSetting('theme', 'dark');

// Read all settings at once
$settings = $service->user->getSettings($user->id);
// ['theme' => 'dark', ...]

Service-level methods:

$service->user->getPermissions($userId);          // array
$service->user->getSettings($userId);             // [key => value]
$service->user->setSetting($userId, $key, $value);

Db\User::setSetting() uses the CRUD change() method, which issues an INSERT ... ON DUPLICATE KEY UPDATE on (user_id, key).

Status of the feature

The key/value settings API exists and is functional, but no framework or plugin code currently calls it. All current per-user preferences are stored in t_user columns. Treat t_user_setting as an extension point rather than an active feature.

Limitations

  • value is varchar(32): keep values short, or serialize them yourself.
  • Values are always strings; there is no type metadata.
  • Model\User caches the full settings map for the lifetime of the instance. After setSetting(), getSetting() on the same instance still returns the old value.
  • key and value are both limited to 32 characters.
  • Settings are deleted with the account through ON DELETE CASCADE.

Authentication and account lifecycle

Sign up and activation

SignUp form
  │  POST email
  ▼
Service\User::signUp()
  ├─ generate nickname from email
  ├─ generate random password (if none provided)
  ├─ generate token = sha1(uniqid())
  ├─ INSERT t_user: status = inactive, role = user (default)
  └─ send Welcome mail (activation + report links)
        │
        ▼
Application\User::activateAction()
  ├─ activate(email, token): status = active, token = ''
  ├─ dispatch user.activated event
  └─ signIn(email, password provided in the activation URL)

Security warning: The activation URL contains the password in plain text. Welcome.php puts the password in the password query parameter, and Application\User::activateAction() reads that parameter before calling signIn().

signUp() runs inside a transaction. When the email already exists:

Existing status Behaviour
inactive Generate a new password, update the hash, resend the welcome mail, throw ActivateAccountException
active Throw AccountExistException

Activation requires both the email and the stored token. A successful activation clears the token and emits user.activated.

Sign in

Service\User::signIn($email, $password, $remember = true):

  1. Retrieve the user by email; throw SignInException if absent.
  2. If status = inactive:
    • correct password → activate the account immediately, emit user.activated, continue;
    • wrong password → generate a new password, resend the welcome mail, throw ActivateAccountException.
  3. Verify the password with password_verify(); throw SignInException on failure.
  4. Destroy and restart the PHP session (session fixation protection).
  5. Store user_id and a fingerprint in $_SESSION.
  6. When $remember is true, set two cookies valid for one year:
    • _x: user id encrypted with AES-256-CBC using PROJECT_KEY;
    • _y: sha1(stored_password_hash . fingerprint).
  7. Update last_connection_at.
  8. Reset the cached current user.

The browser fingerprint is preg_replace('/[^a-zA-Z]/', '', $_SERVER['HTTP_USER_AGENT']).

Auto sign in

Service\User::__construct() starts the session and calls autoSignIn():

  • if the session already contains a matching user_id and fingerprint, it returns;
  • otherwise it decrypts _x, reloads the user, and compares _y with sha1($user['password'] . $fingerprint);
  • on match it renews the session, refreshes both cookies, and stores the session values.

Cookie auto sign-in is therefore invalidated after a password change because the password hash changes.

Sign out

signOut() clears $_SESSION, removes the PHP session cookie and the _x / _y cookies, then destroys the session.

The signout action is handled by Sy\Bootstrap\Application\User::signOutAction(), which redirects to the HTTP referer (or the site root).

Forgot and reset password

ForgetPassword form
  │  POST email
  ▼
Service\User::forgetPassword()
  ├─ unknown user        → User\Exception('User not found')
  ├─ inactive user       → new password + Welcome mail + ActivateAccountException
  └─ active user         → token = sha1(uniqid())
                            update t_user.token
                            send ForgetPassword mail

UserPassword page (email + token)
  ├─ verify email, status = active, token match
  │    └─ mismatch → redirect to /
  └─ render ResetPassword form

ResetPassword form
  └─ update password hash, clear token, sign in

The reset page validates the email, active status, and token on every request, including the form submission. On successful submission, ResetPassword::submitAction() updates the password, clears the token (token = ''), and signs the user in.

Account page

Project\Application\Page::userAccountAction() renders user-account with three sections:

Section Component Action
index Project\Component\User\Account Update profile fields and language
change Project\Component\User\ChangePassword Verify old password, set a new one, sign in again
delete Project\Component\User\DeleteAccount Verify password, delete the account, sign out

Blacklisted users are redirected to the site root before the page renders.

Account deletion

Service\User::delete() overrides the generic CRUD delete:

  1. Retrieve the row.
  2. Delete it; SQL cascades remove permissions and settings.
  3. Dispatch user.deleted with the deleted row.
  4. Delete the user avatar (UPLOAD_DIR/avatar/<md5 of email>.webp).

DeleteAccount is a Form\Crud\Delete component that adds a password validator before calling $service->user->delete().

Session and CSRF

Item Implementation
Session start Service\User::__construct() when no session is active
Session hardening session.cookie_httponly, session.use_strict_mode
Session renewal session_destroy() + session_start() on sign in and auto sign in
CSRF token Service\User::getCsrfToken(), stored in $_SESSION['csrfToken']
Form field Form::addCsrfField() adds __csrf and validates it
API token api/csrf endpoint refreshes the token

Not every form includes CSRF protection. The sign-in, sign-up, and forgot-password forms add both anti-spam and CSRF fields; the reset-password form adds neither.

Events

Event Emitted by Payload
user.activated signIn() (inactive account with correct password) and activate() ['email' => ...]
user.deleted delete() Deleted user row

Listeners are registered on the event service; see section 6.4 of the architecture document.

Exceptions

Exception Meaning
User\Exception Generic user error (base class, extends \Exception)
User\SignInException Unknown email or wrong password
User\SignUpException Database or mail error during sign-up
User\ActivateAccountException Account not activated, invalid token, or activation expected
User\AccountExistException Email already used by an active account
User\AccountNotExistException Declared but not currently thrown by the service

Note: Validation exceptions from the Form component extend Sy\Component\Html\Form\Exception.

Extending the user subsystem

Custom user model

Service\User::getCurrentUser() instantiates Project\Model\User when that class exists, otherwise Sy\Bootstrap\Model\User:

$userModelClass = '\\Project\\Model\\User';
if (class_exists($userModelClass)) {
	$this->currentUser = new $userModelClass(\Sy\Http::session('user_id', 0));
} else {
	$this->currentUser = new \Sy\Bootstrap\Model\User(\Sy\Http::session('user_id', 0));
}

A project-specific model can add domain methods while keeping the base behaviour:

namespace Project\Model;

class User extends \Sy\Bootstrap\Model\User {

	public function isEditor(): bool {
		return $this->hasPermissionAmong(['article-update', 'content-update']);
	}

}

The class must keep the constructor signature __construct($id).

Custom service or database service

Project\Service\Container and Project\Db\Container extend the bootstrap containers. Declaring user in either container overrides the default resolution:

namespace Project\Service;

class Container extends \Sy\Bootstrap\Service\Container {

	public function __construct() {
		parent::__construct();

		$this->user = function () {
			return new \Project\Service\User();
		};
	}

}

Without an explicit declaration:

  • Service\Container::get('user') resolves Sy\Bootstrap\Service\User;
  • Db\Container::get('user') resolves Sy\Bootstrap\Db\User;
  • any other unknown database service resolves to t_<snake_case_name>.

Model magic properties

Model\User::__get() exposes every column of t_user as a read-only property:

$user->id;
$user->email;
$user->firstname;
$user->role;
$user->status;
$user->language;

Unknown keys return null. There is no __set(); use $service->user->update() for writes.

Adding a setting

  1. Choose a key of at most 32 characters.
  2. Write through the model:
$user->setSetting('items-per-page', '50');
  1. Read it where needed:
$perPage = (int) ($user->getSetting('items-per-page') ?? 20);
  1. Document the key and its accepted values in the application code. There is no central registry and no validation layer.

Known limitations

  • No administration UI. Roles, permissions, and grants are managed only through SQL migrations or direct database access.
  • Flat, single role. No hierarchy, no multiple roles, no wildcard. hasRole('admin') grants nothing by itself.
  • blacklisted is overloaded. It is a role used as an application status, while t_user.status already models active/inactive accounts.
  • t_user_setting is unused and undersized. Values are varchar(32), always strings, with no serialization or schema.
  • Settings cache is not invalidated on write. Model\User::setSetting() does not refresh the instance's cached $settings array.
  • Permissions are cached per model instance. Service\User caches the current user for the request; a new Model\User instance reloads permissions from the database.
  • Auto sign-in updates last_connection_at even when validation fails. In autoSignIn(), the update runs after the cookie hash check, including on mismatch.
  • Reset form submission invalidates the token. The token is cleared (token = '') upon successful password update to prevent re-use. Note that the reset link exposes the token in the URL, risking leaks via server logs or browser history.
  • Activation link exposes credentials. The password is sent in plain text via the activation URL.
  • Repeatable role migration truncates tables. Custom roles and grants can be lost when Flyway reruns R__user_roles_and_permissions.sql.
  • No permission registry. Permission identifiers are plain strings shared by convention across repositories; typos silently deny access.
  • Direct user grants are easy to miss. They do not appear in role-based reviews and bypass role changes.

Quick reference

Service\User

Method Purpose
signIn($email, $password, $remember = true) Authenticate, create the session and remember-me cookies
signUp($email, $password = null) Create an inactive account and send the welcome mail
signOut() Destroy the session and cookies
activate($email, $token) Activate an account
report($email, $token) Delete an account reported from the welcome mail
forgetPassword($email) Generate a reset token and send the mail
getCurrentUser() Return the current Model\User (cached per request)
getCsrfToken() Return the session CSRF token
setLanguage($language) Change the display language
passwordVerify($password, $hash) Wrapper around password_verify()
delete(array $pk) Delete the account, dispatch the event, remove the avatar (overrides Service\Crud::delete)
getPermissions($userId) Delegated to Db\User
getSettings($userId) Delegated to Db\User
setSetting($userId, $key, $value) Delegated to Db\User
create, retrieve, update, delete, retrieveAll, foreachRow, change, count, getColumns, transaction Inherited from Service\Crud

Model\User

Method Returns
isConnected() true when the row exists
hasRole($role) Strict comparison with t_user.role
getPermissions() Effective permission list (cached)
hasPermission($permission) Presence in the effective list
hasPermissionAmong(array $permissions) At least one match
getSetting($key) Value or null
setSetting($key, $value) Upsert in t_user_setting
__get($name) Column value or null

Db\User

Method Purpose
getPermissions($id) Union of role and direct permissions
getSettings($id) All settings as [key => value]
setSetting($id, $key, $value) Upsert one setting

SQL snippets

Effective permissions for user 42:

SELECT permission FROM (
	SELECT rp.id_permission AS permission
	FROM t_user u
	INNER JOIN t_user_role_has_permission rp ON rp.id_role = u.role
	WHERE u.id = 42
	UNION
	SELECT up.permission
	FROM t_user_has_permission up
	WHERE up.id = 42
) AS effective
ORDER BY permission;

Create and grant a permission:

INSERT INTO t_user_permission (id, description)
VALUES ('article-publish', 'Publish an article');

INSERT INTO t_user_role_has_permission (id_role, id_permission)
VALUES ('article-admin', 'article-publish');

INSERT INTO t_user_has_permission (id, permission)
VALUES (42, 'article-publish');

Read and write a setting:

SELECT `key`, `value` FROM t_user_setting WHERE user_id = 42;

INSERT INTO t_user_setting (user_id, `key`, `value`)
VALUES (42, 'theme', 'dark')
ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);

Show each user with their role description:

SELECT u.id, u.email, u.status, u.role, r.description AS role_description
FROM t_user u
LEFT JOIN t_user_role r ON r.id = u.role
ORDER BY u.id;

Clone this wiki locally