Users and access
Chassis ships a users module that extends stock Django Admin: Users, Groups, admin sessions, login-attempt limits, the administrator profile, self password change, GeoIP country detection, and the Admin action journal.
Global opt-out
Added in 1.0.7Projects with their own users runtime can disable Chassis automation globally:
CHASSIS_USERS_MODULE_ENABLED = False
This prevents automatic users Admin registration and pages, UserProfile synchronization, session-registry and audit middleware writes, and login-attempt limits. Chassis models and migrations remain available, so the database tables are still created. Remove the two users middlewares from the project configuration as well to make that configuration explicit.
What the site enables
When include_users_module = True (the default), ChassisAdminSiteMixin:
- registers Chassis
UserAdmin/GroupAdminforAUTH_USER_MODELandGroup - registers
UserSession,LoginAttempt,LoginAttemptSchedule,AdminAuditLog,AccountActionandImpersonationEvent - adds the personal Profile and Change password pages
- adds a separate Create user changelist action and page
- adds matching user-menu items
- prepends the Users and Administrators sidebar sections
- uses
ChassisAdminAuthenticationFormwhenlogin_formis unset - shows a GeoIP dashboard alert to superusers when the Country database is missing
Turn the module off on a site that must stay empty:
class CustomAdminSite(ChassisAdminSiteMixin, AdminSite):
include_users_module = False
The global CHASSIS_USERS_MODULE_ENABLED setting takes precedence over this
per-site flag.
Keep the admins and pages but declare your own sidebar:
class CustomAdminSite(ChassisAdminSiteMixin, AdminSite):
include_users_sidebar = False
sidebar_items = (
# your sections, including auth.user / auth.group if you want them
)
Create and edit users
Changed in 1.0.23Users lists accounts with both administrative flags cleared. Administrators lists staff and superusers, including inactive accounts. Both lists use the configured AUTH_USER_MODEL, enforce their selection for bulk actions, and share the existing change, history and password URLs. A separately registered ModelAdmin opts into these sections by inheriting Chassis UserAdmin.
Create user accepts the model’s USERNAME_FIELD, personal fields, REQUIRED_FIELDS, an optional phone number, password, and active status. The new account starts with ordinary access. The page requires the model’s view, add and change permissions, django_chassis.manage_user_access and django_chassis.view_user_creation. Successful creation records a Django admin addition and opens the account card.
For the standard Django user model, these are the grants to use when
delegating the account workflow. Replace auth.user permissions with the
configured model's equivalents when using a custom user model. Assign
Chassis permissions to a group in the default mode.
| Action | Required access |
|---|---|
| Open either account list | Active staff with user view or change access. |
| Create an ordinary account | auth.view_user, auth.add_user, auth.change_user, django_chassis.manage_user_access and django_chassis.view_user_creation. |
| Change activity of an ordinary account | auth.change_user and django_chassis.manage_user_access. |
| Change another account's administrator role, block, or soft-delete it | Active staff superuser and the account's change access. |
| Read the account actions journal | django_chassis.view_accountaction. |
In a test Admin site, grant the creation permissions to an operator's group. Open Users → Create user and save an active test account in the ordinary account list. Then sign in as a superuser, open the card and confirm Change role. The account moves to Administrators, where you can assign groups. Remove administrator access to return it to Users and clear those group memberships.
Account edits and native password changes recheck the operator’s current permissions and the target’s role under the same transaction locks as role changes. A password change updates only the password hash and keeps Django’s session and history handling.
The role flags are read-only. On another account, an active staff superuser can confirm an Change role or Superadministrator action. Removing administrator access clears both flags. Removing superuser access retains staff. Removing administrator access clears group memberships. Removing only superuser access preserves group memberships. Direct permission assignments are preserved. Role and status changes are audited in Account actions (django_chassis.view_accountaction). Role changes, blocking, disabling and soft deletion revoke tracked sessions after commit. Blocking and soft deletion deactivate the account. Clearing either marker leaves the account inactive until separately enabled.
The Account actions journal labels events with color badges and supports search by administrator and account. Filter by action, date or either participant. The list and read-only cards link to each participant when the administrator can open that account.
django_chassis.manage_user_access allows a staff operator with the model’s change permission to manage activity for ordinary accounts. Groups can be assigned in administrator cards. Both user and administrator cards accept an optional phone number. UserProfileService.set_phone(user=..., phone=...) replaces or clears it. Chassis stores digits only and checks uniqueness against existing numbers, including older formatted values. An empty number is available to any number of profiles.
The account cards and the personal administrator profile show the phone, login and activity details, account restrictions, and saved list size and language from UserProfile. On account cards, the activity fieldset follows the personal data. The personal profile also exposes the template blocks chassis_profile_after_account and chassis_profile_after_sessions. User creation uses the same Django Admin fieldsets as the edit page.
The group card shows paginated members and assigned permissions. New group assignments record the assignment date and the assigning administrator when available. The local admin login’s Remember me keeps the session for 14 days. Click the checkbox or its label to toggle it. Leaving it clear creates a browser-session cookie. A site can override get_login_provider_buttons(request) to return a tuple of django_chassis.dto.LoginProviderButtonDTO(slug, label, url, logo_url='', icon_class=''). The site supplies the destination URL and any redirect parameters it needs.
Unique account email
Added in 1.0.24Set CHASSIS_UNIQUE_USER_EMAIL = True to validate nonempty email addresses
when creating or editing standard Django auth.User accounts in Chassis Admin.
The forms compare addresses without case or surrounding spaces and allow any
number of empty values. Add a unique index on LOWER(TRIM(email)) with
WHERE TRIM(email) <> '' in the host project's migrations to enforce this rule
for concurrent writes and other entry points.
Active login blocks
Added in 1.0.24Include BlockedLoginAttemptsAdminPage from django_chassis.views in the site's
chassis_page_classes with the Chassis account module enabled. Blocks → Login
blocks lists active scopes by login, IP and browser using the current attempt
schedule. It requires django_chassis.view_loginattempt.
Grant django_chassis.unlock_loginattempt to show confirmed unlock actions.
A bulk confirmation checks each selected attempt again and skips expired or
superseded blocks. Product pages for other block types can share
django_chassis.options.BLOCKS_PAGE_GROUP in the navbar.
Sidebar
With the site mounted at /admin/, the standard account list uses
/admin/auth/user/, the administrators list uses /admin/pages/administrators/,
and creation uses /admin/pages/user-create/. The account list path follows
AUTH_USER_MODEL when customized.
- Users contains the ordinary account list, Account actions and the impersonation journal.
- Administrators contains the administrator list, Groups, Sessions, Login attempt schedules, Login attempts and the Admin audit journal.
Override get_users_sidebar_section() or get_administrators_sidebar_section()
to change the label or ordering.
The session changelist shows active sessions by default and provides explicit Inactive and All states. Its terminate action is available only for an active, non-current session when the administrator has the matching permission.
Changed in 1.0.23Session rows show the user, browser, operating system, activity, expiry and state. The session card includes the IP address, country code and device type. Admin audit rows show the captured administrator login, action, request and HTTP status. Result, IP address and browser details are available on the audit card. Account links require access to the linked card. The captured audit login remains visible after account deletion.
Login attempt schedules show the attempt number, delay and active state in separate columns. The login attempt journal uses separate columns for time, login, IP address, browser, attempt number, success and unlock events.
Terminating a session requires django_chassis.terminate_usersession. Unlocking login attempts requires django_chassis.unlock_loginattempt. Both actions require access to the journal item, confirmation and a CSRF-protected POST.
Group permissions
Changed in 1.0.4The Group permission selector hides permissions whose content-type model name
starts with historical. This removes the technical Historical* models
created by django-simple-history from the default access flow.
Set SIMPLE_HISTORY_HIDE_HISTORY_MODEL_PERMISSIONS = False to show them again.
Middleware
Add the session registry and Admin journal after authentication:
MIDDLEWARE = [
# ...
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django_chassis.middlewares.UserSessionMiddleware',
'django_chassis.middlewares.AdminAuditMiddleware',
]
Session and Admin audit rows store client IP via netaddr and browser/OS via
device-detector (User-Agent plus Chromium Client Hints).
Both middlewares listen on CHASSIS_ADMIN_PATH_PREFIX (default /admin/).
UserSessionMiddleware registers the current staff session, refreshes last-seen
at most once a minute, and logs the user out if the registry row is revoked or
expired.
Database tables
Changed in 1.0.1The users module stores its data in chassis_user_profiles,
chassis_user_sessions, chassis_login_attempt_schedules,
chassis_login_attempts, and chassis_admin_audit_logs.
Settings
| Setting | Default | Purpose |
|---|---|---|
CHASSIS_USERS_MODULE_ENABLED | True | Enable the automatic users runtime globally |
CHASSIS_UNIQUE_USER_EMAIL | False | Validate nonempty email uniqueness in the standard user Admin forms |
CHASSIS_LOGIN_ATTEMPT_LIMITS_ENABLED | True | Apply LoginAttemptSchedule delays |
CHASSIS_ADMIN_PATH_PREFIX | '/admin/' | Path prefix for session and audit middleware |
GEOIP_COUNTRY_DATABASE_PATH | unset | Absolute path to GeoLite2 Country .mmdb |
SIMPLE_HISTORY_HIDE_HISTORY_MODEL_PERMISSIONS | True | Hide Historical* model permissions from Group forms |
An empty login-attempt schedule means no delays. Configure rows in Admin
(first position must have delay_seconds=0).
GeoIP
Changed in 1.0.1geoip2 ships with the package. Point Django at a MaxMind Country file:
GEOIP_COUNTRY_DATABASE_PATH = '/var/lib/geoip/GeoLite2-Country.mmdb'
If the database is unavailable, country codes stay empty. With a readable
file, Chassis first checks CF-IPCountry, X-Country-Code and X-Geo-Country,
then looks up the client IP in the database if none contains a valid code.
Ensure that your reverse proxy removes client-supplied copies of those headers.
CHASSIS_TRUSTED_PROXY_NETWORKS
controls client IP resolution through X-Forwarded-For.
Profile and password
AdminProfileAdminPage is a PersonalAdminPage: the current staff user sees
account data, groups, last login/IP/country, the current session, and a
timeline of their Admin audit rows.
SelfPasswordChangeAdminPage uses Django’s PasswordChangeForm (old password
required), then logs the user out.
See also
Custom authentication surfaces
Added in 1.0.20AuthenticationSurface lets an application use Chassis attempt limits, GeoIP,
UserProfile and UserSession with its own templates and active nonstaff Django users.
The default Admin login continues to require staff.
Each view has its own module: SurfaceLoginView in
django_chassis.views.surface_login, SurfaceLogoutView in
django_chassis.views.surface_logout, and SurfacePasswordChangeView in
django_chassis.views.surface_password_change. The URL builder lives in
django_chassis.views.authentication_surface_urls. All four are also exported
from django_chassis.views.
from django_chassis.dto.authentication_surface import AuthenticationSurface
from django_chassis.views.authentication_surface_urls import authentication_surface_urls
surface = AuthenticationSurface(
name='operators',
login_url='/login/',
success_url='/workplace/',
login_template='operators/login.html',
password_template='operators/password.html',
url_prefixes=('/workplace/', '/profile/'),
staff_required=False,
lifetime_minutes=720,
expire_on_browser_close=True
)
urlpatterns = authentication_surface_urls(surface=surface)
CHASSIS_AUTHENTICATION_SURFACES = [surface]
Add django_chassis.middlewares.authentication_surface.AuthenticationSurfaceMiddleware
after Django authentication middleware and Chassis UserSessionMiddleware.
lifetime_minutes and expire_on_browser_close may be zero-argument callables,
resolved on login to read application configuration without database reads at import.
URLs are login, POST-only logout and profile/password. Django checks CSRF and
validates next against the request host. The profile/session services remain
available independently of Admin rendering.
The custom surface deadline is absolute and stored in shared Django session metadata; requests never extend it. Expiry denies only this surface and preserves an existing Admin-only registry/backend session. First login into a custom surface uses its browser-session/persistent cookie policy; entering from an existing registered Admin session preserves its cookie policy. Password change rotates the current key and invalidates other login sessions. A browser may restore session cookies after closing; the server deadline is the enforceable security boundary.
Call AuthenticationSurfaceService.is_expired from WebSocket consumers and verify
active User plus UserSession registry on heartbeat. HTTP middleware alone cannot
revoke an already-open socket. Applications retain ownership/business checks.
chassis_page_classes accepts Sequence[type[AdminPage]], including lists. The existing default remains compatible.
Optional profile_provider, theme_context and audit_sink callbacks keep DTOs, appearance and safe auth-event capture independent of Admin templates. Providers receive the active User/request; the audit sink receives request and event (login, logout, password_change) without password data. Use AuthenticationSurfaceService.get_deadline to display the absolute custom-surface expiry, rather than the shared backend cookie expiry.
Open the website as an ordinary user
Added in 1.0.23On an ordinary user's card, a staff operator with access to the card and
django_chassis.impersonate_user can open the website as that user. The modal
requires a reason of up to 500 characters and confirmation. Only active, unblocked accounts without staff,
superuser or deletion status qualify. The administrative session stays on its
original host. The separate read-only journal requires
django_chassis.view_impersonationevent and shows operator, target, destination,
reason, timestamp and lifecycle event.
Register ChassisConfigurationProvider
and initialize GlobalConfig to create chassis.impersonation_frontend_url.
Set it to
the complete HTTPS website entry URL, e.g. https://shop.example.test/claim.
A blank or missing key disables the button. HTTP on localhost, 127.0.0.1 or ::1
is supported in DEBUG. Configure Chassis UserSessionMiddleware for the Admin
prefix and use a revocable server-side Django session backend.
admin.example.test ── confirmed POST ──► Admin returns website URL with #token
shop.example.test ── reads and removes fragment, POSTs token ──► api.example.test
api.example.test ── redeems once, binds target to its website session ──► website
The project supplies the website entry page and its API. Read the fragment into
memory and immediately call history.replaceState to remove it before running
analytics or loading third-party resources. POST the token to a fixed exchange
endpoint. Enforce CSRF and validate the actual browser Origin against the trusted
website origin. On separate domains allow credentialed CORS only for that exact
origin and configure CSRF and website cookies for the deployment. Use host-only
cookies and isolate website session storage from the Admin cookie. Exclude the
exchange payload, response redirect headers and session credentials from logging.
In the consumer's protected POST handler, discard any existing website identity and create a fresh server-side session. Store a private binding and the reference as website session data. All workers must use the same Chassis data and have access to the source session backend and signing configuration.
from secrets import token_urlsafe
from uuid import UUID
from django_chassis.services import ImpersonationService
origin = request.headers["Origin"] # validated browser website origin
request.session.flush()
binding = token_urlsafe(32)
reference, target = ImpersonationService.redeem(token=token, origin=origin, binding=binding)
try:
request.session["impersonation"] = [str(reference), binding, origin]
request.session.save()
except Exception:
ImpersonationService.end(reference=reference, binding=binding, disposition="integration_failed")
raise
# Resolve the website principal on each protected request, including socket heartbeats.
reference_text, binding, origin = request.session["impersonation"]
target = ImpersonationService.validate(reference=UUID(reference_text), binding=binding, origin=origin)
# On website logout, using the values loaded from its session:
ImpersonationService.end(reference=UUID(reference_text), binding=binding)
request.session.flush()
Use the returned ordinary user for website authorization. Keep this delegated
identity out of generic Django login, Admin, and independently issued API tokens.
On PermissionDenied clear the delegated website session and deny the request.
The one-time exchange lasts up to 60 seconds. A redeemed session lasts up to
15 minutes from issuance, bounded by the originating session. Each validation rechecks
the database roles, permission, source session, target eligibility and website URL.
tests/test_impersonation.py covers the modal, CSRF, role and permission changes,
domain binding, backend logout, expiry, journal and replay. Run it against
PostgreSQL to exercise the simultaneous exchanges using separate connections.
The journal labels events with color badges and links to the administrator and target when their cards are accessible. The site address and reason are shown on the read-only event card. The journal displays the exchange deadline for unused grants and the access deadline after redemption. Logout records ended. A failed website session setup records integration_failed.
Risk observation for admin sessions
Added in 1.0.23Risk observation adds a section below the sessions in the personal admin profile
and in the account card. The current staff user can see their own assessment.
Viewing another user's assessment also requires
django_chassis.view_riskassessment and access to their account card.
Assessments are stored in chassis_risk_assessments. They record the observed
signals and the rules that produced the score. Observation does not affect login.
To connect it, install Django-GlobalConfig 1.1.5 or newer, Celery and
django-celery-beat. Register the provider with a category ID reserved by the
project and enable Celery task auto-discovery.
from django_gc import ProviderDefinition
GLOBAL_CONFIG_PROVIDERS = [
ProviderDefinition(
provider='django_chassis.configuration.RiskConfigurationProvider',
category_ids={'observation': 30},
),
]
Run migrate, initialize_global_configs and initialize_risk_schedule.
Run Celery worker and beat, then enable risk.is_enabled in GlobalConfig to
start calculation. The schedule uses risks.schedule_observations to dispatch
risks.assess_session. Re-running the schedule command preserves existing
operator settings. The provider is optional, and the section appears only after
the project initializes its risk settings.