Skip to content

Instantly share code, notes, and snippets.

@mpokryva
Last active July 26, 2022 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpokryva/5019d941554e7521957a7cabcce8438c to your computer and use it in GitHub Desktop.
Save mpokryva/5019d941554e7521957a7cabcce8438c to your computer and use it in GitHub Desktop.
CREATE
TABLE
users(
id SERIAL PRIMARY KEY
);
CREATE
TABLE
orgs(
id SERIAL PRIMARY KEY
);
CREATE
TABLE
org_members(
user INTEGER REFERENCES users NOT NULL,
org INTEGER REFERENCES orgs NOT NULL
);
-- ** RLS setup **
ALTER TABLE
orgs ENABLE ROW LEVEL SECURITY;
-- Create a function, current_app_user(),
-- that returns the user to authorize against.
CREATE
FUNCTION current_app_user() RETURNS INTEGER AS $$ SELECT
NULLIF(
current_setting(
'app.current_app_user',
TRUE
),
''
)::INTEGER $$ LANGUAGE SQL SECURITY DEFINER;
CREATE
POLICY org_member_policy ON
orgs
USING(
EXISTS(
SELECT
1
FROM
org_members
WHERE
user = current_app_user()
AND org = id
)
);
-- Create the db user that'll be used in your application.
CREATE
USER app_user;
GRANT ALL PRIVILEGES ON
ALL TABLES IN SCHEMA public TO app_user;
GRANT ALL PRIVILEGES ON
ALL SEQUENCES IN SCHEMA public TO app_user;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment