Vitor-Avila commented on code in PR #32231:
URL: https://github.com/apache/superset/pull/32231#discussion_r1967809513


##########
superset/commands/database/sync_permissions.py:
##########
@@ -0,0 +1,313 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+from __future__ import annotations
+
+import logging
+from functools import partial
+from typing import Iterable
+
+from superset import app, security_manager
+from superset.commands.base import BaseCommand
+from superset.commands.database.exceptions import (
+    DatabaseConnectionFailedError,
+    DatabaseConnectionSyncPermissionsError,
+    DatabaseNotFoundError,
+    UserNotFoundInSessionError,
+)
+from superset.commands.database.utils import ping
+from superset.daos.database import DatabaseDAO
+from superset.daos.dataset import DatasetDAO
+from superset.databases.ssh_tunnel.models import SSHTunnel
+from superset.db_engine_specs.base import GenericDBException
+from superset.exceptions import OAuth2RedirectError
+from superset.models.core import Database
+from superset.tasks.permissions import sync_database_permissions
+from superset.utils.decorators import on_error, transaction
+
+logger = logging.getLogger(__name__)
+
+
+class SyncPermissionsCommand(BaseCommand):
+    """
+    Command to sync database permissions.
+    """
+
+    def __init__(
+        self,
+        model_id: int,
+        username: str | None = None,
+        old_db_connection_name: str | None = None,
+        db_connection: Database | None = None,
+        ssh_tunnel: SSHTunnel | None = None,
+    ):
+        """
+        Constructor method.
+        """
+        self.username = username
+        self.db_connection_id = model_id
+        self._old_db_connection_name: str | None = old_db_connection_name
+        self._db_connection: Database | None = db_connection
+        self.db_connection_ssh_tunnel: SSHTunnel | None = ssh_tunnel
+
+        self.async_mode: bool = app.config["SYNC_DB_PERMISSIONS_IN_ASYNC_MODE"]
+
+    @property
+    def db_connection(self) -> Database:
+        if not self._db_connection:
+            raise DatabaseNotFoundError()
+        return self._db_connection
+
+    @property
+    def old_db_connection_name(self) -> str:
+        return (
+            self._old_db_connection_name
+            if self._old_db_connection_name is not None
+            else self.db_connection.database_name
+        )
+
+    def validate(self) -> None:
+        self._db_connection = (
+            self._db_connection
+            if self._db_connection
+            else DatabaseDAO.find_by_id(self.db_connection_id)
+        )
+        if not self._db_connection:
+            raise DatabaseNotFoundError()
+
+        if not self.db_connection_ssh_tunnel:
+            self.db_connection_ssh_tunnel = DatabaseDAO.get_ssh_tunnel(
+                self.db_connection_id
+            )
+
+        # For async mode we'll need to pass the user to the Celery task in 
case of
+        # OAuth connections.
+        if self.async_mode:
+            if (
+                not self.username
+                or not security_manager.get_user_by_username(self.username)
+                # The perm is already validated at the API layer, but checking 
here
+                # as well since Celery would also call this Command.
+                or not security_manager.can_access("can_write", "Database")
+            ):
+                raise UserNotFoundInSessionError()
+
+        with self.db_connection.get_sqla_engine() as engine:
+            try:
+                alive = ping(engine)
+            except Exception as err:
+                raise DatabaseConnectionFailedError() from err
+
+        if not alive:
+            raise DatabaseConnectionFailedError()
+
+    def _run(self) -> None:
+        """
+        Triggers the perm sync in sync or async mode.
+        """
+        self.validate()
+        if self.async_mode:
+            self.trigger_task()
+        else:
+            self.sync_permissions()
+
+    @transaction(
+        on_error=partial(on_error, 
reraise=DatabaseConnectionSyncPermissionsError)
+    )
+    def run(self) -> None:
+        """
+        Run the SyncPermissionsCommand for a DB connection.
+        """
+        self._run()
+
+    def run_nested_transaction(self) -> None:
+        """
+        Run the SyncPermissionsCommand in a nested transaction.

Review Comment:
   You're right! ✅ 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: notifications-unsubscr...@superset.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscr...@superset.apache.org
For additional commands, e-mail: notifications-h...@superset.apache.org

Reply via email to