๐ฅ Users, Authentication, and Brokers
This section explains the authentication model, user roles, and how data is segregated between users and brokers.
๐ Authentication Model (Stateless JWT Cookie)
LibreFolio authenticates with a signed JWT kept in an HTTP-only cookie. The server keeps no
record of sessions, neither in memory nor in the database: its one piece of session state is a
version per account, users.session_version, raised by one to end all of the account's sessions at
once. A restore sets every account's version to the restore time in milliseconds instead: a time,
not a counter, which the next change still raises by one
(Session Revocation).
๐ How it Works
- Login: The user sends their
username(or e-mail) andpasswordto the/api/v1/auth/loginendpoint. An identifier holding@names the account with that email address, in any AโZ case, and only when no account has it, the account with exactly that username; one without@is a username only, compared exactly (user_service.get_user_by_username_or_email(), lot A-21a: see Which Account an Identifier Names). - Token Creation:
- The server verifies the credentials (using
bcrypthashing). - If valid, it signs a JWT with
JWT_SECRET(HS256) carrying the user ID (sub), the account's session version (sv), the issue time (iat) and the expiry (exp):create_jwt_token()inbackend/app/services/accounts/auth_service.py.
- The server verifies the credentials (using
- Cookie Issuance: The server responds with a
Set-Cookieheader for thesessioncookie, which holds the JWT; itsmax_agematches the token's lifetime.HttpOnly: The cookie cannot be accessed by JavaScript (prevents XSS token theft).SameSite=Lax: Provides protection against CSRF attacks.Secure: decided bysession_cookie_secure()inbackend/app/api/v1/auth.pyfromSESSION_COOKIE_SECURE.auto, the default, sets it on HTTPS, seen directly or as the firstX-Forwarded-Protovalue of a reverse proxy;alwaysandneverforce it. Login, password change, email change, logout and account deletion use the same rule. See Configuration.
- Authenticated Requests: The browser automatically includes the session cookie in subsequent requests.
- Validation: On every request,
get_current_user()verifies the token's signature and expiry, then loads the user from the database: a missing or deactivated user gets401even with a valid token, and so does a token whosesvis not the account's currentsession_version.
๐พ Session State, Restarts & TTL
- ๐ง Stateless: No session is stored server-side โ the version check reads
users.session_versionfrom the user row every request loads anyway โ so any uvicorn worker can validate any token, provided all workers share the sameJWT_SECRET. - ๐ Restarts: Sessions survive a restart only if
JWT_SECRET, or the file named byJWT_SECRET_FILE, holds a fixed value. Without it, every start generates a new random key, existing tokens no longer verify, and everyone is signed out. See JWT Secret for how the key is resolved. - โฑ๏ธ TTL (Time To Live): The session duration is configurable via the
session_ttl_hoursGlobal Setting (default: 24 hours), read whenever a session cookie is issued: at login, and when a password or email change re-issues it. There is no refresh: after expiry the user logs in again. - ๐ช Revocation: Logout only deletes the cookie. A password change, an email change (which asks for the current password, see Changing the Email), a password reset (
./dev.py user reset, or a reset link once spent), a deactivation or a demotion (from the CLI or the administrator API), or an administrator's sign-out of the account raises the account'ssession_version: every session issued before it gets401at its next request, and a later reactivation does not bring them back. The password change and the email change also send a new cookie to the device that made them, which stays signed in. Deleting the user cuts access at the next request; changingJWT_SECRETsigns everyone out. See Session Revocation.
๐ค User Roles
There are two system-level user roles in LibreFolio:
-
๐ค Normal User:
- ๐ Can manage their own profile and settings.
- ๐ฆ Can create and manage their own brokers.
- ๐ค Can be granted access to other users' brokers.
-
๐ Superuser (Admin):
- โ Has all permissions of a normal user.
- โ๏ธ Can manage system-wide Global Settings, the registration mode included, unless
LIBREFOLIO_REGISTRATIONpins it. - ๐ง Can manage the other accounts through the administrator API under
/api/v1/users: list them, activate or deactivate, promote or demote, delete a regular account (Deleting an Account), create a password-reset link, sign an account out everywhere, restart its onboarding, and create, list or revoke invitations. The API never sets a password: the user chooses it through the reset link. See Registration, Invitations and the Admin API. - ๐ Can access any broker and transaction in the system for support purposes.
Whoever has a shell on the server manages accounts with the user CLI (./dev.py user โฆ), no account needed: it lists, creates, activates or deactivates, promotes or demotes accounts, sets a password directly (user reset), changes an account's email address (user set-email), creates invitations and password-reset links, gives the initial administrator a new setup link (user setup-link), and restarts a user's onboarding. It has no command to list or revoke invitations, to sign an account out without another change, or to delete an account. See Command-Line Tools.
๐๏ธ User-Broker Mapping and Data Segregation
Data in LibreFolio is segregated based on a clear ownership hierarchy, but allows for flexible sharing via the Broker Access Control (RBAC) system.
graph TD
UserA["User A (Owner)"] --> BrokerA1["Broker 1 (Degiro)"]
UserA --> BrokerA2["Broker 2 (IBKR)"]
UserB["User B (Viewer)"] -.-> BrokerA1
BrokerA1 --> TxA1["Transaction X"]
BrokerA2 --> TxA2["Transaction Y"]
Asset["Global Asset (e.g., Apple Inc.)"]
TxA1 -- "involves" --> Asset
- ๐ Ownership: A Broker is created by a User (the Owner).
- ๐ค Sharing: The Owner can grant access to other users (e.g., User B) with specific roles (Viewer, Editor).
- ๐ฐ Transactions: A Transaction belongs exclusively to one Broker.
- ๐ท๏ธ Names: Broker names are unique across the whole instance (
Broker.nameis a unique column), whoever owns them โ see Duplicate names. - ๐ Discovery: The brokers a user cannot access still appear by name on the Brokers page
(
BrokerDiscoveryCard, under Other Existing Brokers). Their sharing view is read-only:GET /brokers/{id}/accessloads the broker withas_user_id="all"and answers any signed-in user, so the user can see whom to ask for access. This is by design (developer decision, 2026-10-08): the users of one instance are not strangers, and seeing who has access lets them ask an Owner or choose whom to share with. The response carries each user's username, e-mail, role, share and avatar (BrokerService.list_accesses()); the frontend shows usernames and avatars, not e-mails.
๐ก๏ธ Broker Access Control (RBAC)
Access to brokers is granularly controlled via the BrokerUserAccess table.
๐ Deep Dive: For a detailed explanation of roles (OWNER, EDITOR, VIEWER) and permissions, see the Access Control (RBAC) documentation.
๐๏ธ Deleting an Account
An account is deleted by its holder, from the profile (DELETE /api/v1/auth/users/me, refused with 400
LAST_ADMIN to the last active administrator: see Superusers), or by an administrator
(DELETE /api/v1/users/{user_id}, with its refusals in
Deleting an Account). Both apply one rule, broker by broker: the
last-owner rule of BrokerService.leave_broker() (backend/app/services/brokers/access.py).
| The account's role on the broker | The deletion |
|---|---|
OWNER, the only one |
Deletes the broker, with its transactions and its BRIM report files |
OWNER, with another OWNER |
Removes the account's access; the broker stays |
EDITOR or VIEWER |
Removes the account's access; the broker stays |
Another OWNER row counts whether or not its account is active: an inactive co-owner keeps the broker.
- One helper for both routes.
user_service.delete_account(session, user)returnsAccountDeletionResult(deleted_broker_ids, files_removed). It callsdelete_user(), which applies the rule to each broker of the account in order of id, deletes the account and commits once; on any failure it rolls back and re-raises, so nothing is deleted and the route answers500Account deletion failed: nothing was deleted. The report files live on disk, outside the transaction:brim_provider.delete_files_for_brokers()removes those of the deleted brokers after the commit, in a worker thread (asyncio.to_thread). A failure there is logged and leaves the deletion done: the request still succeeds. -
The preview.
user_service.preview_user_deletion(session, user_id)computes, by the same rule and without writing anything, whatdelete_user()would take (Nonefor an unknown user). The API returns it asAccountDeletionPreviewRead: to any signed-in user for their own account (GET /api/v1/auth/users/me/deletion-preview), and to an administrator for any account (GET /api/v1/users/{user_id}/deletion-preview).{ "user_id": 7, "username": "alice", "brokers_deleted": [{"id": 3, "name": "Degiro", "transactions": 42}], "brokers_left": [{"id": 5, "name": "IBKR", "role": "OWNER"}], "transfers_unpaired": 1 }brokers_deletedandbrokers_leftare in order of broker id;roleis the account's role on a broker that stays:OWNER,EDITORorVIEWER. -transfers_unpairedcounts the transactions that stay but are linked byrelated_transaction_id, in either direction, to a transaction that goes: the halves of transfers left without their pair (backlog V-3). Each staying half counts once, whatever broker it is on. What becomes of a staying half is the rule of deleting a broker,TransactionService.delete_by_broker(): it loses its link, and becomes the standalone row a split of the pair leaves โ a receivedTRANSFERanADJUSTMENT, aCASH_TRANSFERorFX_CONVERSIONaDEPOSITor aWITHDRAWAL(backlog V-3, D-J4), and the giving leg of aTRANSFERanADJUSTMENTwithout a value (decision 47, as N78-1 changed it on 21/10/2026). See Broker Deletion. - Sessions.get_current_user()no longer finds a deleted account: its sessions get401at their next request.
Tests: ./dev.py test services account-deletion-preview
(backend/test_scripts/test_services/test_account_deletion_preview.py: in seven scenarios, the preview names
exactly the brokers delete_user() then deletes; the counts; nothing written; the report files removed once,
after the commit, and never when nothing is deleted or the deletion fails), ./dev.py test api account-deletion
(the own deletion and its preview, over HTTP) and ./dev.py test api users-admin (the administrator's routes).
๐ Global vs. User-Specific Data
- ๐ค User-Specific:
User,UserSettings. - ๐ฆ Broker-Specific:
Broker,Transaction,BrokerUserAccess. - ๐ Global:
Asset,PriceHistory,FxRate,GlobalSettings.
Assets are global because the information about a financial instrument (like Apple stock) is the same for everyone. However, a user's transactions involving that asset are private (scoped to their Broker).