Overview
Theallauth.usersessions app allows users to view and manage all their active sessions across different devices and browsers. This is essential for security-conscious applications where users need visibility and control over their account access.
Installation
Add the usersessions app to your Django project:settings.py
Basic Configuration
By default, user sessions are created at login but not actively tracked. To enable session tracking:settings.py
URL Configuration
Include the usersessions URLs in your project:urls.py
/accounts/sessions/- List and manage active sessions
User Session Model
Each session is stored in theUserSession model with the following fields:
Displaying Active Sessions
Create a view to show users their active sessions:views.py
my_sessions.html
Ending Sessions
Allow users to terminate specific sessions:views.py
Ending All Other Sessions
Implement a “logout all other devices” feature:views.py
Security Notifications
Detect and notify users when their session’s IP or user agent changes:signals.py
apps.py
Custom Adapter
Customize session management behavior:adapters.py
settings.py
Session Cleanup
Thepurge_and_list() method automatically removes stale sessions (where the Django session no longer exists):
management/commands/cleanup_sessions.py
Configuration Reference
USERSESSIONS_ADAPTER
Default:"allauth.usersessions.adapter.DefaultUserSessionsAdapter"
Path to the adapter class for customizing session management behavior.
USERSESSIONS_TRACK_ACTIVITY
Default:False
When enabled, sessions are actively tracked:
- IP address is updated on each request
- User agent is updated on each request
last_seen_attimestamp is updated
allauth.usersessions.middleware.UserSessionsMiddleware in MIDDLEWARE.
Best Practices
-
Enable Activity Tracking: Set
USERSESSIONS_TRACK_ACTIVITY = Trueto maintain accurate session information. -
Monitor Session Changes: Use the
session_client_changedsignal to detect suspicious activity. - Regular Cleanup: Implement periodic cleanup of stale sessions to keep your database clean.
- User Education: Provide clear information about active sessions in your UI so users understand what they’re seeing.
-
Security Alerts: Consider sending notifications for critical events like:
- New login from unknown device
- IP address changes
- All sessions terminated
- Session Limits: Consider implementing limits on concurrent sessions per user if needed for your security model.
Complete Example
Here’s a complete implementation:settings.py
