Skip to content
JoeCMS Download 3.1.5
Manual · 08

Authentication, users and permissions

The CMS comes with a complete account system: login, registration, password recovery, activation, social login, groups, profiles and granular permissions down to the single content node. A project doesn't implement login: it uses it.

1. The auth module

modules/auth/contents/ contains the pages of the account lifecycle:

FolderFunction
loginsign-in
logoutsign-out
registrationregistration (framework widget, not a custom page)
activationactivation via a code sent by email
recoverpassword recovery
socialsign-in with social providers
sessionsession management
usersmodule-side user management

The front-end theme skins the pages in themes/site/contents/{login,recover,activation,logout}/ and the email templates in themes/site/contents/email/auth/. Widget configuration lives in themes/site/conf/settings.auth.php.

Widget JS can't depend on the theme. A widget in vendor/wolfgan/auth/widgets/<name>/ is also rendered outside the CMS layout — a site with its own public shell mounts $widget["html"], ["css"] and ["js"] wherever it likes, and usually loads only jQuery. A theme function (themes/<theme>/javascript/root.js, which import.php generates for every site) isn't there, and calling it is a ReferenceError that stops the function at the first line: the button stops responding, with nothing on the page explaining why. If a widget wants to use a theme extra, it calls it behind typeof … === "function" and does without the rest. The theme can replace the widget's template, CSS and script by putting index.html, style.css, script.js in themes/<theme>/contents/<name>/: whatever it doesn't provide is inherited from the widget.

The login button calls hCore.auth.login(url, selector, elem, redirect): elem is the clicked element — the onclick passes this — on which the script re-enables the controls after a negative answer, and the return path ({ret_url}) goes in fourth place. Up to 1.6.2 the templates, including themes/site/contents/login/index.html, passed it in third place: a rejected login died in the console (jQuery("/restricted")) without showing the message, and ?ret_url= was lost. The script (vendor/wolfgan/auth/widgets/login/script.js) now accepts as elem only an element or an id, but a login page copied into the theme with the old onclick must be fixed to get the return path. The password recovery widget reads its texts from the template, if they are there: data-err-password, data-err-conferma, data-err-diverse on #errorMsg, data-testo-codice on the button, data-etichette (separated by |) on the strength label; without them, the Italian ones remain (vendor/wolfgan/auth/widgets/recover/script.js). The theme template (themes/site/contents/recover/index.html) carries all of them, with dictionary codes (svc_rec_err_password, svc_rec_err_confirm, svc_reg_err_pw_match, svc_rec_reset_btn, svc_pw_strength); up to 3.0.3 it carried none, and recovery was in Italian in every language. The six code boxes have the label {_svc_otp_digit} N for screen readers.

Account messages are in the page's language. The errors Auth::login() returns to the form (empty fields, wrong credentials, account not yet activated, user not found), the one from Auth::request() for an invalid email, those of the recovery and activation widgets (wrong code, activation failed) and the text of the SMS with the code live in Auth::text(); the 2FA texts in Auth::text2FA() (vendor/wolfgan/auth/Auth.php). They are in Italian, English, French and Spanish; a language that is not there gets English. They are not in the dictionary because they must work on every installation without database rows: that is why Auth::text() is public, and a widget uses it instead of writing a message of its own. The link for an account still to be activated goes through content_i18n_url("/attivazione") (/en/activation, /fr/attivazione) and follows the contents/i18n.php manifest; Auth::userArea() does the same for the personal area (JC_USER_AREA_PATH), where the final buttons of activation and recovery lead, as does the redirect of someone opening activation while already signed in. The two messages the login script writes by itself (a response without an error, a service that does not respond) are chosen by hCore.auth.loginText() in vendor/wolfgan/auth/widgets/login/script.js, reading <html lang>. Up to 3.0.3 they were all in Italian in any language, and 2FA in Spanish came out in English. Two things to know for a custom-built login:

  • the form POSTs to /login, without a prefix: the kernel takes the language from the Referer prefix, and only for XHR requests (rewritePathInfo() in vendor/wolfgan/cms/services/kernel.php). A call without X-Requested-With, or with Referrer-Policy: no-referrer, gets the messages in the default language;
  • up to 3.1.2 registration via XHR (modules/auth/contents/registration/index.php), sent from a page with its own sections such as the home page, received that page's HTML and the account was not created: the POST was caught by the XHR shortcut in library/gallery/system/init.php (01 §2). Since 3.1.3 POSTs no longer take it;
  • Api::send() (vendor/hcore/api/Api.php) passes error through ffTranslator::get_word_by_code() using the text itself as the code: a text the dictionary does not know becomes a placeholder row in ff_international (is_new = 1, with the message in word_code, which is a varchar(255)). A new message, link included, stays under 255 characters.

