-
Notifications
You must be signed in to change notification settings - Fork 32
♻️ webserver: Enhance Action Confirmation Token Logic (🚨🗃️) #8150
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
pcrespov
merged 22 commits into
ITISFoundation:master
from
pcrespov:is40/refactoring-confirmation-repository
Sep 26, 2025
Merged
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
3389868
✨ Implement ConfirmationRepository for managing user confirmation tokens
pcrespov c25904a
✨ Refactor confirmation service and repository integration for improv…
pcrespov 988e059
✨ Enhance confirmation service integration: add methods for managing …
pcrespov db89598
✨ Refactor invitation service: integrate confirmation service and rem…
pcrespov 601fe0b
✨ Refactor confirmation service integration: centralize service retri…
pcrespov c62bed5
✨ Refactor login module: replace legacy repository with confirmation …
pcrespov 3575989
rm legacy
pcrespov d4bdb58
rm legacy and move models
pcrespov b19eb75
imports
pcrespov 8d69500
new column
pcrespov adff46c
migration
pcrespov e715324
repositions migration
pcrespov 0f14b2b
fix: update down_revision in migration and import app_setup_func in g…
pcrespov 838783e
write operations
pcrespov 4ba3d20
fixes test
pcrespov fe4fc57
fixe pylint
pcrespov 85d7da7
fix: enhance error logging in change email process and correct variab…
pcrespov 661099c
minor fix
pcrespov e1bff2b
feat: implement confirmation service setup and integrate with invitat…
pcrespov 0c39aa2
Merge branch 'master' into is40/refactoring-confirmation-repository
pcrespov 51b00a6
Merge branch 'master' into is40/refactoring-confirmation-repository
pcrespov 685a8d2
Merge branch 'master' into is40/refactoring-confirmation-repository
pcrespov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
70 changes: 70 additions & 0 deletions
70
...e_postgres_database/migration/versions/9dddb16914a4_update_confirmation_created_column.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| """update confirmation created column | ||
|
|
||
| Revision ID: 9dddb16914a4 | ||
| Revises: 06eafd25d004 | ||
| Create Date: 2025-07-28 17:25:06.534720+00:00 | ||
|
|
||
| """ | ||
|
|
||
| import sqlalchemy as sa | ||
| from alembic import op | ||
| from sqlalchemy.dialects import postgresql | ||
|
|
||
| # revision identifiers, used by Alembic. | ||
| revision = "9dddb16914a4" | ||
| down_revision = "7e92447558e0" | ||
| branch_labels = None | ||
| depends_on = None | ||
|
|
||
|
|
||
| def upgrade(): | ||
| # Step 1: Add new column as nullable first | ||
| op.add_column( | ||
| "confirmations", | ||
| sa.Column( | ||
| "created", | ||
| sa.DateTime(timezone=True), | ||
| nullable=True, | ||
| ), | ||
| ) | ||
|
|
||
| # Step 2: Copy data from created_at to created, assuming UTC timezone for existing data | ||
| op.execute( | ||
| "UPDATE confirmations SET created = created_at AT TIME ZONE 'UTC' WHERE created_at IS NOT NULL" | ||
| ) | ||
|
|
||
| # Step 3: Make the column non-nullable with default | ||
| op.alter_column( | ||
| "confirmations", | ||
| "created", | ||
| nullable=False, | ||
| server_default=sa.text("now()"), | ||
| ) | ||
|
|
||
| # Step 4: Drop old column | ||
| op.drop_column("confirmations", "created_at") | ||
|
|
||
|
|
||
| def downgrade(): | ||
| # Step 1: Add back the old column | ||
| op.add_column( | ||
| "confirmations", | ||
| sa.Column( | ||
| "created_at", postgresql.TIMESTAMP(), autoincrement=False, nullable=True | ||
| ), | ||
| ) | ||
|
|
||
| # Step 2: Copy data back, converting timezone-aware to naive timestamp | ||
| op.execute( | ||
| "UPDATE confirmations SET created_at = created AT TIME ZONE 'UTC' WHERE created IS NOT NULL" | ||
| ) | ||
|
|
||
| # Step 3: Make the column non-nullable | ||
| op.alter_column( | ||
| "confirmations", | ||
| "created_at", | ||
| nullable=False, | ||
| ) | ||
|
|
||
| # Step 4: Drop new column | ||
| op.drop_column("confirmations", "created") | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
5 changes: 5 additions & 0 deletions
5
services/web/server/src/simcore_service_webserver/login/_application_keys.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| from aiohttp import web | ||
|
|
||
| from ._confirmation_service import ConfirmationService | ||
|
|
||
| CONFIRMATION_SERVICE_APPKEY = web.AppKey("CONFIRMATION_SERVICE", ConfirmationService) |
155 changes: 155 additions & 0 deletions
155
services/web/server/src/simcore_service_webserver/login/_confirmation_repository.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| import logging | ||
| from typing import Any | ||
|
|
||
| import sqlalchemy as sa | ||
| from models_library.users import UserID | ||
| from servicelib.utils_secrets import generate_passcode | ||
| from simcore_postgres_database.models.confirmations import confirmations | ||
| from simcore_postgres_database.models.users import users | ||
| from simcore_postgres_database.utils_repos import ( | ||
| pass_or_acquire_connection, | ||
| transaction_context, | ||
| ) | ||
| from sqlalchemy.engine import Row | ||
| from sqlalchemy.ext.asyncio import AsyncConnection | ||
|
|
||
| from ..db.base_repository import BaseRepository | ||
| from ._models import ActionLiteralStr, Confirmation | ||
|
|
||
| _logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def _to_domain(confirmation_row: Row) -> Confirmation: | ||
| return Confirmation.model_validate( | ||
| { | ||
| "code": confirmation_row.code, | ||
| "user_id": confirmation_row.user_id, | ||
| "action": confirmation_row.action.value, # conversion to literal string | ||
| "data": confirmation_row.data, | ||
| "created_at": confirmation_row.created, # renames | ||
| } | ||
| ) | ||
|
|
||
|
|
||
| class ConfirmationRepository(BaseRepository): | ||
|
|
||
| async def create_confirmation( | ||
| self, | ||
| connection: AsyncConnection | None = None, | ||
| *, | ||
| user_id: UserID, | ||
| action: ActionLiteralStr, | ||
| data: str | None = None, | ||
| ) -> Confirmation: | ||
| """Create a new confirmation token for a user action.""" | ||
|
|
||
| async with transaction_context(self.engine, connection) as conn: | ||
| # We want the same connection checking uniqueness and inserting | ||
| while True: # Generate unique code | ||
|
|
||
| # NOTE: use only numbers since front-end does not handle well url encoding | ||
| numeric_code: str = generate_passcode(20) | ||
|
|
||
| # Check if code already exists | ||
| check_query = sa.select(confirmations.c.code).where( | ||
| confirmations.c.code == numeric_code | ||
| ) | ||
| result = await conn.execute(check_query) | ||
| if result.one_or_none() is None: | ||
| break | ||
|
|
||
| # Insert confirmation | ||
| insert_query = ( | ||
| sa.insert(confirmations) | ||
| .values( | ||
| code=numeric_code, | ||
| user_id=user_id, | ||
| action=action, | ||
| data=data, | ||
| ) | ||
| .returning(*confirmations.c) | ||
| ) | ||
|
|
||
| result = await conn.execute(insert_query) | ||
| row = result.one() | ||
| return _to_domain(row) | ||
|
|
||
| async def get_confirmation( | ||
| self, | ||
| connection: AsyncConnection | None = None, | ||
| *, | ||
| filter_dict: dict[str, Any], | ||
| ) -> Confirmation | None: | ||
| """Get a confirmation by filter criteria.""" | ||
| # Handle legacy "user" key | ||
| if "user" in filter_dict: | ||
| filter_dict["user_id"] = filter_dict.pop("user")["id"] | ||
|
|
||
| # Build where conditions | ||
| where_conditions = [] | ||
| for key, value in filter_dict.items(): | ||
| if hasattr(confirmations.c, key): | ||
| where_conditions.append(getattr(confirmations.c, key) == value) | ||
|
|
||
| query = sa.select(*confirmations.c).where(sa.and_(*where_conditions)) | ||
|
|
||
| async with pass_or_acquire_connection(self.engine, connection) as conn: | ||
| result = await conn.execute(query) | ||
| if row := result.one_or_none(): | ||
| return _to_domain(row) | ||
| return None | ||
|
|
||
| async def delete_confirmation( | ||
| self, | ||
| connection: AsyncConnection | None = None, | ||
| *, | ||
| confirmation: Confirmation, | ||
| ) -> None: | ||
| """Delete a confirmation token.""" | ||
| query = sa.delete(confirmations).where( | ||
| confirmations.c.code == confirmation.code | ||
| ) | ||
|
|
||
| async with transaction_context(self.engine, connection) as conn: | ||
| await conn.execute(query) | ||
|
|
||
| async def delete_confirmation_and_user( | ||
| self, | ||
| connection: AsyncConnection | None = None, | ||
| *, | ||
| user_id: UserID, | ||
| confirmation: Confirmation, | ||
| ) -> None: | ||
| """Atomically delete confirmation and user.""" | ||
| async with transaction_context(self.engine, connection) as conn: | ||
| # Delete confirmation | ||
| await conn.execute( | ||
| sa.delete(confirmations).where( | ||
| confirmations.c.code == confirmation.code | ||
| ) | ||
| ) | ||
|
|
||
| # Delete user | ||
| await conn.execute(sa.delete(users).where(users.c.id == user_id)) | ||
|
|
||
| async def delete_confirmation_and_update_user( | ||
| self, | ||
| connection: AsyncConnection | None = None, | ||
| *, | ||
| user_id: UserID, | ||
| updates: dict[str, Any], | ||
| confirmation: Confirmation, | ||
| ) -> None: | ||
| """Atomically delete confirmation and update user.""" | ||
| async with transaction_context(self.engine, connection) as conn: | ||
| # Delete confirmation | ||
| await conn.execute( | ||
| sa.delete(confirmations).where( | ||
| confirmations.c.code == confirmation.code | ||
| ) | ||
| ) | ||
|
|
||
| # Update user | ||
| await conn.execute( | ||
| sa.update(users).where(users.c.id == user_id).values(**updates) | ||
| ) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.