Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a tenant change hook #333

Merged
merged 2 commits into from
Jan 11, 2024
Merged

Conversation

Winslett
Copy link
Contributor

I've been looking to use ActsAsTenant in addition to Postgres's row-level security (RLS). With RLS, you can use a session variable to restrict the scope of queries to a single variable for a user. Then, the user would not be able to query all rows from a single query. In an attempt to keep ActsAsTenant as simple as possible, I think the best way to do this is a tenant_change_hook (or a similar pattern). This would allow a user to run a block of code each time the tenant is changed.

Using this tenant_change_hook, you could implement RLS with the following code block:

ActsAsTenant.configure do |config|
  config.tenant_change_hook = lambda do |tenant|
    if tenant.present?
      ActiveRecord::Base.connection.execute(ActiveRecord::Base.sanitize_sql_array(["SET rls.account_id = ?;", tenant.id]))
      Rails.logger.info "Changed tenant to " + [tenant.id, tenant.name].to_json
    end
  end
end

I've been around open source projects. Be harsh ;)

@excid3
Copy link
Collaborator

excid3 commented Jan 10, 2024

Thanks @Winslett, this is a great addition. Looks like Standardrb flagged a couple things but after that it should be good to go.

@excid3 excid3 merged commit 599d8af into ErwinM:master Jan 11, 2024
28 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants