Skip to content

Customer Registration & Login ​

Flow ID: CF-10 | Module(s): eshop, Auth domain | Complexity: High | Last Updated: 2026-11-16 — 4.130.0 resync: duplicated registered accounts now merged by the one-off patcher (#1027), noted in Known Issues item 9; previous: 2026-11-04 — 4.129.0 resync: citations re-anchored; password hashing migration (#895: auth_hash_migrate_to, rehash on login) and AdvWrapLegacyPasswordHashes (#966) documented; registration accepts an email that exists only on guest orders (#894); email lookups resolve to the lowest id (#893); sid claim shown in the JWT example; '' family wording and rotation helper citations corrected; previous: 2026-10-21 — one REST session per device (#954, API 1.122): refresh-token families, per-session logout and reuse revocation, sid claim, POST /rest/customer/me/password keeps the caller's session, session cap; previous: 2026-10-13 — 4.127.0 resync: refresh-token rotation (#790, API 1.115) cited on current code (Tokens::rotateRefreshToken(), RefreshTokenModel::rotate(), Config grace), CustomerAuth/container.php/RefreshTokenModel line citations refreshed, rotation tests listed; previous: 2026-10-05 — #892: social login requires a provider-verified email, the requestEmail fallback is removed, and a disabled provider answers 404; previous: 2026-10-02 — 4.125.0 resync: CustomerAuth citations refreshed after logout() was added (:185-195), RefreshTokenModel::revoke() and updatePassword() test coverage noted; previous: 2026-09-14 — corrected application/models/Adv_mailer.php token-generation citation from line 65 (comment) to line 66 ($token = bin2hex(random_bytes(32));) in Code Flow, Token Format, and Business Rules

Business Overview ​

Customer authentication supports four paths: email/password login, registration, social OAuth (Google/Facebook), and guest checkout. The system uses JWT tokens (REST) alongside traditional sessions (legacy).

Key business behaviors:

  • Guest customers get DB record with random password + is_guest=1 — cannot log in later
  • Social auth creates/links accounts by email (auto-registers with random password if new) — only an email the provider vouches for (see Business Rules)
  • Password recovery via cryptographically random token-based email links (64-char hex, 60-minute TTL) — available via both legacy storefront and REST API
  • Customer passwords are legacy salted triple-SHA1 (or unsalted md5) unless auth_hash_migrate_to is set, in which case new passwords and re-hashed logins use password_hash() (#895; see Password Verification); bcrypt for admin
  • Login referrer validated against base_url() to prevent open redirects

API Reference ​

REST Endpoints ​

MethodPathAuthDescription
POST/rest/auth/customer/loginNoneLogin with email/password → returns JWT
POST/rest/auth/customer/refreshNone (the refresh token is the credential)New access token AND a rotated refresh token; the presented token is superseded (#790, API 1.115). 401 for an unknown, expired, other-type or reused token (src/Rest/Auth/CustomerAuth.php:138-162)
POST/rest/auth/customer/logoutNone (the refresh token is the credential)End the session the presented refresh token belongs to (every refresh token of its family, rotated ones included; the customer's sessions on other devices stay signed in); always 200 {message} (#790, #954)
POST/rest/auth/customer/registerNoneRegister new account → returns JWT; 429 + Retry-After when throttle hit (v1.11, #324); 409 on duplicate email (deliberately retained), but only when a registered (non-guest) account already uses the email; an email that exists only on guest orders can register (#894, src/Rest/Auth/CustomerAuth.php:236,287)
POST/rest/auth/customer/forgot-passwordNoneRequest password reset email
POST/rest/auth/customer/reset-passwordNoneConsume reset token + set new password
GET/rest/customer/meCustomer JWTGet own profile
POST/rest/customer/meCustomer JWTUpdate own profile
POST/rest/customer/me/passwordCustomer JWTChange password

Legacy Storefront ​

URLMethodPurpose
/customer/loginlogin()Email/password login
/signupregister()Registration form
/customer/logoutlogout()Clear session
/customer/recover_passwordrecover_password()Reset flow
/customer/googleLogingoogleLogin()OAuth2 Google — 404 unless SOCIAL_AUTH.GOOGLE_LOGIN_ENABLED
/customer/facebookLoginfacebookLogin()OAuth2 Facebook — 404 unless SOCIAL_AUTH.FACEBOOK_LOGIN_ENABLED

JWT Token Structure ​

json
{
  "iss": "base_url()",
  "aud": "base_url()",
  "iat": 1234567890,
  "nbf": 1234567890,
  "exp": 1234567890,
  "data": {
    "userId": "123",
    "type": "customer",
    "sid": "<family id, 32 hex>"
  }
}

Built by Tokens::generateAccessToken() (src/Rest/Auth/Tokens.php:18-45). data.sid is present when the session family is non-empty (:25-27). An admin token also carries data.roles (:29-31); a customer token does not.

Token expiry configurable via JWT_ACCESS_TOKEN_EXPIRY (default 3600s) and JWT_REFRESH_TOKEN_EXPIRY (default 604800s) (src/Rest/Auth/container.php:15-16). The refresh lifetime slides: every refresh issues a new refresh token that lives JWT_REFRESH_TOKEN_EXPIRY from that moment (see Code Flow — REST Refresh). JWT_REFRESH_TOKEN_GRACE is the rotation grace window in seconds: default 60, clamped to 0..3600 by Config::normaliseGrace() (a non-numeric value falls back to 60; 0 turns the grace off, so any superseded token is reuse) — src/Rest/Auth/Config.php:7-8,28-36, read at src/Rest/Auth/container.php:17, passed to Config at :65-72. The session cap REST_AUTH_MAX_SESSIONS_PER_USER is read at container.php:18 and normalised by Config::normaliseMaxSessions() (src/Rest/Auth/Config.php:42-50).


Code Flow — REST Password Reset ​

Two new anonymous REST endpoints added in commit 747fd2989 handle the full reset cycle.

Request reset (POST /rest/auth/customer/forgot-password) ​

src/Rest/Auth/CustomerAuth.php:352-378

POST /rest/auth/customer/forgot-password
  └─ CustomerAuth::forgotPassword()               [src/Rest/Auth/CustomerAuth.php:352]
       └─ PasswordResetService::requestReset($email)
               [src/Domains/Customer/Customer/PasswordResetService.php:22]
            |-- empty email        → 422 {errors: {email: "Email is required."}}
            |-- invalid format     → 422 {errors: {email: "Email is invalid."}}
            |-- getCustomerBy([mail, has_access=1, is_guest=0]) → null
            |                      → silent return (no error, no email)
            └─ Adv_mailer::recover_password_mail($email)
                 |-- bin2hex(random_bytes(32)) → writes active_token
                 |    + active_token_expires_at = now + 3600s
                 |    to shop_customer                [application/models/Adv_mailer.php:69]
                 └─ sends email (template: resetPassword,
                      registry keys: EMAIL_SHOP_MAILER / PASSWORD_RESET)
  Success → 200 {"message": "If an account exists for this email, a reset link has been sent."}
  (same body returned for both known and unknown email — see #193)

The getCustomerBy() pre-check at src/Domains/Customer/Customer/PasswordResetService.php:36-43 enforces has_access=1 and is_guest=0 before delegating to the mailer, preventing a fatal null-dereference inside recover_password_mail(). Unknown addresses return silently so the response cannot be used to confirm account existence.

Consume reset token (POST /rest/auth/customer/reset-password) ​

Body accepts newPassword (camelCase) or new_password (snake_case): src/Rest/Auth/CustomerAuth.php:421-433

POST /rest/auth/customer/reset-password
  └─ CustomerAuth::resetPassword()                [src/Rest/Auth/CustomerAuth.php:421]
       └─ PasswordResetService::consumeToken($token, $newPassword)
               [src/Domains/Customer/Customer/PasswordResetService.php:48]
            |-- empty token        → 422 {errors: {token: "Token is required."}}
            |-- empty password     → 422 {errors: {newPassword: "New password is required."}}
            |-- password < 6 chars → 422 {errors: {newPassword: "New password must be at least 6 characters."}}
            |-- isValidToken($token) == false
            |                      → 422 {errors: {token: "Invalid token."}}
            └─ customer_model::resetPassword($token, $newPassword)
                 |-- SELECT the customer WHERE active_token=$token
                 |     AND active_token_expires_at > now()   → none: return false
                 |-- revokeRestSessions(<that customer>)     (#790)
                 |     DELETE FROM refresh_tokens
                 |       WHERE user_id = <that customer> AND user_type = 'customer'
                 |     DB error → RuntimeException: nothing else runs, the password and
                 |       the token are unchanged → 500 {"message": "Internal server error."}
                 |       (SafeActionDispatch); the customer can retry with the same link
                 |-- encrypt via generateEncryptedValues() (triple-SHA1 with a new
                 |     salt, or the auth_hash_migrate_to scheme; Adv_customer_model.php:563-573)
                 └─ UPDATE shop_customer
                      SET password=..., salt=..., active_token=NULL,
                          active_token_expires_at=NULL
                      WHERE active_token=$token
                        AND active_token_expires_at > now()
                      DB error → RuntimeException → 500 (as above; the token is unchanged)
                      0 rows (token consumed after the check) → false
                        → consumeToken() → 422 {errors: {token: "Invalid token."}}
  Success → 200 {"message": "Password updated."}

consumeToken() no longer discards resetPassword()'s result: a reset that wrote nothing gets the same 422 as an invalid token, never "Password updated.". The storefront reset form answers that case the way set_new_password() answers an invalid link — user.msg.nsl.address.not.valid and a redirect home — instead of silently re-rendering the form.

The revocation lives in Adv_customer_model::resetPassword() / revokeRestSessions(), so the legacy storefront reset form ends the customer's REST sessions too. Revocation runs BEFORE the password write, so a failed revocation leaves the old password rather than a new password beside live sessions; the storefront reset form then shows its generic customer.password.recover.alert.error message and the form again. The storefront change-password form (Adv_customer::update_my_password()) revokes before its write as well, with the same message on failure, so a password changed on the website ends the customer's app sessions. POST /rest/customer/me/password ends every OTHER session of the customer and keeps the caller's, identified by the sid claim of its access token (#954; see docs/decisions/954-per-device-sessions.md). It revokes and writes in one database transaction (src/Rest/Customer/Controllers/Customer.php:345-364), so a failure of either rolls both back and answers 500 with nothing changed; an access token without sid ends every session.

Code Flow — REST Refresh (rotation, #790) ​

POST /rest/auth/customer/refresh   {refresh_token}        (admin: /rest/auth/admin/refresh, same flow, roles added to the access JWT)
  └─ CustomerAuth::refresh()                       [src/Rest/Auth/CustomerAuth.php:138-162]
       └─ Tokens::rotateRefreshToken($token, REST_FRONTEND_USER)   [src/Rest/Auth/Tokens.php:74-88; passes a fresh 64-hex token, now + JWT_REFRESH_TOKEN_EXPIRY, and the grace]
            └─ RefreshTokenModel::rotate()                 one transaction, SELECT ... FOR UPDATE on the presented row
                 |-- unknown / expired / other user type          → null → 401 (nothing changes)
                 |-- current (rotated_at NULL)                    → INSERT successor (expires_at = now + refresh lifetime),
                 |                                                  UPDATE presented SET rotated_at = now, replaced_by = successor
                 |-- rotated, within the grace window             → return the CURRENT token of the chain; rotate nothing
                 └-- rotated, after the grace window (reuse)      → DELETE that session (its chain) → 401
  200 {access_token, refresh_token}

A customer can hold several sessions, one per sign-in (#954): generateRefreshToken() on login and registration mints a random family_id and deletes nothing, and each session is stored as a chain of rows in its family. The superseded rows keep rotated_at / replaced_by until their own expires_at, so reuse of a stolen token stays detectable for as long as it would have been valid. A rotation's successor inherits the family, and the family id travels in the access token as the sid claim. During a rolling deploy an old pod can still write rows with family '': the first refresh on an updated server gives such a session its own family, and deleteSession() (src/Rest/Auth/RefreshTokenModel.php:335) ends a session by following replaced_by (at most 10 links), so logout and reuse leave the user's other '' sessions alone. The row lock serialises two requests holding the same token: the second finds it rotated and, inside the grace window, receives the first one's token, so both clients converge on one session. Logout ends the presented token's session through deleteSession() (each real family met on its chain is deleted whole, each '' row by id), whether the token presented is current or superseded; the customer's other sessions are untouched.

Rotation rules, all in RefreshTokenModel (src/Rest/Auth/RefreshTokenModel.php):

  • rotate() (:176) retries once when rotateOnce() (:197) fails with a deadlock (1213) or a lock wait timeout (1205); any other error propagates and becomes a 500 through SafeActionDispatch.
  • The presented row is read with SELECT ... FOR UPDATE, filtered on user_type, and accepted only when the stored token equals the presented one byte for byte (lockByToken() :282, sameToken() :298), because the column's collation compares case-insensitively.
  • A token whose expires_at has passed is refused (null) before its rotated_at is looked at, so an expired superseded token never ends the session.
  • The grace test is withinGrace() (:271): 0 disables it, the window is half-open (elapsed < grace), and a rotated_at in the future (clock skew) counts as inside the window only when the skew is smaller than the grace.
  • Inside the grace window the caller receives the head of the chain, found by following replaced_by for at most 10 hops (currentHead() :307); a broken or expired chain yields null, so a 401.
  • Tokens::generateRefreshToken() (login, register) no longer deletes the customer's other rows: it saves the first token of a new family, then RefreshTokenModel::evictLeastRecentlyUsedFamilies() trims the customer to REST_AUTH_MAX_SESSIONS_PER_USER live sessions (default 10, minimum 1), deleting the whole family of the least recently used ones. A family's last activity is the created_at of its live head, because every rotation creates a new head. Reuse after the grace window deletes only the replayed session (its chain, through deleteSession(), src/Rest/Auth/RefreshTokenModel.php:239-241,335-361).
  • RemoveExpiredRefreshTokens deletes rows by their own expires_at (src/Rest/Auth/RemoveExpiredRefreshTokens.php:18), so superseded rows live as long as the token would have.
  • Schema: migration database/migrations/20261001120000_add_rotation_columns_to_refresh_tokens.php adds rotated_at DATETIME NULL, replaced_by INT UNSIGNED NULL and a prefix index idx_token (token(64)) (:24-35); a NULL rotated_at marks the current token, so rows that existed at deploy stay valid. The column list of refresh_tokens is documented in AD-01. Migration database/migrations/20261021034252_add_family_id_to_refresh_tokens.php (#954) adds family_id VARCHAR(32) NOT NULL DEFAULT '' with idx_family_id and backfills one family per (user_type, user_id) (:32-35), so every session that existed at deploy continues. The '' default is for the rolling deploy: a row that 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), and its access tokens carry no sid. Every query on a family is also scoped by user_id and user_type, so '' never joins two users' rows (rollout residue: docs/decisions/954-per-device-sessions.md, Deploy).

Code Flow — REST Logout ​

POST /rest/auth/customer/logout   {refresh_token}
  └─ CustomerAuth::logout()                         [src/Rest/Auth/CustomerAuth.php:195-205; OpenAPI block :164-194]
       |-- token missing / not a non-empty string → nothing deleted
       └─ RefreshTokenModel::revoke($token, 'customer')      [src/Rest/Auth/RefreshTokenModel.php:61-70]
            |-- find the row by token; none, or another user type → nothing deleted
            └─ deleteSession(): DELETE the presented row's chain, scoped to its user and
                  type: each real family on the chain whole, each '' row by id (:335-361)
               (this device's session, rotated tokens included; a real DB error throws → 500)
  Always → 200 {"message": "Logged out."}

Authorised by possession of the refresh token (policy auth: none, as refresh): the refresh token can already mint access tokens, so requiring an access token as well adds no protection and would stop a client from signing out once its access token expired. Unthrottled for the same reason /refresh is — the token is 256 bits of randomness, and the response is identical whether or not it matched. POST /rest/auth/admin/logout is the same with user_type = 'backend'. An access token already issued stays valid until it expires (JWTs are stateless).

A customer holds one REST session per signed-in device (#954), so a logout ends that device's session only, and signing in on another device no longer signs this one out. An access token already issued stays valid until it expires.

Cheap validation (empty, length) runs before any DB call — src/Domains/Customer/Customer/PasswordResetService.php:50-60. isValidToken() is called only after all local checks pass.

Token format ​

The token written to shop_customer.active_token is bin2hex(random_bytes(32)) (application/models/Adv_mailer.php:69) — a 64-character hex string (256 bits of entropy), shared by both the REST and legacy recover_password() storefront flows. It is single-use: resetPassword() (ecommercen/eshop/models/Adv_customer_model.php:207) sets both active_token = NULL and active_token_expires_at = NULL on success (:226-227). The TTL is 60 minutes, enforced by active_token_expires_at written by set_forgot_password_token() (ecommercen/eshop/models/Adv_customer_model.php:155) using PASSWORD_RESET_TOKEN_TTL = 3600 (ecommercen/eshop/models/Adv_customer_model.php:8). Expiry is checked in both isValidToken() (ecommercen/eshop/models/Adv_customer_model.php:171) and in the resetPassword() UPDATE WHERE clause, so a stale token cannot reset a password even if the pre-check is bypassed.

Routes are registered with a (\w{2})/ locale-prefix variant in application/config/rest_routes.php. The CustomerAuth controller policy defaults to 'auth' => 'none' in application/config/rest_policies.php, so both new endpoints are publicly accessible without change.


Domain Layer ​

FileResponsibility
src/Domains/Customer/Customer/PasswordResetService.phpWraps legacy Adv_customer_model + Adv_mailer for the password-reset request flow — shared by the REST endpoint and, since #323, the legacy storefront recover-password form. requestReset() validates email + active-account status, silently skips unknown addresses, then delegates to the legacy mailer. consumeToken() validates token + password then delegates to the legacy model. Constructor is side-effect-free — legacy CI models load lazily via private accessors.
src/Rest/Auth/CustomerAuth.phpREST auth controller. forgotPassword() + resetPassword() delegate entirely to PasswordResetService. logout() (src/Rest/Auth/CustomerAuth.php:195) revokes the presented refresh token via RefreshTokenModel::revoke() and always answers 200 (see Code Flow — REST Logout). login(), refresh(), register() covered in this doc.

Business Rules ​

RuleDescription
Guests cannot log incheckCustomer() requires is_guest = 0
Guests cannot recover passwordhas_access = 1 and is_guest = 0 required — enforced by PasswordResetService::requestReset() (src/Domains/Customer/Customer/PasswordResetService.php:36-43) and by the legacy storefront
Emails always lowercasedmb_strtolower() before every DB operation
OAuth creates if not existsmapOAuthEmailToCustomer() auto-registers
OAuth email must be vouched forAdv_customer::verifiedSocialLoginEmail(): Google only when the email_verified claim is JSON true; Facebook's email is accepted as returned (the Graph API asserts no verification flag); any other provider is refused. No email, an unverified one, or a failed token exchange redirects to /customer/login with customer.login.social.error — nothing is looked up, created or logged in
Disabled providergoogleLogin() / facebookLogin() answer 404 while their SOCIAL_AUTH.*_LOGIN_ENABLED flag is off, before any session write or provider redirect
Guest email can register (#894)register() calls customerEmailExist() (src/Rest/Auth/CustomerAuth.php:287), which ignores is_guest = 1 rows (ecommercen/eshop/models/Adv_customer_model.php:843-853); an email that exists only on guest orders registers as a second shop_customer row, and 409 is for a registered account only
Email lookups take the lowest id (#893)getCustomerBy() orders by id ASC and takes one row (ecommercen/eshop/models/Adv_customer_model.php:53-57); getRegisteredCustomerIdByEmail() uses it (:1129-1134)
CSRF on OAuthoauth2state session token validated on callback
Password reset token = 64 charsbin2hex(random_bytes(32)) (application/models/Adv_mailer.php:69) — single-use, 60-minute TTL via active_token_expires_at; consumed by setting both active_token = NULL and active_token_expires_at = NULL
Password minimum (REST reset)6 characters — enforced at src/Domains/Customer/Customer/PasswordResetService.php:58-60
Refresh rotates (#790, API 1.115)Every /refresh returns a new refresh token valid for JWT_REFRESH_TOKEN_EXPIRY from that moment; the client must store it and send it on the next refresh and on logout (src/Rest/Auth/RefreshTokenModel.php:215-232)
Grace windowA superseded token presented again within JWT_REFRESH_TOKEN_GRACE seconds (default 60, clamped 0..3600, 0 = off) gets a fresh access token and the session's CURRENT refresh token, never a second branch (src/Rest/Auth/RefreshTokenModel.php:233-238,271-279, src/Rest/Auth/Config.php:28-36)
Reuse ends the sessionA superseded token presented after the grace window deletes the refresh tokens of its session (its chain) and answers 401; the legitimate holder of that session must sign in again. The customer's other sessions are untouched (#954)
One session per device (#954, API 1.122)A sign-in starts a new family (refresh_tokens.family_id) and ends nothing. Past REST_AUTH_MAX_SESSIONS_PER_USER live sessions the least recently used family ends. Reset, the storefront password change and account erasure still end every session
REST password change keeps the caller's sessionPOST /rest/customer/me/password deletes every family except the one in the access token's sid claim, in the same transaction as the password write (a failure of either answers 500 and changes nothing: the old password and every session stay). An access token without sid (issued before #954) ends every session, the caller's included

Security & Rate Limiting ​

Legacy Admin Login Protection ​

The Blocking library enforces rate limiting on the legacy admin login path:

  • 5 login attempts per 10-minute window, IP-based
  • Failed attempts tracked in the block_access database table
  • After threshold, the IP is blocked for the remainder of the window

REST API Authentication Throttle ​

Since API v1.9 (#5), the REST JWT login endpoints (/rest/auth/admin/login, /rest/auth/customer/login) are brute-force throttled server-side via Advisable\Rest\Auth\LoginThrottle — per submitted identifier (default 5 / 15 min, cleared on success) and per client IP (default 20 / 15 min, never cleared), returning 429 + Retry-After. The same response is returned for both counters and identifiers are counted whether or not the account exists, so a lockout never confirms account existence. Counters live in the shared L2 cache (limits hold across pods); the throttle fails open with a logged warning if the cache backend is down. See Known Issues & Security Gaps item 5 for the per-IP forwarding-header caveat (#322), and item 4 for the separate forgot-password throttle (#193).

Since API v1.11 (#324), POST /rest/auth/customer/register is also brute-force throttled via a third LoginThrottle instance — DI name rest.auth.register_throttle, realm customer-register (src/Rest/Auth/container.php:94-100,105-108; src/Rest/Auth/CustomerAuth.php:22,33 — THROTTLE_REALM_REGISTER and the $registerThrottle constructor parameter). Defaults: 3 per email + 5 per IP per hour (env vars REST_AUTH_REGISTER_THROTTLE_MAX_PER_EMAIL=3, REST_AUTH_REGISTER_THROTTLE_MAX_PER_IP=5, REST_AUTH_REGISTER_THROTTLE_WINDOW_SECONDS=3600, REST_AUTH_REGISTER_THROTTLE_ENABLED=true — src/Rest/Auth/container.php:29-32). The per-IP cap is deliberately tighter than login's (5 vs 20) because legitimate signups from a single IP are rare (src/Rest/Auth/container.php:90-93). The throttle gate runs after cheap 400 validation so malformed requests never consume quota; recordFailure() is called on every well-formed request — a 409 and a 201 cost the same counter slot, and the counter is never cleared (src/Rest/Auth/CustomerAuth.php:250-263,277-283). Counting happens before the duplicate-email check: counting only unregistered addresses would itself be a free existence oracle; the trade-off is that a not-yet-registered email's per-email quota can be griefed for one window, bounded by the per-IP cap (src/Rest/Auth/CustomerAuth.php:265-283, the duplicate check follows at :287). The 409 "Email already registered." response is deliberately retained — generic-response was declined to avoid breaking the registration UX for real users (src/Rest/Auth/CustomerAuth.php:287-290). Counters in the shared L2 cache; fail-open with a logged warning if the cache is down (src/Rest/Auth/LoginThrottle.php:61-64,150-158). The #322 forwarding-header caveat (noted under login's throttle) applies to the per-IP layer here too; the per-email counter is unaffected.

JWT Token Role Handling ​

  • Refresh tokens are opaque; the role claim lives in the access token. The access token minted by AdminAuth::refresh() carries roles re-resolved at each refresh by getUserRoles() (config-based static users first, otherwise the database; src/Rest/Auth/AdminAuth.php:133-159,203-216), so a role change reaches the admin on the next refresh
  • The access token minted by CustomerAuth::refresh() carries no roles -- customer authorization is determined by the REST_FRONTEND_USER type only (src/Rest/Auth/CustomerAuth.php:138-162)

Password Verification ​

  • Admin auth uses password_verify() supporting bcrypt and argon2i hashes (see AD-01).
  • Customer passwords are checked by Adv_customer_model::checkPassword() (ecommercen/eshop/models/Adv_customer_model.php:576-604): a password_hash() hash or a wrapped legacy hash ($wrap1$…) goes to Advauth::advAuthVerify(); otherwise salted triple-SHA1 or unsalted md5. With $config['auth_hash_migrate_to'] set (application/config/auth.php:22, default null), new passwords are written in that scheme (generateEncryptedValues(), :563-568) and a successful login re-hashes an older hash (upgradePasswordHash(), called at :423, defined :440-465; #895). A failed upgrade write is logged and does not change the login result; the upgrade is skipped with an error log if generateEncryptedValues() does not produce the target scheme (:448-455). AdvWrapLegacyPasswordHashes (ecommercen/job/libraries/AdvWrapLegacyPasswordHashes.php, #966) wraps stored legacy hashes in place (see SY-09).
  • Config-based static users (from config_auth configuration) are checked before database users (admin only) -- allows emergency/backdoor access when DB is unavailable

Known Issues & Security Gaps ​

  1. Email enumeration on forgot-password (#193 + #323, fixed) — POST /rest/auth/customer/forgot-password returns 200 with the same generic message whether or not an account exists (API v1.10); 422 remains only for a missing/malformed email. The legacy storefront recover-password form was hardened the same way in #323: the callback_recoverPasswordEmailValidation existence-check rule (which showed a visible "email not found" error for unknown addresses) was removed, and Adv_customer::recoverPasswordPost() now routes through PasswordResetService::requestReset() — so both storefront themes render the existing neutral confirmation (customer.password.recover.alert.success) whether or not the email exists. Residual (both surfaces): a timing side-channel remains (known emails trigger a DB write + SMTP send), mitigated on the REST path by the request throttle below (item 4); the storefront form is still unthrottled (see item 4).

  2. Weak reset-token entropy (#193, fixed) — Tokens are now bin2hex(random_bytes(32)) (64 hex chars, 256 bits) generated in Adv_mailer::recover_password_mail(), replacing sha1(time() . $customer->id). Both the REST and legacy storefront flows share this generation path.

  3. No token TTL (#193, fixed) — shop_customer.active_token_expires_at (new migration) is set to +60 min on issue (Adv_customer_model::PASSWORD_RESET_TOKEN_TTL) and enforced in both isValidToken() and resetPassword() (the consuming UPDATE re-checks expiry, so a stale token cannot reset a password even if a caller skips the pre-check). Tokens with a NULL expiry — i.e. every token issued before the migration — are treated as expired, deliberately invalidating the weak legacy tokens at deploy. Both REST and the legacy storefront flow enforce this (shared model methods).

  4. No rate limiting on forgot-password (#193, fixed) — POST /rest/auth/customer/forgot-password is throttled via a second LoginThrottle instance (realm forgot-password): 3 requests per email and 10 per IP per hour by default (REST_AUTH_RESET_THROTTLE_* env vars), counting every request (each accepted one can send an email), never cleared, 429 + Retry-After when exceeded. The legacy storefront recover-password form is not throttled server-side — #323 closed its enumeration disclosure (item 1) but deliberately left throttling as a follow-up (it also depends on the ip_address() trust fix #322 for a per-IP layer). The #322 forwarding-header caveat applies to the REST per-IP layer.

  5. Rate limiting on REST JWT login (#5, fixed) — POST /rest/auth/customer/login (and the admin counterpart) are brute-force throttled since API v1.9: failed attempts are counted per submitted identifier (default 5/15 min, cleared on successful login) and per client IP (default 20/15 min) via Advisable\Rest\Auth\LoginThrottle (counters in the shared L2 cache), returning 429 + Retry-After when exceeded — the same response for both counters, so a lockout never confirms account existence. Configurable via REST_AUTH_THROTTLE_* env vars; fail-open with a logged warning if the cache backend is down. Caveat: the per-IP layer relies on MY_Input::ip_address(), which currently trusts client-controlled forwarding headers (GitHub #322) — until that is fixed, the per-identifier counter is the effective control. /refresh remains deliberately unthrottled — refresh tokens are high-entropy random values, so online brute-force is impractical. forgot-password throttling landed with #193 (see item 4). register throttle landed in commit 7b0ae98f96 (v1.11, #324 — see item 6); the 409 duplicate-email response is deliberately retained and the enumeration vector is mitigated by throttle (not closed); the #322 per-IP caveat applies to the register throttle's IP layer as well.

  6. Register endpoint enumeration + no throttle (#324, fixed in v1.11) — POST /rest/auth/customer/register is brute-force throttled since commit 7b0ae98f96 (API v1.11): 3 per email + 5 per IP per hour via a third LoginThrottle instance (rest.auth.register_throttle, realm customer-register; src/Rest/Auth/container.php:94-100,105-108). The 409 "Email already registered." response is deliberately retained — generic-response was declined to avoid breaking registration UX for real users (src/Rest/Auth/CustomerAuth.php:287-290). The throttle mitigates the 409 enumeration vector but does not close it: a caller within quota can still observe 409 vs 201 to probe email existence. The per-IP layer is subject to the #322 forwarding-header caveat; the per-email counter is unaffected.

  7. Bare empty 200 on an uncaught REST error (#462, fixed) — A \Throwable escaping a REST action's success path (e.g. inside Tokens::generateAccessToken()/generateRefreshToken() during CustomerAuth::login()) previously left CI3's default empty 200 (Content-Type: text/html, 0 bytes): RouterDispatcher::dispatch() caught only \Exception — so PHP Errors escaped entirely — and even when it caught it merely logged and returned without writing a response. Every action is now wrapped by Advisable\Rest\Support\SafeActionDispatch::invokeControllerAction() (src/Rest/Support/SafeActionDispatch.php:45-64), which catches \Throwable and emits a well-formed 500 {"message":"Internal server error."} via sendError(); RouterDispatcher dispatches through it (application/controllers/RouterDispatcher.php:126) and widened its DI-resolution and middleware catches to \Throwable (:73, :117). CI3 buffers output and flushes only after dispatch() returns, so the rewritten status + body reaches the client. The 401 and 429 paths are unchanged; true uncatchable fatals (OOM / time-limit) remain out of scope and are still handled by the existing _shutdown_handler.

  8. Phantom 200 carrying an unpersisted refresh token (#498, fixed) — Under CI3 db_debug=false (the production default) a failing refresh_tokens write returned false with no throw, so Tokens::generateRefreshToken() handed back a token that was never persisted and login / token-refresh / register replied a normal 200 carrying it — a later /refresh with that token then failed. RefreshTokenModel::save(), deleteSession(), revokeFamiliesExcept() and evictLeastRecentlyUsedFamilies() inspect the driver-level error after the write via a private assertNoDbError() and throw \RuntimeException on a real DB error; a zero-row DELETE is deliberately not treated as an error (src/Rest/Auth/RefreshTokenModel.php:20-40,79-88,105-144,335-361,378-387; revoke() :61-70 goes through deleteSession()). deleteBy() (:363-366) does not check for errors. The throw is caught by item 7's SafeActionDispatch, so these endpoints now surface a 500 instead of the phantom 200. Error-path only — the success contract ({access_token, refresh_token} on a healthy write) is unchanged.

  9. Correct credentials rejected on duplicated non-guest rows + NULL-hash deprecation (#463, fixed) — Adv_customer_model::checkCustomer() previously authenticated against an arbitrary first ->row() for an email, so an email owning more than one non-guest row could have valid credentials rejected. It now orders non-guest rows by id ASC and authenticates against whichever duplicate row actually owns the supplied password (ecommercen/eshop/models/Adv_customer_model.php:394-429); the return contract (customer id on success, 0 on failure) is unchanged and a valid password is still required, so there is no auth bypass. checkPassword() additionally rejects a NULL/empty stored hash before hashing and casts salt/password to string (casts :578-579 and :590, NULL/empty-hash guard :587-589), removing a PHP 8.1 null-to-string deprecation that a strict error handler could escalate to a fatal. Root-cause confirmation for the originally-stranded account needs production DB access and remains open — see the REST Customer Login Recovery guide below. #1027 (fixed): the duplicated non-guest rows themselves are now removed by the one-off patcher patches/MergeDuplicateRegisteredCustomers.php (shim migration database/migrations/20261109120000_merge_duplicate_registered_customers.php:5-7), which runs on php migrator.php migrate. It groups is_guest = 0 rows by LOWER(TRIM(mail)) (patches/MergeDuplicateRegisteredCustomers.php:161-170); the survivor is the most recently active account (newest order, then highest date_registered, then highest id) and keeps its own password and salt; the other rows are demoted to is_guest = 1 (:306-313) and their customer refresh_tokens are deleted (:282-288). The checkCustomer() tolerance above (#463) stays as the fallback for forks that have not run the patcher. Limits: only groups sharing an e-mail after LOWER(TRIM()) merge, and demoted rows keep their name, addresses and password hash, so they remain personal data until an erasure runs (#893). The merge is irreversible. See docs/decisions/1027-merge-duplicate-registered-customers.md.

  10. Refresh tokens are plaintext at rest (#790, partly fixed) — POST /rest/auth/customer/logout and /rest/auth/admin/logout revoke the session, a password reset or a storefront password change revokes all of the customer's refresh tokens, and /refresh now rotates the refresh token with reuse detection (see Code Flow — REST Refresh). Still open: refresh_tokens.token is stored in plaintext (it now has a prefix index, idx_token), and the grace window returns the session's current token, which a hashed store could not do without keeping a sealed copy. Hashing needs a migration that invalidates every live session. Multi-device sessions are done (#954, see Code Flow — REST Refresh). Tracked as follow-ups on #790.

  11. Social-login fallback signed in as a typed email (#892, fixed) — Adv_customer::requestEmail() took a typed email and logged the visitor into that customer, gated only by the login_referrer session flag that starting any social login sets. The action, its customerRequestEmail layout (both themes) and its customer.login.requestEmail copy are removed; oAuth2Login() now refuses instead of falling back to it, and requires a provider-verified email (see Business Rules). login_referrer is now only a post-login redirect target. Still open: shop_customer.mail is not unique, so a social login on a duplicated email signs into one of several rows. Since #893 that row is deterministic: getCustomerBy() orders by id ASC and takes one row (ecommercen/eshop/models/Adv_customer_model.php:53-57), so every email lookup resolves to the lowest id.


Client Extension Points ​

TypeDetails
Customer controllerOverride in application/modules/eshop/controllers/
Customer modelOverride password hashing, session data
Auth libraryAdvauth — configurable hash strategy (md5, sha1, bcrypt, argon2i)
Social authRegistry: SOCIAL_AUTH.GOOGLE_CLIENT_ID/SECRET, FACEBOOK_CLIENT_ID/SECRET, GOOGLE_LOGIN_ENABLED, FACEBOOK_LOGIN_ENABLED. A fork adding a provider must state its verification rule by overriding Adv_customer::verifiedSocialLoginEmail() — an unknown resource owner is refused

Tests ​

FileTestsWhat is covered
tests/Legacy/Eshop/AdvCustomerSocialLoginTest.php20#892: requestEmail unreachable (abandoned social login, signed-in customer); Google refused unless email_verified is JSON true (false, absent, null, string, int); verified Google logs into the matching customer or creates one; Facebook with an email logs in, without one is refused; unknown provider and failed token exchange refused; disabled provider 404s before any session write, on entry and on callback
tests/Unit/Domains/Customer/Customer/PasswordResetServiceTest.php11requestReset: empty email, invalid email format, unknown email, known email sends mail. consumeToken: missing token, invalid token, missing password, short password, happy path; a token consumed after the check is reported as invalid (testConsumeTokenReportsATokenConsumedAfterTheCheckAsInvalid, :142); a failed session revocation propagates (testConsumeTokenLetsAFailedSessionRevocationPropagate, :158)
tests/Integration/Domains/Customer/Customer/PasswordResetServiceIntegrationTest.php6Real-DB round-trip: new password persists and authenticates after consumeToken, old password rejected, token column cleared; an invalid token is rejected; requestReset with an unknown email is silent; isValidToken() true for a future expiry, false for a past or NULL expiry
tests/Integration/Rest/Auth/LoginThrottleContainerTest.php7 (lines 65-161)Container regression guards for #324: register_throttle_is_registered_in_container, register_throttle_resolves_as_login_throttle, customer_auth_is_wired_to_all_three_throttles; the login and password-reset throttles have the same registered/resolves pair
tests/Unit/Rest/Auth/CustomerAuthLogoutTest.php7Customer + admin logout against an in-memory token store: deletes only the presented session (family), the same customer's other device keeps refreshing (#954), a logged-out token is refused by refresh(), repeat / unknown / malformed / missing tokens all answer the same 200 and delete nothing, a customer logout cannot revoke an admin token (#790)
tests/Legacy/Rest/Auth/RefreshTokenModelRevokeTest.php7RefreshTokenModel::revoke() deletes the family of the presented token, scoped to the user type; an unknown token deletes nothing; a real DB error throws (#790). revokeFamiliesExcept() keeps the caller's family, deletes everything without one, and throws on a real DB error (#954)
tests/Integration/Legacy/Rest/Auth/RefreshTokenRotationTest.php36Per-device sessions (#954): two logins are two sessions that each refresh, the successor inherits the family, reuse and logout end one session only, a reset ends all, revokeFamiliesExcept() keeps the caller's session, the cap evicts the least recently used family (rotation counts as activity, superseded rows go too, per user and type, expired sessions not counted, the rollout family '' counts once however many heads it has). Rotation against the test database: new token, sliding expiry, grace-window retry and concurrent twin converge on one token, chain following, reuse after the grace window ends the session, logout after rotation, grace 0, the half-open boundary and rotated_at clock skew, expired / unknown / other-type tokens, byte-for-byte token match, admin, a new login leaving the existing session alive, a password change or reset revoking the rotated rows (#790)
tests/Integration/Legacy/Rest/Auth/RefreshTokenRotationConcurrencyTest.php1A second process holds the row lock; the rotation waits, then takes the grace path and exactly one successor exists (#790)
tests/Legacy/Rest/Auth/RefreshTokenModelRotateRetryTest.php4A deadlock (1213) or lock wait timeout (1205) is retried once, a second failure or any other error is not (#790)
tests/Unit/Rest/Auth/ConfigTest.php12JWT_REFRESH_TOKEN_GRACE is clamped to 0..3600, non-numeric falls back to 60 (#790)
tests/Unit/Rest/Auth/CustomerAuthRefreshTest.php4refresh() returns {access_token, refresh_token}, issues the access token for the rotated family (sid), 401 on a refused token, 400 without one (#790, #954)
tests/Unit/Rest/Support/Resources/ResourceContextTest.php19Scope flags and fromTokenData(); since #954 the sid claim becomes getSessionId() for a customer and a backend token, and an absent, empty or non-string sid gives null
tests/Unit/Rest/Auth/TokensTest.php17generateAccessToken() (with and without the sid claim, and its round trip through validateToken() into ResourceContext::getSessionId()), generateRefreshToken() (a new family per call, no deletion, the session cap passed to the model), validateToken(), Config::normaliseMaxSessions(), and rotateRefreshToken() (passes a fresh token, the sliding expiry and the grace to the model; returns the family; null when the model refuses) (#790, #954)
tests/Unit/Rest/Customer/Controllers/CustomerChangePasswordSessionsTest.php7POST /rest/customer/me/password revokes every session except the caller's sid and writes the password in one transaction, ends all without a sid, rolls back when the revocation fails, when the write fails or when it updates no row, and revokes nothing on a wrong password or a rejected request (#954)
tests/Legacy/Eshop/AdvCustomerModelChangePasswordTest.php5Adv_customer_model::changePassword() writes what the hashing seam returns (#603), returns false when no row was updated, and throws on a driver error instead of reporting the -1 of a swallowed failure as success (#954)
tests/Legacy/Eshop/AdvCustomerModelResetTokenTest.php16Token write/expiry and isValidToken() cases; resetPassword() revokes that customer's REST refresh tokens before the password UPDATE (:415-:491), looked up by the same valid-token condition; a failed revocation throws and issues no UPDATE; a failed UPDATE throws instead of reporting success; an unknown token touches nothing; updatePassword() writes hash and salt for that customer only (:516), matching zero rows is not a failure (:533), a failed write throws (:549); revokeRestSessions() matching nothing is a no-op (:587) (#790, #873)
tests/Unit/Rest/Auth/CustomerAuthResetPasswordTest.php2reset-password through the real PasswordResetService: a reset the model reports as not done answers the same 422 as an invalid token, never Password updated. (#790)
tests/Legacy/Eshop/AdvCustomerPasswordRevocationTest.php6Storefront forms: update_my_password() revokes before writing and keeps the old password (generic error, form again) when revocation fails, and reports a failed write and shows the form again (update_my_password_reports_a_failed_write_and_shows_the_form_again, :257); set_new_password() reports a failed revocation the same way, and a token consumed before the write with the invalid-link message; success paths unchanged (#790)

Coverage gaps:

  • No REST controller tests for CustomerAuth::forgotPassword() / resetPassword() (controllers are not unit-tested in this codebase)
  • No end-to-end test that verifies the email is actually sent and received

Wiki Guide: OAuth provider setup and configuration — see Social Auth Guide. Diagnosing and remediating a stranded REST customer login (duplicate rows, NULL/empty password hash, failed refresh_tokens write) — see REST Customer Login Recovery.