[Database] Cách tạo user chỉ có quyền xem trong postgresql

Để an toàn dữ liệu, bạn muốn tạo user chỉ xem dữ liệu database trong postgres.

Ví dụ db: db_user_prod ; user: stepup_view

Bước 1: Đăng nhập vào user có quyền quản trị cao nhất.

sudo -u postgres psql

Bước 2: Tạo mới user và mật khẩu

create user stepup_view;
alter user stepup_view with encrypted password 'matkhaucuaban';

Bước 3: Set quyền chỉ xem

  • Set quyền cho user stepup_view connect được tới database db_user_prod
GRANT CONNECT ON DATABASE db_user_prod to stepup_view;

  • Chuyển sang db mà chúng ta sẽ set quyền chỉ xem
\c db_user_prod;

  • Set quyền chỉ xem
GRANT SELECT ON ALL TABLES IN SCHEMA public TO stepup_view; 
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO stepup_view;

Vậy là ok rồi đó :drooling_face: