From 138ad78d4fedc5fe9edfd8de4e864b3c4425d931 Mon Sep 17 00:00:00 2001 From: yashlamba Date: Tue, 7 Nov 2023 22:17:09 +0100 Subject: [PATCH] ext: add user to db history before each flush --- invenio_accounts/ext.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/invenio_accounts/ext.py b/invenio_accounts/ext.py index dc52298f..8ad31a6e 100644 --- a/invenio_accounts/ext.py +++ b/invenio_accounts/ext.py @@ -19,6 +19,7 @@ from flask_security import Security from invenio_db import db from passlib.registry import register_crypt_handler +from sqlalchemy import event from werkzeug.utils import cached_property from invenio_accounts.forms import ( @@ -27,6 +28,8 @@ register_form_factory, send_confirmation_form_factory, ) +from invenio_accounts.models import User +from invenio_accounts.proxies import current_db_change_history from . import config from .datastore import SessionAwareSQLAlchemyUserDatastore @@ -330,3 +333,12 @@ def make_session_permanent(self, app): @app.before_request def make_session_permanent(): session.permanent = True + + +# Discuss: Logically, this should happen after_flush to avoid cases of rollbacks/failure. +@event.listens_for(db.session, "before_flush") +def update_db_history_user_updates(session, flush_context, instances): + """Listener for syncing updates to Users to DB history.""" + for obj in session.dirty: + if isinstance(obj, User): + current_db_change_history.add_updated_user(id(db.session), obj.id)