⚠️ modules/auth/conf/routing_table.xml also contains rules for ^/oauth2/(.+), ^/apiserver/(.*) and ^/services/oauth2/(.+): the destination folders don't exist in this repo. They're rules inherited from upstream, inert today — there's no working OAuth2 server to use as-is.

2. The session API

Auth::isLogged();              // bool
Auth::get();                   // session array: ID, group, and application values
Auth::get("user");             // user object (acl_primary = group)

$auth = Auth::get();
$auth["chiave_applicativa"] = $valore;
Auth::set($auth);              // signature: set($value, $key = null)

On top sits the platform helper, in hook.php:

$ID = checkUserRights(true);   // true  → redirect to /login if guest   (pages)
$ID = checkUserRights(false);  // false → returns 0                    (services: answer JSON)

checkUserRights() also implements admin impersonation (user-id-value cookie + ?force_id=, allowed only to the administrators group). The ID is the personal-record one (anagraph.ID, the same as Auth::get()["ID"]), and an impersonated ID only counts if it is a personal record linked to an account (anagraph.ID_user): otherwise the function falls back to the signed-in user and deletes the cookie, which is left alone when it isn't there.

⚠️ Pitfall: precisely because impersonation exists, checkUserRights() may return a different user from the logged-in one. A check like "this record is mine" must be done on the ID returned by the function, not on the session's — otherwise, when impersonating, the admin sees their own stuff instead of the user's they're looking at.

3. The two user tables (and the one that counts)

TableRole
access_usersthe active one. Accounts, credentials. Admin is ID=1 in the seed
access_groups, access_users_groupsgroups and membership
anagraphperson profile, linked via anagraph.ID_user
cm_mod_security_userssecond legacy user table of the mod_security module: it exists, contains the same admin, and is not the active login path

The users and groups backend sections (conf/gallery/manage/{users,groups}/) keep access_users ↔ access_groups ↔ access_users_groups ↔ anagraph in sync, with bcrypt passwords.

Two operational notes:

  • Passwords are bcrypt and that's it, not least because MySQL's PASSWORD() no longer exists on MySQL 8. Login accepts only bcrypt (Auth::verifyPassword() in vendor/wolfgan/auth/Auth.php): an account with a hash in another format (MySQL PASSWORD(), WordPress) can't sign in and has to reset the password through recovery. Every write produces bcrypt: recovery (updateAccessInfo() in hook.php, with Auth::hashPassword()), the password field of the access model (string:inBcrypt in vendor/hcore/anagraph/services/access.php), the users backend, registration and the installer. Admin ID=1 in the seed (database.sql) still has a hash in the old format, which opens nothing with bcrypt-only login: the installer rewrites it with the chosen password (UPDATE, not INSERT).
  • An account's email address isn't just any field: changing it without a confirmation flow on the new address means being able to "move" an account to an unverified email. If the flow isn't there, the field stays non-editable by the user.

4. Profiles and permissions

Backend access profiles

Protection of the whole backend is a single rule in modules/auth/conf/routing_table.xml / conf/modules/auth/: restricted, with <profiles>admin,data-entry</profiles> and process_next. Everything under /restricted is protected by that rule: there's no need (and you shouldn't) to re-check in every controller.

Granular permissions on sections

Auth::env("AREA_VGALLERY_SHOW_MODIFY");
Auth::env("AREA_VGALLERY_SHOW_ADDNEW");
Auth::env("AREA_VGALLERY_SHOW_DELETE");
Auth::env("AREA_VGALLERY_SHOW_SEO");
Auth::env("AREA_VGALLERY_SHOW_PERMISSION");

