blender-id/bid_main/middleware.py
Oleg Komarov ce31207f36 User session tracking (#93587)
## Motivation

A user needs to know how their account is being accessed/used.
At the very minimum, we need to display information about recent sign-ins and active sessions.

This PR adds:
- a new "Active Sessions" page that lists existing sessions linked to a user, with an option to terminate a particular session;
- an email that is sent to a confirmed email address when a new login happens from a different IP address.

## Implementation

Builtin django sessions are lacking some essential features:
- it's impossible to efficiently list all sessions belonging to a user
- there is not enough metadata: when and where a session was created

This PR adds a cross table `bid_main_user_session` that links to both `django_session` and `bid_main_user` tables, and also stores info about sign-in timestamp, last activity timestamp, IP and User-Agent.
A `UserSession` object is updated (or created, for new sessions and for active sessions existing before the rollout) on every authenticated request to update the `last_active_at` field.
This is done in a new `user_session_middleware`.

A further improvement (intentionally excluded from the PR): use geoip2 to display an IP-based location in the Active Sessions listing and the email.

Reviewed-on: #93587
Reviewed-by: Anna Sirota <annasirota@noreply.localhost>
2024-08-02 16:04:08 +02:00

14 lines
387 B
Python

from bid_main.models import UserSession
def user_session_middleware(get_response):
def middleware(request):
if (
hasattr(request, 'session')
and hasattr(request, 'user')
and request.user.is_authenticated
):
UserSession.update_or_create_from_request(request)
return get_response(request)
return middleware