Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL revoke privileges from column

I have a user group named editor_users in my PostgreSQL 9.5 database. And my product table is granted select, insert, update and delete to editor_user members.

But I want to prevent my id column. Nobody may not update id column. How can I revoke update privileges from users?

like image 435
barteloma Avatar asked Jan 05 '18 07:01

barteloma


People also ask

How do you revoke privileges in PostgreSQL?

Introduction to the PostgreSQL REVOKE statement First, specify the one or more privileges that you want to revoke. You use the ALL option to revoke all privileges. Second, specify the name of the table after the ON keyword. You use the ALL TABLES to revoke specified privileges from all tables in a schema.

How do I revoke a specific user privilege?

You can also revoke one or more table privileges by specifying a privilege-list. Use the DELETE privilege type to revoke permission to delete rows from the specified table. Use the INSERT privilege type to revoke permission to insert rows into the specified table.

How do I change privileges in PostgreSQL?

First, connect to your database cluster as the admin user, doadmin , by passing the cluster's connection string to psql . This brings you into the interactive shell for PostgreSQL, which changes your command prompt to defaultdb=> . From here, connect to the database that you want to modify the user's privileges on.

How do I find grant privileges in PostgreSQL?

Another way to do this is to use the information_schema schema and query the table_privileges table as: $ SELECT * FROM information_schema. table_privileges LIMIT 5; The above query will show detailed information about user privileges on databases as well as tables.


2 Answers

You could give privileges for every column. Assuming you have a table like the following:

CREATE TABLE product (
    id serial primary key,
    mytext text
);

You can grant privileges to editor_user like that:

GRANT SELECT(id), INSERT(id) ON product TO editor_user;
GRANT SELECT(mytext), UPDATE(mytext), INSERT(mytext), REFERENCES(mytext) ON product TO editor_user;
like image 127
Max Avatar answered Sep 29 '22 11:09

Max


You have two options here. The first is to revoke to the table and grant to the columns. If you do this, then it is worth using the Indoemation schema or system catalogs to discover all the relevant columns and programmatically creating the grant statements. If you go that route array_agg and array_to_string are your friends.

for example you could:

revoke all on table product from public, ...;
select 'grant insert(' || array_to_string(array_agg(attname), ', ') || ') to ... ;' 
  from pg_attribute
 where attrelid = 'product'::regclass and attnum > 0;

Then copy and paste the output into the psql window.

like image 43
Chris Travers Avatar answered Sep 29 '22 10:09

Chris Travers