⚠️ Auth::env() and Cms::env() read different buckets. They're not interchangeable. It's one of the hardest mistakes to spot reading the code, because the wrong call doesn't fail: it returns null, and the permission simply turns out denied (or granted) for no apparent reason.

The AREA_* constants — 74 occurrences in the code — are resolved at runtime by Auth::env()/Cms::env(). Some have their platform value in hook.php (AREA_PUBLISHING_SHOW_PREVIEW, AREA_SEO_SHOW_MODIFY, MOD_SEC_PROFILING), which defines them only if they do not exist yet. A project that wants to switch one of those backend functions on or off defines it in its config (themes/site/conf/config.remote.php), read before hook.php: changing it inside hook.php does not last, because updates replace it.

Permissions on content

users_rel_vgallery links user and node, with cascading inheritance: permission on a folder flows down to its children. It's the mechanism that allows editorial teams with partial visibility.

library/gallery/system/adv_permission.php and init_permission.php contain the advanced permissions engine.

5. Registration and user area

  • Registration moved to the framework widget (not a custom page), with the account in access_users and the profile in anagraph.
  • It's turned on/off with JC_REGISTRATION_ENABLE (chosen in the wizard).
  • The personal area path is JC_USER_AREA_PATH; /area-utente is just a fallback, not a fixed value: code must not hard-wire it.
  • Whoever signs up gets as profile language the language of the page they signed up from, both in access_users and anagraph. Afterwards they change it only with the language switcher. It's the language they receive emails and notifications in: see 06 §2.
  • hook.php contains the application helpers: registerUser(), updateUserInfo(), updateAccessInfo(), getUserByTokenLocal(), saveLocalToken(), checkSid()/getSid()/setSid(). It is platform code: a project's listeners, like the one below, go in a module or in hook.local.php (10 §1).
  • Once the account is created, jc_registration_submit() (modules/auth/contents/registration/index.php) fires the on_registration_done event: $account carries ID_user, ID_anagraph and email, $dati the consents (newsletter, privacy), the language, the IP, the browser, the date of birth (dob) and, in extra, the fields the project adds to the form named extra[...]: the widget sends them as they are, with no need to modify it. The CMS doesn't store the marketing consent or the project's fields anywhere: if the project needs them (customer record, marketing list, questionnaire), it writes them here. With no listeners nothing happens.
    Auth::addEvent("on_registration_done", function (&$account, $dati) {
        // $dati["newsletter"] is true if the box was ticked
        // $dati["extra"]["..."]: comes from the browser, must be validated
    });

The return after sign-in. ?redirect= (login, registration, activation, recovery, logout) and ?ret_url= (login) say where to send the user once the operation is done. They come from the page address, that is from whoever wrote the link, and go through Auth::redirectLocale() (vendor/wolfgan/auth/Auth.php): only a path of the site is valid (/area-utente, /en/my-account?tab=2), without spaces, quotes, < > or backslashes, and not starting with // or /\. An absolute address, even on your own domain, is ignored and the widget behaves as if there were no parameter. The login and logout scripts apply the same rule in the browser. A custom login that accepts a return address runs it through the same method: without it, it's an open redirect (?redirect=https://altro.sito) or code run in the page (?redirect=javascript:…).

Activation. The activation widget (vendor/wolfgan/auth/widgets/activation/) emails a 6-digit code and opens the screen to enter it. Two non-negotiable rules:

  • The code never goes back in the response to the browser. It's the secret proving access to the mailbox: index.php empties it ($response["code"] = "") before Api::send(). The widget doesn't need it — it reads the digits from the fields filled in by whoever received the email — and a custom activation page must not put it back there for debugging convenience: anyone would read it in the developer tools and activate someone else's account.
  • If the email doesn't go out, the page says so. Auth::request() normalises the outcome of Notifier::send() with Auth::erroreInvio(): that method returns a string when sending fails, true with a single service when it succeeds, and the array with error only when there are several services. Reading it without normalising gives a 500 (or an empty error in the good case) instead of the real message. See 06 §2.

5bis. Second factor (2FA)

