Skip to content

Instantly share code, notes, and snippets.

@alexesDev
Created March 13, 2018 09:31
Show Gist options
  • Save alexesDev/187ab92a7674c1289d8304bd8665463d to your computer and use it in GitHub Desktop.
Save alexesDev/187ab92a7674c1289d8304bd8665463d to your computer and use it in GitHub Desktop.
Postgres security row polises with sessions vars
set role api; set session app.current_user_id to 1; select * from app_users;
id | first_name
----+------------
1 | john
2 | max
set role api; set session app.current_user_id to 2; select * from app_users;
id | first_name
----+------------
2 | max
drop table if exists app_users cascade;
drop table if exists app_chains cascade;
drop table if exists app_chains_users cascade;
create table app_users (
id serial primary key,
first_name text not null
);
alter table app_users enable row level security;
alter table app_users force row level security;
create role api;
create table app_chains (
id serial primary key,
owner_id int not null references app_users,
name text not null
);
create table app_chains_users (
user_id int not null references app_users,
chain_id int not null references app_chains,
primary key(user_id, chain_id)
);
create policy chain_scope on app_users to api
USING (
id = current_setting('app.current_user_id')::integer or
id in (
select user_id
from app_chains c
join app_chains_users cu on cu.chain_id = c.id
where c.owner_id = current_setting('app.current_user_id')::integer
)
);
grant all on app_users to api;
grant all on app_chains to api;
grant all on app_chains_users to api;
insert into app_users (id, first_name)
values (1, 'john'), (2, 'max'), (3, 'jessy');
insert into app_chains (id, owner_id, name)
values (1, 1, 'pretty');
insert into app_chains_users (user_id, chain_id)
values (1, 1), (2, 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment