Managing Postgresql Users, Roles, and permissions

Let’s make sure you have postgresql db. Please follow your Postgres documentation for the installation.

  1. You have a database and you want to create a user for the database only and you want to make it owner. First of all the user must be “Superuser” on the database. Then follow the steps:
  2. Login as the user – abcd
  3. Lets take step by step to make the user owner and revoke all the privileges from public.
1) Create an admin user and grant superpuser (without superuser, you can do the alter ... owner

2) alter to have the admin user owner
alter schema public owner to administer;

3)revoke the default create permissions
revoke create on schema public from public;

4) revoke the public role's ability to connect to the database
revoke all on database demodb from public;

5) create a write role and grant permissions
create role db_write no login no inherit;

-- grant usage on the db
grant usage on schema public to db_write;
-- allow all operations on all tables
grant select, insert, update, delete on all tables in schema public to db_write;
-- allow usage of sequences, need for serial keys etc
grant usage, select on all sequences in schema public to db_write;
-- grant default operations on all tables created in the future
alter default privileges in schema public
   grant select, insert, update, delete on tables to db_write;
-- grant default operations on all sequences created in the future
alter default privileges in schema public
   grant usage, select on sequences to db_write;  

5) create a user with the db_write role
create role "db_user" with login in role db_write;

6) grant user permission to connect to our database.
grant connect on database demodb to db_user;

Once you have a database setup, following steps to remove default public access

If you do not have the db owner or if you need a new db owner, then create an admin user and grant superpuser (without superuser, you can do the alter ... owner

1) alter to have the admin user owner
alter schema public owner to administer;

2)revoke the default create permissions
revoke create on schema public from public;

3) revoke the public role's ability to connect to the database
revoke all on database demodb from public;