K87L8BZBS6

Untitled

Dec 10th, 2024
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.73 KB | None | 0 0
  1. def update_grants(
  2.     schema: str,
  3.     role_configs: dict,
  4.     **kwargs
  5. ):
  6.     """
  7.    Обновляет права доступа для заданной схемы и списка ролей.
  8.  
  9.    :param schema: Имя схемы.
  10.    :param role_configs: Словарь с конфигурацией для ролей, где ключ — имя роли,
  11.                         а значение — словарь с параметрами:
  12.                             - "include_tables": список таблиц, на которые выдаются права.
  13.                             - "exclude_tables": список таблиц, исключаемых из прав.
  14.                             - "exclude_columns": словарь { "table_name": ["column1", "column2"] }
  15.                               с исключаемыми столбцами.
  16.    """
  17.     with PostgresHook(postgres_conn_id="DWH_prod").get_conn() as conn:
  18.         cur = conn.cursor()
  19.  
  20.         for role, config in role_configs.items():
  21.             include_tables = config.get("include_tables", [])
  22.             exclude_tables = config.get("exclude_tables", [])
  23.             exclude_columns = config.get("exclude_columns", {})
  24.  
  25.             # 1. Общий доступ для роли на схему
  26.             cur.execute(f"GRANT USAGE ON SCHEMA {schema} TO {role};")
  27.  
  28.             # 2. Условная выдача прав на таблицы
  29.             if include_tables:
  30.                 for table in include_tables:
  31.                     grant_query = f"GRANT SELECT ON {schema}.{table} TO {role};"
  32.                     logging.info(grant_query)
  33.                     cur.execute(grant_query)
  34.             else:
  35.                 # Если include_tables не задан, выдать права на все таблицы, кроме исключенных
  36.                 cur.execute(f"GRANT SELECT ON ALL TABLES IN SCHEMA {schema} TO {role};")
  37.                
  38.                 if exclude_tables:
  39.                     query_revoke = f"""
  40.                    WITH tables_to_revoke AS (
  41.                        SELECT table_schema, table_name
  42.                        FROM information_schema.tables
  43.                        WHERE table_schema = %s AND table_name = ANY(%s)
  44.                    )
  45.                    SELECT 'REVOKE SELECT ON ' || table_schema || '.' || table_name || ' FROM {role};'
  46.                    FROM tables_to_revoke;
  47.                    """
  48.                     cur.execute(query_revoke, (schema, exclude_tables))
  49.                     revoke_statements = cur.fetchall()
  50.  
  51.                     for row in revoke_statements:
  52.                         logging.info(row[0])
  53.                         cur.execute(row[0])
  54.  
  55.             # 3. Выдача прав на определенные столбцы
  56.             if exclude_columns:
  57.                 for table, columns in exclude_columns.items():
  58.                     columns_to_grant = f"""
  59.                    SELECT column_name
  60.                    FROM information_schema.columns
  61.                    WHERE table_schema = %s AND table_name = %s
  62.                          AND column_name NOT IN %s;
  63.                    """
  64.                     cur.execute(columns_to_grant, (schema, table, tuple(columns)))
  65.                     granted_columns = cur.fetchall()
  66.  
  67.                     if granted_columns:
  68.                         column_list = ", ".join(col[0] for col in granted_columns)
  69.                         grant_query = (
  70.                             f"GRANT SELECT ({column_list}) ON {schema}.{table} TO {role};"
  71.                         )
  72.                         logging.info(grant_query)
  73.                         cur.execute(grant_query)
  74.  
  75.         conn.commit()
  76.         cur.close()
Advertisement
Add Comment
Please, Sign In to add comment