Postgres 仅向用户授予 SELECT 和 UPDATE 权限

问题描述 投票:0回答:2

任何人都可以告诉我如何在 postgresql 上授予用户(用户名:restricted_user)仅具有 SELECT AND UPDATE 权限吗?我正在运行centos。

目前用户无法选择任何内容。我已经登录到 phpPgMyAdmin,我似乎只能为有效的用户授予每个表的 SELECT 和 UPDATE 权限,但我想将此规则应用于所有数据库中的所有表。

谢谢

database postgresql database-schema privileges
2个回答
7
投票

您可以一次授予模式中的所有表:

GRANT SELECT, UPDATE ON ALL TABLES IN SCHEMA public TO restricted_user;

如果正在使用

serial
列或其他序列,您还需要:

GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO restricted_user;

针对每个相关模式运行。 更多内容请参见

GRANT
的精美手册。 您还需要每个模式的
USAGE
权限:

GRANT USAGE ON SCHEMA public TO restricted_user;

如果您有另一个用户创建更多对象,您可能也希望默认为未来的对象授予相同的权限。这就是

DEFAULT PRIVILEGES
发挥作用的地方:

ALTER DEFAULT PRIVILEGES FOR creating_user IN SCHEMA public
GRANT SELECT, UPDATE ON TABLES TO restricted_user;

ALTER DEFAULT PRIVILEGES FOR creating_user IN SCHEMA public
GRANT USAGE ON SEQUENCES TO restricted_user;

0
投票

我知道有很多答案和解决方案,但我希望能帮助别人。我创建了一个简单的查询来处理这个问题。

DO $$
DECLARE 
    schema_name text;
    user_name text;
    table_privileges text;
BEGIN
    -- set user to assign privileges to
    user_name := 'my_user';
    -- set which privileges to assign
    table_privileges := 'SELECT, INSERT, UPDATE';

    FOR schema_name IN 
        -- find schemas (in my case I'm working in timescale so excluding     these as well) feel free to determine your own filters on schemas
        SELECT DISTINCT table_schema 
        FROM information_schema.tables
        WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
          AND table_schema NOT LIKE ('%timesca%')
    LOOP
        EXECUTE format('REVOKE ALL ON ALL TABLES IN SCHEMA %I FROM PUBLIC;', schema_name);
        
        EXECUTE format('GRANT USAGE ON SCHEMA %I TO %I;', schema_name, user_name);  
        EXECUTE format('GRANT SELECT, INSERT, UPDATE ON ALL TABLES IN SCHEMA %I TO %I;', schema_name, user_name);
        EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT SELECT, INSERT, UPDATE ON TABLES TO %I', schema_name, user_name);

        IF(UPPER(table_privileges) like '%INSERT%') THEN
            EXECUTE format('GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA %I TO %I;', schema_name, user_name);
            EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA %I GRANT USAGE, SELECT ON SEQUENCES TO %I;', schema_name, user_name);         
        END IF;

    END LOOP;

END $$;
© www.soinside.com 2019 - 2024. All rights reserved.