Security API – Security Class
The Security class provides a complete authentication, authorisation and protection toolkit. It covers user login/logout, session management, permissions, owner‑based row‑level security, password hashing, CSRF, rate limiting, TOTP two‑factor authentication and secure "Remember Me" cookies. Every method is static and safe – no manual session manipulation needed.
Contents
- Recipes – real-world one-liners
- Authentication – Login, Logout, LoginAs
- User State – IsLoggedIn, IsAdmin, CurrentUser*, etc.
- Auth Guards – RequireAuth, RequireRole
- Table‑level Permissions
- Allowed Pages
- OwnerID (Row‑level Security)
- Password Utilities
- Remember Me
- CSRF Protection
- Rate Limiting
- Two‑factor for your console account (setup)
- Two‑factor Authentication (TOTP) — developer API
- Display Name
- Secure Token Generation
Recipes – real-world one-liners
The everyday security jobs, the short way. Most reads are also available through
pp()
(pp()->user(), pp()->role(), pp()->can()) — use whichever reads best.
Who's logged in?
if (!Security::IsLoggedIn()) redirect(pp()->url('login'));
$name = Security::CurrentUsername(); // "jsmith"
$me = Security::CurrentUserData(); // the whole user row
$role = Security::CurrentUserGroup(); // "admin" / "user" …
$admin = Security::IsAdmin();
Guard a page or an action
Security::RequireAuth(); // must be logged in (redirects otherwise)
Security::RequireRole('admin'); // must have this role
// a softer, inline check that returns a bool
if (!Security::HasPermission('edit', 'orders')) {
pp()->toast('error', 'You cannot edit orders');
return;
}
Scope data to the current user (row-level security)
// only show the signed-in user's own records
$mine = pp()->table('tickets')->where('assigned_to', Security::GetOwnerId())->get();
// …or, in a Designer WHERE tab / Lookup, the SQL-variable way:
// assigned_to = :userid
// see the SQL Variables guide.
Passwords — never store plain text
$hash = Security::HashPassword(post('password')); // bcrypt/argon
pp()->update('users', $id, ['password' => $hash]);
// on login
if (Security::VerifyPassword(post('password'), $row['password'])) { /* ok */ }
Protect a form (CSRF) & slow down brute force
// in the form
echo '<input type="hidden" name="_token" value="' . Security::CSRF()->Token() . '">';
// on submit
if (!Security::CSRF()->Check(post('_token'))) { http_response_code(419); exit; }
// rate-limit an endpoint: 5 tries per 60s per key
if (!Security::RateLimit('login:' . post('username'), 5, 60)) {
pp()->toast('error', 'Too many attempts — try again soon');
return;
}
A one-off secure token
$token = Security::GenerateToken(32); // e.g. a password-reset / invite link
pp()->insert('invites', ['email' => post('email'), 'token' => $token, 'created' => now()]);
Authentication
Login – Standard username/password
// Basic login
if (Security::Login($username, $password)) {
echo "Welcome, " . Security::CurrentUsername();
} else {
echo "Invalid credentials.";
}
Login with “Remember Me”
// Pass true to set a persistent cookie (30 days)
Security::Login($username, $password, true);
Login without password (e.g. after OAuth)
// LoginAs only needs a username – no password check
Security::LoginAs('john.doe');
Check credentials without logging in
if (Security::CheckUsernamePassword('admin', 'secret')) {
// valid, but session is unchanged
}
Logout
Security::Logout();
// After logout, all session data is removed.
// You should redirect to the login page.
header('Location: /login');
User State
// Is anybody logged in?
if (Security::IsLoggedIn()) { … }
// Is the current user a superadmin?
if (Security::IsAdmin()) { … }
// Is the visitor a guest?
if (Security::IsGuest()) { … }
// Get the username
echo Security::CurrentUsername(); // e.g. "john.doe"
// Get the role/group
echo Security::CurrentUserGroup(); // "superadmin", "developer", "user"
// Get all groups (array) – currently wraps role in an array
$groups = Security::CurrentUserGroups();
// Full user data array (cached in session)
$user = Security::CurrentUserData();
echo $user['email'];
// Reload user data from database
Security::RefreshUserData();
Table‑level Permissions
Each table has seven permission bits: Add, Delete, Edit, Search/List, Print/Export, Import, Manage (admin).
Set permissions for a table
// Using a string (each letter grants the corresponding right)
Security::SetPermissions('orders', 'ADES'); // can add, delete, edit, search
// Using an array
Security::SetPermissions('products', [
'A' => true,
'D' => false,
'E' => true,
'S' => true,
'P' => true,
'I' => false,
'M' => false
]);
Check a specific permission
if (Security::HasPermission('orders', 'E')) {
echo "User can edit orders.";
} else {
echo "Edit access denied.";
}
Retrieve all permissions for a table
$perms = Security::GetPermissions('orders');
if ($perms['A']) { echo "Can add"; }
Allowed Pages
Fine‑grained control over which individual pages a user can access for a table and page type (list, add, edit, view, print, search).
Set allowed pages
// Allow only the "summary" and "details" pages for the list type
Security::SetAllowedPages('orders', 'list', ['summary', 'details']);
// A single page as a string
Security::SetAllowedPages('orders', 'add', 'order_add');
Get allowed pages
$pages = Security::GetAllowedPages('orders', 'list');
if (in_array('summary', $pages)) {
echo "Summary page is allowed.";
}
OwnerID (Row‑level Security)
When a table has “own data only” security, the system needs to know which ID belongs to the current user. OwnerID stores that value.
Set OwnerID
// After login, set the user's ID as the owner for the customers table
Security::SetOwnerId('customers', $user['id']);
Get OwnerID
$ownerId = Security::GetOwnerId('customers');
DB::Select('customers', ['assigned_to' => $ownerId]);
Password Utilities
Hash a password
$hashed = Security::HashPassword('mySecureP@ss');
// Uses bcrypt (PASSWORD_DEFAULT)
Verify a password
if (Security::VerifyPassword('mySecureP@ss', $hashed)) {
// valid
}
Check if a hash needs rehashing
if (Security::PasswordNeedsRehash($hashed)) {
$newHash = Security::HashPassword($newPassword);
DB::Update('users', ['password' => $newHash], ['id' => $userId]);
}
Remember Me
// When logging in with rememberMe = true, a long‑lived cookie is set.
Security::Login($username, $password, true);
// On subsequent visits, before any authentication check:
if (!Security::IsLoggedIn() && Security::LoginFromRememberMe()) {
// User was logged in via cookie; session is now active.
}
CSRF Protection
// Generate a CSRF token (stored in session)
$token = Security::CSRF()->Token();
// Output a hidden field in a form
echo Security::CSRF()->HiddenField();
// Check a submitted token
if (!Security::CSRF()->Check($_POST['_token'] ?? '')) {
die('Invalid CSRF token.');
}
// Regenerate token (e.g. after login)
Security::CSRF()->Regenerate();
Check() method uses hash_equals() for timing‑safe comparison.
Rate Limiting
// Protect a login endpoint from brute‑force attacks
$key = 'login:' . $_SERVER['REMOTE_ADDR'];
$maxAttempts = 5;
$window = 60; // 60 seconds
if (!Security::RateLimit()->Check($key, $maxAttempts, $window)) {
$remaining = Security::RateLimit()->Remaining($key, $maxAttempts, $window);
die("Too many attempts. Try again in $window seconds.");
}
// After a failed login:
Security::RateLimit()->Hit($key);
// After a successful login, you can clear the rate limit:
// (Manually unset the session key or wait for the window to expire)
Two‑factor for your console account all roles
This is the ready-to-use, self-service 2FA for the PPPHP console login itself
(distinct from the developer Security::TOTP() API below, which is for building 2FA into generated apps).
Any signed-in user — user, developer, superadmin or owner — can turn it on for their own account.
- Where: your avatar menu → Security & 2FA, or open
/account/securitydirectly (also linked from your Profile page). - Turn it on: flip the master switch — the setup expands. Pick Authenticator app (scan the QR with Google Authenticator / Authy / 1Password, or type the key), or Email codes (a 6-digit code emailed at each sign-in). Confirm one code to enable it.
- Backup codes: you get 10 single-use recovery codes, shown once — save them. Regenerate a fresh set anytime.
- Signing in: after your password, a verification screen asks for a code from your app/email, or a backup code if your device is lost.
- Turn it off: confirm your current password in the Turn off two-factor card.
Notes: email codes require the platform email to be configured under Settings. The owner's signed break-glass access token bypasses 2FA by design, so a lost device can never lock the vendor out. There's also an in-page Guide button on the security page.
Two‑factor Authentication (TOTP) — developer API
// Generate a secret for a user
$secret = Security::TOTP()->GenerateSecret(); // e.g. "JBSWY3DPEHPK3PXP"
DB::Update('users', ['totp_secret' => $secret], ['id' => $userId]);
// Get the QR code URL (for apps like Google Authenticator)
$qrUrl = Security::TOTP()->GetQRCodeUrl($username, $secret, 'MyApp');
// Display as a QR image using a service or JavaScript library
// Verify a code entered by the user
$code = $_POST['totp_code']; // 6 digits
if (Security::TOTP()->Verify($secret, $code)) {
echo "Code is valid!";
} else {
echo "Invalid code.";
}
// Verify with a wider time drift (±2 periods, ±60 seconds)
Security::TOTP()->Verify($secret, $code, 2);
Display Name
// Get the current user's display name
echo Security::GetDisplayName(); // returns fullname, or username as fallback
// Set a custom display name in the session (temporary)
Security::SetDisplayName('John (Admin)');
Secure Token Generation
// Generate a cryptographically secure random token (hex)
$token = Security::GenerateToken(); // 64 hex chars (32 bytes)
$shortToken = Security::GenerateToken(16); // 32 hex chars (16 bytes)
// Use for CSRF, password resets, invitation links, etc.
Auth Guards – RequireAuth, RequireRole
These are shortcut methods that immediately stop the request if the user is not authenticated or lacks the required role. They replace the repetitive guard code that was previously duplicated in every controller.
RequireAuth()
Redirects to the login page if the user is not logged in. Use it at the top of any protected method.
// Protect a whole controller method
public function listProjects(): void {
Security::RequireAuth();
// ... your code here
}
RequireRole(array $roles)
Stops with a 403 Forbidden message if the current user's role is not in the allowed list.
// Only superadmin and developer can create projects
Security::RequireRole(['superadmin', 'developer']);
Combined example
public function createProject(): void {
Security::RequireAuth();
Security::RequireRole(['superadmin', 'developer']);
// proceed with project creation...
}