Python脚本如何操作数据库行列权限

wen 实用脚本 27

本文目录导读:

Python脚本如何操作数据库行列权限

  1. 使用SQL直接管理权限
  2. 使用ORM框架管理权限
  3. 使用中间层实现权限控制
  4. 使用动态SQL构建器
  5. 使用第三方权限管理库
  6. 关键建议

我来详细介绍Python操作数据库行列权限的几种实现方式:

使用SQL直接管理权限

MySQL示例

import mysql.connector
def manage_mysql_permissions():
    conn = mysql.connector.connect(
        host="localhost",
        user="root",
        password="password"
    )
    cursor = conn.cursor()
    # 创建用户
    cursor.execute("CREATE USER 'user1'@'localhost' IDENTIFIED BY 'password'")
    # 授予列级别权限
    cursor.execute("""
        GRANT SELECT (id, name, email) 
        ON database1.users 
        TO 'user1'@'localhost'
    """)
    # 通过视图实现行级别权限
    cursor.execute("""
        CREATE VIEW user1_view AS 
        SELECT id, name, email 
        FROM users 
        WHERE department = 'sales'
    """)
    cursor.execute("GRANT SELECT ON database1.user1_view TO 'user1'@'localhost'")
    conn.commit()
    cursor.close()
    conn.close()

PostgreSQL示例

import psycopg2
def manage_postgres_permissions():
    conn = psycopg2.connect(
        host="localhost",
        user="admin",
        password="password"
    )
    conn.autocommit = True
    cursor = conn.cursor()
    # 创建角色
    cursor.execute("CREATE ROLE analyst WITH LOGIN PASSWORD 'password'")
    # 授予表级别权限
    cursor.execute("GRANT SELECT ON employees TO analyst")
    # 列级别权限(通过创建视图)
    cursor.execute("""
        CREATE VIEW employee_basic AS
        SELECT id, name, position
        FROM employees
    """)
    cursor.execute("GRANT SELECT ON employee_basic TO analyst")
    # 行级别权限(使用行级安全策略)
    cursor.execute("ALTER TABLE employees ENABLE ROW LEVEL SECURITY")
    cursor.execute("""
        CREATE POLICY user_policy ON employees
        FOR ALL
        USING (current_user = manager)
    """)
    cursor.close()
    conn.close()

使用ORM框架管理权限

SQLAlchemy示例

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    email = Column(String)
    department = Column(String)
    salary = Column(Integer)
class PermissionManager:
    def __init__(self, connection_string):
        self.engine = create_engine(connection_string)
        self.Session = sessionmaker(bind=self.engine)
    def get_user_data_with_row_permissions(self, user_role, department=None):
        """基于角色的行级权限控制"""
        session = self.Session()
        # 基本查询
        query = session.query(User)
        # 行级过滤
        if department:
            query = query.filter(User.department == department)
        return query.all()
    def get_user_data_with_column_permissions(self, user_role):
        """基于角色的列级权限控制"""
        session = self.Session()
        # 定义不同角色的可访问列
        column_permissions = {
            'admin': [User.id, User.name, User.email, User.salary],
            'manager': [User.id, User.name, User.email],
            'employee': [User.id, User.name]
        }
        allowed_columns = column_permissions.get(user_role, [User.id, User.name])
        # 动态构建查询
        query = session.query(*allowed_columns)
        return query.all()

使用中间层实现权限控制

from functools import wraps
import hashlib
class DatabasePermissionMiddleware:
    def __init__(self, connection):
        self.connection = connection
        self.permissions_cache = {}
    def check_row_permission(self, user_id, table, row_id, operation='read'):
        """检查行级权限"""
        # 实际应用中需要查询权限表
        permission_key = f"{user_id}:{table}:{row_id}:{operation}"
        return self.permissions_cache.get(permission_key, False)
    def check_column_permission(self, user_id, table, column):
        """检查列级权限"""
        # 示例权限配置
        permissions = {
            'admin': ['*'],  # 所有列
            'manager': ['id', 'name', 'email', 'department'],
            'employee': ['id', 'name']
        }
        user_role = self.get_user_role(user_id)
        allowed_columns = permissions.get(user_role, [])
        return column in allowed_columns or '*' in allowed_columns
    def get_user_role(self, user_id):
        """获取用户角色"""
        cursor = self.connection.cursor()
        cursor.execute("SELECT role FROM user_roles WHERE user_id = %s", (user_id,))
        result = cursor.fetchone()
        return result[0] if result else 'employee'
