How to check all roles/user/group_role have what privileges in postgres database?

女生的网名这么多〃 提交于 2020-02-06 07:35:53

问题


I have postgres database. I want the list of users with access privileges they are being assigned.

I tried to find query and also looked in to psql command line help. (\nu and all) but I haven't found any usefull information.

Is anyone knows about that can help me out.

Thanks.


回答1:


There are few basic command like \du and \l that will provide the general information.

For getting the detailed information you may use the below function.

CREATE OR REPLACE FUNCTION database_privs(text) RETURNS table(username text,dbname name,privileges  text[])
AS
$$
SELECT $1, datname, array(select privs from unnest(ARRAY[
( CASE WHEN has_database_privilege($1,c.oid,'CONNECT') THEN 'CONNECT' ELSE NULL END),
(CASE WHEN has_database_privilege($1,c.oid,'CREATE') THEN 'CREATE' ELSE NULL END),
(CASE WHEN has_database_privilege($1,c.oid,'TEMPORARY') THEN 'TEMPORARY' ELSE NULL END),
(CASE WHEN has_database_privilege($1,c.oid,'TEMP') THEN 'CONNECT' ELSE NULL END)])foo(privs) WHERE privs IS NOT NULL) FROM pg_database c WHERE 
has_database_privilege($1,c.oid,'CONNECT,CREATE,TEMPORARY,TEMP') AND datname not in ('template0');
$$ language sql;

and then call the same function by providing the username/role that you get from \du

postgres=# \du
                                   List of roles
 Role name |                         Attributes                         | Member of 
-----------+------------------------------------------------------------+-----------
 postgres  | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
 test      |                                                            | {}
 test2     |                                                            | {}
 test3     |                                                            | {}

postgres=# select * from database_privs('test');
 username |  dbname   |         privileges          
----------+-----------+-----------------------------
 test     | postgres  | {CONNECT,TEMPORARY,CONNECT}
 test     | template1 | {CONNECT}
 test     | test      | {CONNECT,TEMPORARY,CONNECT}
(3 rows)

Disclosure: I work for EnterpriseDB (EDB)



来源:https://stackoverflow.com/questions/59858343/how-to-check-all-roles-user-group-role-have-what-privileges-in-postgres-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!