refactor(user): confirm an email inside the single user update

pr-ready step 3 (simplify). The confirmation now rides the one
apply_user_update transaction, guarded by expected_email, so a later 400
or 403 rolls it back and the edit audit sees it without a post-write
patch. update_user resets trust whenever it writes an email the caller
doesn't vouch for, replacing trust_email. Tests share the dialog's apply,
save and emailField helpers, and drop two redundant local imports.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Georges-Antoine Assi
2026-11-17 09:30:48 -05:00
parent cf46b01ff5
commit 012ae2fa1e
8 changed files with 139 additions and 72 deletions

View File

@@ -7,7 +7,7 @@ from sqlalchemy.orm import QueryableAttribute, Session, load_only
from sqlalchemy.sql import Delete, Select, Update
from decorators.database import INJECTED_SESSION, begin_session
from exceptions.database_exceptions import LastAdminError
from exceptions.database_exceptions import EmailChangedError, LastAdminError
from models.snapshot import Snapshot
from models.user import Role, User
@@ -118,33 +118,34 @@ class DBUsersHandler(DBBaseHandler):
data: dict[str, Any],
*,
keep_an_admin: bool = False,
expected_email: str | None = None,
session: Session = INJECTED_SESSION,
) -> User:
"""Write `data` to the user.
Args:
keep_an_admin: Raise LastAdminError if the write would leave no admin.
expected_email: Raise EmailChangedError unless the stored email still
matches, so a confirmation applies only to the address it names.
"""
if keep_an_admin:
self.refuse_removing_the_last_admin(id, data, session=session)
session.execute(
update(User)
.where(User.id == id)
.values(**data)
.execution_options(synchronize_session="evaluate")
# A new address is unconfirmed unless the caller vouches for it.
if "email" in data and "email_trusted" not in data:
data = {**data, "email_trusted": False}
query = self.filter(
update(User),
ids=[id],
emails=[expected_email] if expected_email is not None else (),
)
return session.scalars(select(User).filter_by(id=id)).one()
@begin_session
def trust_email(
self,
id: int,
email: str,
session: Session = INJECTED_SESSION,
) -> bool:
"""Mark the user's email trusted only if it is still `email`."""
query = self.filter(update(User), ids=[id], emails=[email])
# "evaluate" can't run the case-insensitive email match in Python.
sync = "evaluate" if expected_email is None else "fetch"
result = session.execute(
query.values(email_trusted=True).execution_options(
synchronize_session=False
)
query.values(**data).execution_options(synchronize_session=sync)
)
return affected_rows(result) > 0
if expected_email is not None and affected_rows(result) == 0:
raise EmailChangedError(id)
return session.scalars(select(User).filter_by(id=id)).one()
@begin_session
def set_ra_progression(