Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I create role groups in postgresql

Tags:

sql

postgresql

I can create a role in postgresql.

  • CREATE ROLE myname WITH LOGIN PASSWORD 'pass';

and I can set privilages on a database schema for this user.

  • GRANT USAGE ON SCHEMA public TO myname;

and select privilages to a user.

  • GRANT SELECT ON ALL TABLES IN SCHEMA public TO myname;

But I have so many users in my database. I do not want to set these privilages to all of my users. Actually I want to create role groupnames:

  • viewer
  • editor
  • admin

And viewer will be select privilages on all tables, editor will be select, insert and update privilages on all tables.

my users will be in these groups.

How can I do this?

like image 538
barteloma Avatar asked Dec 13 '17 08:12

barteloma


People also ask

How do I create a role in PostgreSQL?

After you connect with the psql client, run the following command to create a role that has the LOGIN attribute and a non-empty, MD5-encrypted password: postgres=#CREATE ROLE demorole1 WITH LOGIN ENCRYPTED PASSWORD 'password1'; Note: The trailing semicolon ( ; ) at the end of the SQL statement is required.

What is Group role in PostgreSQL?

First, every member of a group can explicitly do SET ROLE to temporarily “become” the group role. In this state, the database session has access to the privileges of the group role rather than the original login role, and any database objects created are considered owned by the group role not the login role.


2 Answers

CREATE ROLE viewer;
CREATE ROLE editor;
CREATE ROLE admin;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO viewer;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO viewer;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT,INSERT,UPDATE ON TABLES TO editor;
GRANT some_other_privs_to_admin_group

after that just grant group to user:

GRANT editor TO your_user;

and so on

https://www.postgresql.org/docs/current/static/sql-alterdefaultprivileges.html https://www.postgresql.org/docs/current/static/sql-createrole.html

CREATE ROLE adds a new role to a PostgreSQL database cluster. A role is an entity that can own database objects and have database privileges; a role can be considered a “user”, a “group”, or both depending on how it is used.

and

A role having the LOGIN attribute can be thought of as a user. Roles without this attribute are useful for managing database privileges

like image 141
Vao Tsun Avatar answered Nov 11 '22 17:11

Vao Tsun


For this very reason it is advisable to use "groups", that is roles (usually with NOLOGIN) to which you add the users (by granting the role to them).

In your case:

CREATE ROLE viewer;
GRANT <whatever> TO viewer;
GRANT viewer TO myname;

Then myname will enjoy all the privileges granted to viewer, and you don't have to mess around with granting and revoking privileges to every user.

like image 40
Laurenz Albe Avatar answered Nov 11 '22 16:11

Laurenz Albe