Skip to content

Admin Authentication & SSO ​

Flow ID: AD-01 Module(s): auth, sso, advisable Complexity: Medium Last Updated: 2026-11-04 — 4.129.0 resync: citations re-anchored; password hashing migration (#895: auth_hash_migrate_to, wrapped legacy hashes, upgradeAdminPasswordHash() on admin login) and the AdvWrapLegacyPasswordHashes job (#966) documented; '' family wording and logout/revoke description corrected; previous: 2026-10-21 — one REST session per device (#954, API 1.122): the admin login no longer ends the admin's other sessions, logout and reuse end one session, access tokens carry sid, live sessions are capped; previous: 2026-10-17 — a constructor role gate's error_401() now stops the action (#936); previous: 2026-10-13 — 4.127.0 resync: /rest/auth/admin/refresh now rotates the refresh token with reuse detection (#790, API 1.115), AdminAuth/RefreshTokenModel citations and refresh_tokens columns refreshed; previous: 2026-10-02 — 4.125.0 resync: POST /rest/auth/admin/logout (#790) added, AdminAuth.php citations refreshed; previous: 2026-06-12

Business Overview ​

Admin authentication supports three providers: database auth (default), static config auth (fallback), and OAuth2/OIDC SSO via Keycloak. The system uses 9 roles mapped to dedicated admin panel home pages. Rate limiting (IP-based, 5 attempts / 10-minute window) protects the session-based login against brute force. The REST admin login is separately brute-force throttled by LoginThrottle (#5): 5 failures per identifier and 20 failures per IP within a 15-minute fixed window result in a 429 Too Many Requests response with a Retry-After header. In addition to session-based auth for the admin panel, the REST API layer provides stateless JWT authentication for admin users with access + refresh token pairs.

The auth module also includes an internal task management system for admin users (create, assign, complete tasks), and an audit logging subsystem that records admin actions to a dedicated table.

API Reference ​

REST Endpoints (JWT-Based) ​

MethodPathControllerDescription
POST/rest/auth/admin/loginAdvisable\Rest\Auth\AdminAuth::loginAuthenticate admin user, returns JWT access + refresh tokens. Returns 429 + Retry-After when brute-force throttle fires.
POST/rest/auth/admin/refreshAdvisable\Rest\Auth\AdminAuth::refresh (src/Rest/Auth/AdminAuth.php:133-159)Exchange a refresh token for a new access token (roles re-read) AND a rotated refresh token; the presented token is superseded (#790, API 1.115). Body {refresh_token}; 400 when missing, 401 for an unknown, expired, other-type or reused token. Returns {access_token, refresh_token}.
POST/rest/auth/admin/logoutAdvisable\Rest\Auth\AdminAuth::logout (src/Rest/Auth/AdminAuth.php:191-201)End the session the presented refresh token belongs to (#790, #954): every refresh token of its family (one sign-in), rotated ones included, is deleted; the admin's sessions on other devices stay signed in. Body {refresh_token}; no access token needed (policy: the AdminAuth class default auth: none, application/config/rest_policies.php:189); always answers 200 {message: "Logged out."} and is idempotent. Revokes via RefreshTokenModel::revoke($token, REST_BACKEND_USER) (REST_BACKEND_USER = 'backend', application/config/constants.php:234). Routes: application/config/rest_routes.php:8-9 (plain + locale-prefixed). An access token already issued stays valid until it expires.

Admin Panel Routes (Session-Based) ​

RouteControllerDescription
advisable/loginAdv_login::loginLogin form + POST handler
advisable/login/logoutAdv_login::logoutDestroy session, redirect to login
advisable/sso/loginAdvSso::loginRedirect to Keycloak authorization URL
advisable/sso/callbackAdvSso::callbackOAuth2 code exchange callback
advisable/sso/logoutAdvSso::logoutKeycloak end-session + local session destroy

User management routes (auth, auth/add, auth/edit/{id}, auth/delete/{id}, auth/undelete/{id}, auth/changePassword/{id}, auth/changeMyPassword) are documented in (see AD-58 Admin User Management for the full legacy and REST route tables, RBAC policies, and endpoint details).

Task management routes (auth/tasks, auth/myTasks, auth/tasksTo, etc.) are documented in AD-55 Task Management.

Code Flow ​

Database Login Flow (Session-Based) ​

Adv_login::login()
  |-- Load Blocking library
  |-- POST: username + pwd
  |     |-- Advauth::login($username, $password)
  |     |     |-- Check $dbAuth flag (from config 'db_auth')
  |     |     |-- users_model->getByUsername($username)
  |     |     |-- Guard: $user->soft_delete must be 0
  |     |     |-- advAuthVerify($password, $user->password) [bcrypt/argon2i, wrapped legacy hashes, or the legacy `auth_hash` scheme; Advauth.php:118]
  |     |     |-- upgradeAdminPasswordHash($user, $password) [Advauth.php:119; re-hashes into the auth_hash_migrate_to scheme when one is set]
  |     |     |-- user_role_model->getUserRolesIds($user->id) -> array of role IDs
  |     |     |-- session->set_userdata([uid, username, roles, loggedIn, uprovider=2])
  |     |     \-- return true
  |     |-- blocking->attempt(true) [clears IP record on success]
  |     |-- roles_model->getRole($roles[0]) -> get role home page
  |     \-- redirect($firstRole->home)
  |-- On failure:
  |     |-- blocking->attempt(false) [increments IP counter]
  |     \-- render['wrong_data'] = 1
  \-- blocking->allowAttempt() -> false if >=5 attempts within 10 min -> redirect to admin

Config Auth Flow (Fallback) ​

Advauth::login()
  |-- Check $configAuth flag (from config 'simple_auth')
  |-- Read config_auth array from auth.php
  |-- Plain-text comparison: username == $user['username'] && password == $user['password']
  |-- session->set_userdata([uid=null, username, roles, loggedIn, uprovider=1])
  \-- return true

Config users are defined in application/config/auth.php via environment variables:

  • APP_ADMIN_USERNAME / APP_ADMIN_PWD with AUTH_ROLE_ADMIN
  • APP_ADMIN_ADVISABLE_USERNAME / APP_ADMIN_ADVISABLE_PWD with AUTH_ROLE_ADVISABLE

SSO Login Flow (Keycloak OIDC) ​

AdvSso::login()
  |-- SingleSignOn::getLoginUrl()
  |     |-- OIDC discovery: GET {keycloak}/realms/{realm}/.well-known/openid-configuration [cached via PSCache]
  |     |-- Build URL: authorization_endpoint + client_id + response_type=code + scope=openid roles
  |     \-- redirect to Keycloak
  |
AdvSso::callback()
  |-- Verify ?iss matches expected issuer ({server}/realms/{realm})
  |-- failOnError(?error)
  |-- expectAuthorizationCode(?code)
  |-- exchangeAuthorizationCodeForTokens($code)
  |     |-- POST to token_endpoint with grant_type=authorization_code
  |     |-- client_id + client_secret from env
  |     \-- returns [access_token, refresh_token, full_response]
  |-- decodeAccessToken($accessToken)
  |     |-- Extract kid from JWT header
  |     |-- Match kid against JWKs (cached from jwks_uri)
  |     |-- Extract x5c certificate, build PEM
  |     \-- JWT::decode($accessToken, new Key($pem, $alg))
  |-- determineRoleFromAccessToken($decoded)
  |     |-- Read groups claim from token
  |     |-- Build group paths to check (org+site combos with defaults):
  |     |     /group-org-{orgId}/group-site-{siteId}/role-{roleName}
  |     |-- Cross-reference realm_access.roles (prefixed 'ecommercen-v4-{role}')
  |     |-- Match group path against ROLE_MAPPING
  |     \-- Return AUTH_ROLE_* constant
  |-- session->set_userdata([sso_access_token, sso_refresh_token, uid=null, username=$name, roles=[$role], loggedIn, uprovider=3])
  \-- redirect to role home page

SSO Session Validation (Every Admin Page Load) ​

The Adv_admin_controller constructor calls validateSSOSession() on every request:

validateSSOSession() [ecommercen/helpers/auth_helper.php]
  |-- Skip if uprovider != AUTH_PROVIDER_SSO
  |-- Try to decode current sso_access_token
  |-- On DecodeTokenException (expired):
  |     |-- refreshAccessToken(sso_refresh_token)
  |     |     |-- POST to token_endpoint with grant_type=refresh_token
  |     |     \-- returns new [access_token, refresh_token]
  |     |-- Decode new access token
  |     |-- Determine new role
  |     \-- Update session with new tokens + roles
  |-- On any other SSO exception:
  |     |-- Destroy session data
  |     \-- Re-throw (controller catches and redirects)

REST API JWT Auth Flow ​

AdminAuth::login()                                            [AdminAuth.php:60]
  |-- Read username + password from JSON body or POST        [AdminAuth.php:62-64]
  |-- throttle->retryAfter('admin-login', ip, username)      [AdminAuth.php:71]
  |     |-- Checks per-identifier counter and per-IP counter in L2 cache
  |     |-- Returns seconds-to-retry (int) when either limit is exceeded
  |     \-- Returns null when attempt is allowed
  |-- On throttle hit: set Retry-After header, return 429    [AdminAuth.php:72-74]
  |-- Advauth::statelessAdminLogin($username, $password)     [AdminAuth.php:77]
  |     |-- Check DB auth: users_model->getByUsername, advAuthVerify, then upgradeAdminPasswordHash   [Advauth.php:180-191]
  |     |-- Check config auth: plain-text match
  |     \-- Return user ID or null
  |-- On invalid credentials:
  |     |-- throttle->recordFailure('admin-login', ip, username) [AdminAuth.php:78]
  |     |     |-- Increments per-identifier counter in L2 cache
  |     |     \-- Increments per-IP counter in L2 cache
  |     \-- Return 401                                        [AdminAuth.php:79]
  |-- throttle->clearIdentifier('admin-login', username)     [AdminAuth.php:83]
  |     \-- Deletes per-identifier counter (IP counter is NOT cleared)
  |-- getUserRoles($userId)
  |     |-- Check config_auth users first (match by username)
  |     \-- Fall back to user_role_model->getUserRolesIds
  |-- Tokens::generateRefreshToken($userId, REST_BACKEND_USER)    [AdminAuth.php:87, Tokens.php:55-65; #954: a new session]
  |     |-- Generate 64-char random hex token and a random 32-char family_id
  |     |-- Store in refresh_tokens table with expiry (the admin's other rows are kept)
  |     \-- Evict the least recently used families past REST_AUTH_MAX_SESSIONS_PER_USER
  |-- Tokens::generateAccessToken($userId, REST_BACKEND_USER, $roles, $family_id)    [AdminAuth.php:90, Tokens.php:18-45]
  |     |-- JWT payload: iss, aud, iat, nbf, exp, data{userId, type, roles, sid}
  |     \-- Signed with HS256 (configurable)
  \-- Return {access_token, refresh_token}

AdminAuth::refresh()                                          [AdminAuth.php:133-159]
  |-- Read refresh_token from JSON body or POST; 400 if missing
  |-- Tokens::rotateRefreshToken($token, REST_BACKEND_USER)   [Tokens.php:74-88]
  |     \-- RefreshTokenModel::rotate()                       [RefreshTokenModel.php:176-195]
  |           |-- unknown / expired / other user type -> null -> 401
  |           |-- current token -> INSERT successor (expires_at = now + JWT_REFRESH_TOKEN_EXPIRY), mark presented row rotated
  |           |-- superseded, within JWT_REFRESH_TOKEN_GRACE -> return the session's current token, rotate nothing
  |           \-- superseded, after the grace window (reuse) -> delete that session (its chain) only -> 401
  |-- getUserRoles($rotated['user_id'])                       [AdminAuth.php:148]
  \-- Return {access_token (current roles, sid = the family), refresh_token (the successor)}

AdminAuth::logout()                                           [AdminAuth.php:191-201]
  |-- Read refresh_token from JSON body or POST              [AdminAuth.php:193-194]
  |-- If it is a non-empty string:
  |     \-- RefreshTokenModel::revoke($token, REST_BACKEND_USER)  [AdminAuth.php:196-198]
  \-- Always return 200 {message: "Logged out."}             [AdminAuth.php:200]

Domain Layer ​

Legacy Auth Module (ecommercen/auth/) ​

FileDescription
controllers/Adv_auth.phpUser CRUD + task management (702 lines). Role-gated: ADVISABLE+ADMIN for user management. ADVISABLE-only users cannot see Advisable/Developer roles in dropdown. Extensible via afterAdd/afterEdit/afterDelete hooks.
models/Adv_users_model.phpUsers table CRUD + audit log queries. Soft-delete pattern. guardUserEdit() prevents password/soft_delete modification via edit.
models/Adv_roles_model.phpDB-based roles. Constructor reads the roles table. Provides dropdown, getRoles, getRole, getRolesByIds, getRoleByName, getRolesByName.
models/Adv_user_role_model.phpJunction table user_role management. Diff-based update: calculates roles to add/remove.
models/Adv_tasks_model.phpTasks CRUD — see AD-55 Task Management for full model reference.

SSO Module (ecommercen/sso/) ​

FileDescription
controllers/AdvSso.phpLogin, callback, logout endpoints. Extends Base_c (not Admin_c -- unauthenticated entry point). Uses guard() wrapper for exception handling.

Modern SSO Layer (src/Auth/SingleSignOn/) ​

FileDescription
SingleSignOn.phpComplete OIDC client (472 lines). Handles discovery, JWK loading, token exchange, token refresh, JWT decoding, group-based role determination.
Exception/BaseException.phpBase with HTTP status code support
Exception/NotEnabledException.phpSSO feature flag disabled
Exception/AuthorizationCodeMissingException.phpMissing ?code parameter
Exception/AuthorizationExchangeFailedException.phpToken exchange HTTP error
Exception/DecodeTokenException.phpJWT decode failure (expired, malformed, no matching key)
Exception/JWKsIrretrievableException.phpCannot fetch JWK set
Exception/MissingGroupsClaimException.phpJWT has no groups claim
Exception/OpenIDConfigurationIrretrievableException.phpCannot fetch OIDC discovery
Exception/RoleMismatchException.phpGroup matched but role not in ROLE_MAPPING
Exception/RoleMissingException.phpNo matching group path found
Exception/TokenRefreshFailedException.phpRefresh token exchange failed
Exception/UnexpectedIssuerException.php?iss does not match expected realm

REST Auth Layer (src/Rest/Auth/) ​

FileDescription
AdminAuth.phpAdmin JWT login + refresh + logout (217 lines). OpenAPI annotated. Brute-force throttle injected as $throttle.
LoginThrottle.phpFixed-window brute-force throttle (159 lines). Two counters per realm (per-identifier + per-IP), counted on failed attempts only, stored in L2 cache. Fail-open: cache errors are logged as warnings and logins proceed unthrottled.
CustomerAuth.phpCustomer JWT login + refresh + logout + register + forgot/reset password (separate system; see CF-10 Customer Auth).
Tokens.phpJWT generation (access), refresh token generation on login (generateRefreshToken(), :55-65) and refresh-token rotation (rotateRefreshToken(), :74-88). Uses firebase/php-jwt.
Config.phpConfig DTO: key, algorithm, accessTokenExpire, refreshTokenExpire, refreshGraceSeconds (JWT_REFRESH_TOKEN_GRACE, default 60, clamped 0..3600 by normaliseGrace(), :28-36) and maxSessionsPerUser (normaliseMaxSessions(), :42-50).
RefreshTokenModel.phpCRUD for refresh_tokens table. Extends CI_Model. rotate() (:176, one transaction with SELECT ... FOR UPDATE, retried once on deadlock/lock wait timeout) implements the rotation, grace window and reuse detection; revoke(string $token, string $userType) (:61-70) ends the presented token's session through deleteSession() (:335-361), which follows replaced_by for at most 10 hops and deletes each real family met on the chain whole and each '' row by id (the user's other sessions are kept); it is used by both logout endpoints. revokeFamiliesExcept() and evictLeastRecentlyUsedFamilies() (#954) back the REST customer password change and the session cap.
TokenProtect.phpMiddleware-style JWT validation for protected endpoints.
BackendGuard.php / FrontendGuard.php / AnyGuard.phpRoute guards by user type.
RemoveExpiredRefreshTokens.phpCleanup job for expired refresh tokens.

Auth Helper (ecommercen/helpers/auth_helper.php) ​

Global functions loaded on every admin request:

  • isLoggedIn() -- checks session loggedIn
  • validateSSOSession() -- auto-refreshes SSO tokens
  • allowRole($roles, $roleIds) -- checks if any session role matches allowed list
  • advAuthHash($val, $token) -- delegates to Advauth::advAuthHash()
  • isAdvisableUser(), isDeveloper(), isAdmin(), isCmsUser(), isProductsUser(), isReportingUser(), isOrdersUser(), isMarketingUser(), isMediaUser() -- individual role checks
  • mergeUsersRoles($users, $usersRoles) -- decorates user objects with roles
  • allowedUsers($users, $roles) -- filters users by roles

Architecture ​

Authentication Providers ​

IDConstantSourcePassword HandlingSession uid
1AUTH_PROVIDER_CONFIGapplication/config/auth.php (config_auth)Plain-text comparisonnull
2AUTH_PROVIDER_DBusers tableadvAuthVerify(): password_verify() (bcrypt/argon2i), wrapped legacy hashes, or the legacy auth_hash scheme (see Password Hashing)User ID
3AUTH_PROVIDER_SSOKeycloak OIDCJWT signature verificationnull

Provider priority in Advauth::login(): DB auth checked first, then config auth. Both can be enabled simultaneously via config flags db_auth and simple_auth.

9 Admin Roles ​

ConstantIDNameHome RouteDescription
AUTH_ROLE_ADVISABLE1AdvisableadvisableSuperuser -- platform developers
AUTH_ROLE_DEVELOPER2DeveloperadvisableDevelopment access
AUTH_ROLE_ADMIN3AdminadvisableClient admin
AUTH_ROLE_CMS4CMScategory/category_adminContent management
AUTH_ROLE_PRODUCTS5Productsproducts_adminProduct catalog
AUTH_ROLE_ORDERS6Ordersorders_adminOrder management
AUTH_ROLE_REPORTING7Reportingeshop/reportingReports & analytics
AUTH_ROLE_MARKETING8Marketingpromo_adminCampaigns & promotions
AUTH_ROLE_MEDIA9Mediasliders/sliders_adminSlider/media management

Defined in application/config/constants.php (lines 99-107). Role metadata (name, home) stored in the roles database table (seeded by migration 20260409131959_create_roles_table.php).

Keycloak Group Path Resolution ​

SSO role determination follows a priority-ordered group path search:

  1. /group-org-{orgId}/group-site-{siteId}/role-{roleName} (exact match)
  2. /group-org-{orgId}/group-site-default/role-{roleName} (default site)
  3. /group-org-default/group-site-{siteId}/role-{roleName} (default org)
  4. /group-org-default/group-site-default/role-{roleName} (full default)

The role name is extracted from realm_access.roles with prefix ecommercen-v4- stripped, then matched against ROLE_MAPPING (advisable, developer, admin, cms, products, orders, reporting, marketing, media).

Password Hashing ​

Configured in application/config/auth.php via auth_hash:

Config ValueAlgorithmNotes
password-hash-mcrypt (default)PASSWORD_BCRYPT via password_hash()Recommended
password-hash-argon2iPASSWORD_ARGON2I via password_hash()PHP 7.2+
md5md5()Deprecated -- do not use
md5-tokenmd5($val . $token)Deprecated -- salt-based MD5
wecare-cryptsha1()Legacy -- verify accepts md5 OR sha1

Migration target (auth_hash_migrate_to, #895) ​

auth_hash_migrate_to (application/config/auth.php:22, default null) accepts password-hash-mcrypt or password-hash-argon2i. Any other value, or Argon2 on a PHP build without it, logs an error and turns the migration off (Advauth::migrationTargetAlgo(), application/libraries/Advauth.php:54-83). When set, advAuthHash() writes password_hash() in that scheme (:235-237). advAuthVerify() also accepts $wrap1$ wrapped legacy hashes (:260-262, verifyWrappedHash() :402-415). A successful DB admin login on the session path (Advauth::login(), :119) and on the stateless path (statelessAdminLogin(), :189) calls upgradeAdminPasswordHash() (:417-428), which replaces a hash that needs a rehash via Adv_users_model::replacePasswordHash() (ecommercen/auth/models/Adv_users_model.php:51). The one-off job AdvWrapLegacyPasswordHashes (#966, scope=users covers the users table) wraps stored legacy hashes in place; see SY-09 Customer Data Jobs.

JWT Token Structure (REST API) ​

Access token payload:

json
{
  "iss": "https://site-url.com/",
  "aud": "https://site-url.com/",
  "iat": 1712345678,
  "nbf": 1712345678,
  "exp": 1712349278,
  "data": {
    "userId": "42",
    "type": "backend",
    "roles": [1, 3]
  }
}

Refresh tokens are opaque 64-character hex strings stored in the refresh_tokens table.

Session Data Structure ​

php
// DB Auth
['uid' => 42, 'username' => 'admin', 'roles' => [1, 3], 'loggedIn' => true, 'uprovider' => 2]

// Config Auth
['uid' => null, 'username' => 'admin', 'roles' => [3], 'loggedIn' => true, 'uprovider' => 1]

// SSO Auth
['uid' => null, 'username' => 'John Doe', 'roles' => [1], 'loggedIn' => true, 'uprovider' => 3,
 'sso_access_token' => '...jwt...', 'sso_refresh_token' => '...']

Data Model ​

users and user_role Tables ​

Full column-level schema, indexes, and FK notes for users and user_role are documented in (see AD-58 Admin User Management for canonical schema of both tables). Key auth-relevant facts: soft_delete = 1 blocks login; user_role.role_id has a FK to roles(id) via fk_user_role_role_id.

block_access Table ​

ColumnTypeDescription
idINT(11) PK AIRecord ID
ipVARCHAR(15)Client IP address
attemptsTINYINT(1)Failed attempt count
last_attemptDATETIMETimestamp of last attempt

Index: ip. Records auto-deleted when block window expires (10 minutes).

user_audit_logs Table ​

Full schema documented in (see AD-32 Audit Logging for the canonical user_audit_logs column definitions, indexes, and migration reference). Auth-relevant fact: SSO users produce rows with user_id = null; provider records DATABASE or CONFIG.

tasks Table ​

See AD-55 Task Management for the canonical schema. Key points: title is TEXT (not VARCHAR), there is no updated_at column, and the table has no Phinx migration (defined only in database/initial/initial.sql).

refresh_tokens Table ​

ColumnTypeDescription
idINT UNSIGNED, PKAuto-increment row id; the target of replaced_by
user_idVARCHAR(255)User ID or username
user_typeVARCHAR(10), default backendbackend (REST_BACKEND_USER) or customer (REST_FRONTEND_USER), application/config/constants.php:234-235; added by database/migrations/20260309131750_add_user_type_to_refresh_tokens.php
tokenVARCHAR(255)64-char hex refresh token
expires_atDATETIMEToken expiry timestamp
created_atDATETIMEDefaults to CURRENT_TIMESTAMP
rotated_atDATETIME NULLSet when the token is exchanged for its successor; NULL marks the session's current token (migration 20261001120000_add_rotation_columns_to_refresh_tokens.php:24-35)
replaced_byINT UNSIGNED NULLid of the successor row; followed (max 10 hops) to find the current token for a grace-window retry
family_idVARCHAR(32) NOT NULL, default '', indexed (idx_family_id)The session (one sign-in) the row belongs to: random at login and registration, inherited by every successor, and sent in the access token as sid. Logout, reuse revocation and the session cap act on a family, always scoped by user_id and user_type (#954; migration 20261021034252_add_family_id_to_refresh_tokens.php:32-35, existing rows backfilled one family per user). The '' default exists for the rolling deploy: a row an old pod writes during the rollout gets '', which can hold several sessions of that user and type: the first refresh gives each its own family, and logout, reuse revocation and the cap act on each '' session by its own chain or head row, never on all of them together (RefreshTokenModel.php:115-129,166-168,335-361). Its access tokens carry no sid (see the decision record's Deploy section)

A session is a chain of rows: superseded rows are kept until their own expires_at so reuse stays detectable, and RemoveExpiredRefreshTokens drops them afterwards. The migration also adds the prefix index idx_token (token(64)). See CF-10 Customer Auth for the rotation rules.

Configuration ​

Environment Variables (REST JWT) ​

VariableDefaultDescription
JWT_ACCESS_TOKEN_EXPIRY3600Access token lifetime in seconds (src/Rest/Auth/container.php:15)
JWT_REFRESH_TOKEN_EXPIRY604800Refresh token lifetime in seconds; every refresh issues a successor that lives this long from that moment (src/Rest/Auth/container.php:16)
REST_AUTH_MAX_SESSIONS_PER_USER10Live REST sessions (refresh-token families) one user may hold; a sign-in past the cap ends the least recently used one. Non-numeric falls back to 10, below 1 is raised to 1 (src/Rest/Auth/container.php:18, src/Rest/Auth/Config.php:42-50)
JWT_REFRESH_TOKEN_GRACE60Seconds during which a superseded refresh token is still honoured (it returns the session's current token). Clamped to 0..3600, non-numeric falls back to 60, 0 disables the grace (src/Rest/Auth/container.php:17, src/Rest/Auth/Config.php:28-36)

Environment Variables (SSO) ​

VariableDescription
APP_ADMIN_SSO_ENABLEDEnable/disable SSO (boolean)
APP_ADMIN_SSO_KEYCLOAK_SERVER_URLKeycloak base URL
APP_ADMIN_SSO_KEYCLOAK_REALMKeycloak realm name
APP_ADMIN_SSO_KEYCLOAK_CLIENT_IDOAuth2 client ID
APP_ADMIN_SSO_KEYCLOAK_CLIENT_SECRETOAuth2 client secret
APP_SAAS_SITE_IDSite identifier for group matching
APP_SAAS_ORG_IDOrganization identifier for group matching

Environment Variables (Static Auth) ​

VariableDescription
APP_ADMIN_USERNAMEConfig auth admin username
APP_ADMIN_PWDConfig auth admin password
APP_ADMIN_ADVISABLE_USERNAMEConfig auth advisable username
APP_ADMIN_ADVISABLE_PWDConfig auth advisable password

Environment Variables (REST Login Throttle) ​

VariableDefaultDescription
REST_AUTH_THROTTLE_ENABLEDtrueMaster switch. Set to false to disable throttling entirely (e.g., staging load tests).
REST_AUTH_THROTTLE_MAX_PER_USER5Max failed attempts per submitted username/email before a 429 is returned.
REST_AUTH_THROTTLE_MAX_PER_IP20Max failed attempts per client IP before a 429 is returned.
REST_AUTH_THROTTLE_WINDOW_SECONDS900Fixed window duration in seconds (default 15 minutes).

Config Files ​

FileContents
application/config/auth.phpAuth flags (simple_auth, db_auth), hash type, static users
application/config/constants.phpAUTH_ROLE_* and AUTH_PROVIDER_* constants
src/Rest/Auth/container.phpDI registration for REST auth (Tokens, Config, AdminAuth, CustomerAuth), API versioning (VersionResolver), and the full middleware pipeline (PolicyResolver, Authentication, Authorization, FeatureGuard, ResourceContext, RelationFilter, Audit). Also registers three LoginThrottle instances backed by cache.l2: the default instance (login throttle, #5), rest.auth.password_reset_throttle (forgot-password, #193, tighter per-email cap), and rest.auth.register_throttle (customer registration, #324, 3/email + 5/IP per hour).

Client Extension Points ​

  • Adv_auth ships ten empty extension hooks for client repos to override — user-lifecycle hooks (afterAdd, afterEdit, afterDelete, afterUndelete, afterChangePassword) and task-lifecycle hooks (afterAddTask, afterEditTask, afterTaskDelete, afterTaskCompleted, afterTaskUncompleted). Full hook table and override pattern: (see AD-58 Admin User Management for the complete client extension hook reference).
  • Client repos can add static config users via environment variables in .env.
  • The Adv_login controller extends Base_c (not Admin_c) so it can be overridden in application/controllers/ in client repos for custom login page behavior.

Business Rules ​

  • Provider priority: DB auth is checked first, then config auth. Both can be enabled simultaneously.
  • Soft-delete: soft_delete = 1 prevents login. Users are never hard-deleted.
  • SSO uid is null: SSO users have no local users table record. The uid session key is null.
  • Rate limiting is IP-based (session login): The block_access table tracks per-IP failed attempts. After 5 failures within 10 minutes, the IP is blocked. On successful login, the record is deleted. Block records auto-expire after 10 minutes.
  • REST login is separately throttled by LoginThrottle (src/Rest/Auth/LoginThrottle.php): two independent counters are maintained in L2 cache — per-identifier (submitted username, 5 failures / 15 min) and per-IP (20 failures / 15 min). On successful login, the per-identifier counter is cleared; the per-IP counter is deliberately never cleared so that one cracked account does not reset an attacker's IP budget (LoginThrottle.php:82-96). The identifier is counted whether or not the account exists, so a 429 response never confirms account existence (LoginThrottle.php:11-14). The throttle is fail-open: if the L2 cache is unavailable, logins proceed unthrottled and a warning is logged (LoginThrottle.php:61-64). The per-IP dimension depends on MY_Input::ip_address(), which currently trusts client-controlled forwarding headers — see Known Issues.
  • Refresh tokens rotate (#790, API 1.115): POST /rest/auth/admin/refresh returns a new refresh token every time and supersedes the presented one (src/Rest/Auth/RefreshTokenModel.php:215-232). Re-presenting a superseded token within JWT_REFRESH_TOKEN_GRACE returns the session's current token (:233-238); after the grace window it is treated as theft, that session's chain is deleted (deleteSession(), :239-241,335-361) and the answer is 401; the admin's other sessions are untouched (#954). A client must store the refresh_token of every refresh response.
  • No 2FA: The system does not implement two-factor authentication.
  • Role gating: most admin controllers call allowRole($roles, $sessionRoles) in their constructor and refuse with error_401(); return; (75 controllers; a few have no gate, see #557). The return leaves only __construct, so the refusal is what stops the request: error_401() records it (ecommercen/core/Adv_base_controller.php:170-198, isRequestRefused()), and the dispatcher (system/core/CodeIgniter.php:327) calls the requested method, or _remap(), through dispatch_controller_method() (system/core/Common.php:711-718), which skips a controller that has refused. The response is the 401 blockaccess page, and the post_controller / post_system hooks still run (#936). Non-ADVISABLE users cannot see/assign ADVISABLE or Developer roles.
  • Password change: Only ADVISABLE + ADMIN roles can change other users' passwords. Any logged-in user can change their own password via changeMyPassword().
  • Task management: See AD-55 Task Management for all task business rules, security gaps, and lifecycle details.
  • SSO caching: OIDC configuration and JWKs are cached via PSCache to avoid hitting Keycloak on every request. TTL matches the L2 cache default.
  • SSO session refresh: If the access token is expired but the refresh token is valid, validateSSOSession() transparently refreshes both tokens and updates session roles.

Live Browser Testing Findings ​

Login Page (/advisable/login.htm) ​

  • URL behavior: Root /advisable redirects with HTTP 307 to /advisable/login.htm.
  • Form fields: username (text input), pwd (password input), submit button labeled "Σύνδεση".
  • Visitor IP display: The login page displays the visitor's IP address on the page.
  • Session cookie: Standard PHPSESSID cookie (HttpOnly).

REST JWT Auth ​

  • Endpoint: POST /rest/auth/admin/login returns access_token and refresh_token at the root level of the JSON response (not nested under a data key).

SSO Configuration ​

  • SSO is enabled via Keycloak at auth.ecommercen.com, realm ecommercen.

Admin Panel Sidebar ​

After login, the admin panel sidebar contains 60+ menu items organized across 10 major sections:

SectionKey Items
DashboardHome, Quick Stats
CustomersCustomer list, Loyalty, Reviews
OrdersOrder list, Returns, Payments
ProductsCatalog, Categories, Brands, Variations, Bundles
SEORedirects, Sitemap, Meta tags
MarketingCampaigns, Coupons, Newsletters, Promotions
ContentPages, Blog, Sliders, Menus, Builder
ReportingSales, Traffic, Analytics
ECOMMERCEN PlusAI features, Marketplace, Integrations
CacheCache management, Rebuild
SettingsGeneral, Shipping, Payments, Taxes, Emails

Known Issues & Security Gaps ​

  1. REST throttle IP spoofable via forwarding headers (src/Rest/Auth/AdminAuth.php:70). $this->input->ip_address() resolves the client IP using MY_Input, which trusts X-Forwarded-For and similar headers supplied by the client. An attacker behind a single real IP can rotate spoofed forwarding-header values to bypass the per-IP throttle limit (LoginThrottle.php:51-54). The per-identifier counter is unaffected. Tracked as GitHub #322.