# 使用示例
def with_permission_check(func):
    @wraps(func)
    def wrapper(self, *args, **kwargs):
        user_id = kwargs.get('user_id')
        if not user_id:
            raise PermissionError("No user specified")
        # 权限检查逻辑
        if not self.check_row_permission(user_id, *args):
            raise PermissionError("Insufficient permissions")
        return func(self, *args, **kwargs)
    return wrapper

使用动态SQL构建器

class DynamicSQLBuilder:
    def __init__(self, connection):
        self.connection = connection
        self.permission_config = self.load_permission_config()
    def load_permission_config(self):
        """加载权限配置"""
        return {
            'user1': {
                'tables': ['employees'],
                'columns': ['id', 'name', 'department'],
                'row_filter': "department = 'sales'"
            },
            'user2': {
                'tables': ['employees'],
                'columns': ['id', 'name', 'email', 'salary'],
                'row_filter': "department IN ('sales', 'marketing')"
            }
        }
    def build_select_query(self, user_id, table):
        """构建带权限的查询语句"""
        if user_id not in self.permission_config:
            raise PermissionError(f"User {user_id} has no permissions")
        config = self.permission_config[user_id]
        if table not in config['tables']:
            raise PermissionError(f"No access to table {table}")
        # 构建列选择
        columns = ", ".join(config['columns'])
        # 构建行过滤
        row_filter = config.get('row_filter', '1=1')
        query = f"SELECT {columns} FROM {table} WHERE {row_filter}"
        return query
    def execute_with_permissions(self, user_id, query_type, table, **kwargs):
        """执行带权限的查询"""
        if query_type == 'SELECT':
            query = self.build_select_query(user_id, table)
        elif query_type == 'INSERT':
            query = self.build_insert_query(user_id, table, **kwargs)
        elif query_type == 'UPDATE':
            query = self.build_update_query(user_id, table, **kwargs)
        elif query_type == 'DELETE':
            query = self.build_delete_query(user_id, table, **kwargs)
        return self.execute_query(query)

使用第三方权限管理库

# 使用 Apache Ranger 或类似工具
import requests
class ExternalPermissionManager:
    def __init__(self, ranger_url, auth_token):
        self.ranger_url = ranger_url
        self.auth_token = auth_token
    def check_permission(self, user, resource, action):
        """调用外部权限系统检查"""
        headers = {'Authorization': f'Bearer {self.auth_token}'}
        payload = {
            'user': user,
            'resource': resource,
            'action': action
        }
        response = requests.post(
            f"{self.ranger_url}/api/authorization",
            json=payload,
            headers=headers
        )
        return response.json().get('allowed', False)
    def get_allowed_columns(self, user, table):
        """获取用户允许访问的列"""
        response = requests.get(
            f"{self.ranger_url}/api/columns/{table}/{user}",
            headers={'Authorization': f'Bearer {self.auth_token}'}
        )
        return response.json().get('columns', [])

关键建议

  1. 安全考虑

    • 总是使用参数化查询防止SQL注入
    • 不要直接在代码中硬编码密码
    • 使用连接池和适当的错误处理
  2. 性能优化

    • 缓存权限查询结果
    • 批量处理权限变更
    • 使用数据库原生权限系统减少开销
  3. 最佳实践

    • 采用最小权限原则
    • 记录权限变更日志
    • 定期审查权限配置
    • 使用事务确保权限变更原子性
  4. 选择建议

    • 简单场景:使用数据库内置权限系统
    • 复杂场景:使用中间件或第三方工具
    • 微服务架构:使用独立权限服务

选择哪种方式取决于你的具体需求、数据库类型、安全要求和系统复杂度。

抱歉,评论功能暂时关闭!