Off by default. It's turned on with a constant in config.remote.php (the installer writes it empty):

define("AUTH_2FA", "sms");   // "" = off, "email" or "sms"

or per call with Auth::login($user, $pass, array("2FA" => "email")).

  • The flow. Correct username and password don't open the session yet: Auth::login sends a 6-digit code and answers require: "2fa" (status 428). The login widget shows the code field and on the next click sends username, password and code again; only then does the session (or token) start. The framework widget does this by itself; a custom login must handle require.
  • Channels. Email with the theme template themes/site/contents/email/auth/account_code.html (svc_mail_2fa_* dictionary texts), or with the module's one (vendor/wolfgan/auth/mailer/account_code.html, English only) if the theme does not have it; SMS with the Notifier: JoeSMTP if sms.joesmtp is configured, otherwise Twilio (06 §4). With sms, a user without a phone gets the code by email; with neither, 409. Up to 3.0.3 the template was auth::account_code.html, a name the Mailer does not resolve: the code email could not go out (mailer_template_notfound, and sign-in replied that the code could not be sent).
  • The code isn't stored: it's an HMAC of user ID and time window (the domain's sa_expire, default 300 s) keyed with JC_APP_SECRET + password hash. It's valid for the current and previous window; regenerating JC_APP_SECRET only invalidates codes in flight.
  • Limits. A new send at most every 60 s (the previous code stays valid); after 5 wrong codes the user's 2FA is locked for 15 minutes. State (no secrets) is in cache/auth-2fa/.
  • Exceptions. Emergency sudo access with the config's superadmin credentials skips 2FA; accounts not yet activated get the activation message, not a code.

6. The session: cookies, and the duplicate trap

The full detail — with symptom, cause and the seven rules that follow — is in ../documentazione/cms-ricetta-portabile.md §12. In short, what can't be forgotten:

  1. Cookie parameters must be set BEFORE session_start(), in a single place (cms_session_cookie_params() in conf/gallery/config.php). Setting them afterwards doesn't change the cookie already emitted: it creates a second one with the same name, and login stops holding.
  2. Deleting a cookie needs an expiry in the past. lifetime = 0 produces a session cookie, not a deletion.
  3. Domain is part of the cookie's identity: to clean up an already-dirty browser both forms (with and without Domain) must be emitted.
  4. Secure is derived from the connection (MOD_AUTH_COOKIE_SECURE to force it): hard-wired to true makes the cookie get discarded over HTTP, and in development login never holds.
  5. SameSite = Lax (MOD_AUTH_COOKIE_SAMESITE to set it to None, needed only if the site is embedded in a third-party iframe).
  6. No Domain on localhost and IP addresses: browsers discard the cookie.
  7. SESSION_NAME isn't a free value: it's derived from the domain (PHPSESS_[third][second][YYYYMM], www omitted) because two installations under the same parent domain share cookies and with a fixed name the sessions overwrite each other. Year and month stay frozen in the constant: recomputing them would log out every user on the first of each month.

vendor/wolfgan/auth/services/session.php is patched relative to upstream. A vendor update overwriting it brings the defect back: before replacing it, compare cookieParams(), cookieApply(), cookie_create() and cookie_destroy().

7. Application security: what to put in a new project

Settings proven in the ecosystem, to carry over:

  • bcrypt passwords (already so in the user backend);
  • double-submit CSRF with a token in a cookie + hidden field on forms that write;
  • rate limiting on login and password recovery;
  • application cookies with the array syntax of setcookie(): since PHP 7.3 the old trick of '; samesite=Lax' appended to the path no longer works;
  • whoever can't get in shouldn't know the door exists: a reserved area answers 404, not 403, to unauthorised users, and the menu entry doesn't show;
  • secrets outside tracked files: they live in config.remote.php (0640). See IGIENE_SEGRETI.md;
  • if you encrypt data (third-party tokens, credentials), AES-256-GCM with a key derived from JC_APP_SECRET via HKDF, with a different info per use — so one subsystem's secret isn't another's.

⚠️ JC_APP_SECRET lives in config.remote.php. Regenerating that file makes everything encrypted with it unreadable. It goes in the backup, and it isn't regenerated.