Rails Admin and Multitenancy

Rails Admin vs. Multitenancy

Recently I started changing our single-tenant app into a multi-tenant one. Everything was going well until I stuck upon Rails Admin. As we all know, Rails Admin is a great tool to administer your data, among other gems like Administrate or Active Admin.

The challenge with Rails Admin I had was about scoping down the data so that given user sees data only from his tenant. I saw an issue on Github and unfortunately Rails Admin by default does not have an ability to add scopes with parameters. For instance, right now it is impossible to create an ActiveRecord scope to which we pass current user:

Exploring Rails Admin Code

I walked through the code and I was even adjusting the dashboard and index action so it can pass the current user argument to the scope, but after rethinking the problem, I took a different approach.

While reading the code, I saw that

Rails Admin supports two kinds of authorization systems: CanCan and Pundit. Click to Tweet
That gave me an idea that maybe instead of adjusting the gem to handle the additional argument, I could create my logic for authorization. As I thought about it, I started walking through the CanCan authorization logic.

Fortunately. The authorization logic was quite easy to understand and had some comments. I took an inspiration from the code and based on this, I created my own authorization, which is used for multi-tenancy.

Implementation of Multi-Tenant Authorization

Here are the steps to set up Rails Admin with multi-tenancy:

1. Create a module with class AuthorizationAdapter, which contains logic for authorization:

In my particular case, I had to limit the data scope by checking if given model is in user tenant.

2. Add a multitenant extension to Rails Admin:

3. Use the authorization in Rails Admin config:

Implementing such logic allows authorizing users and limits data, so a user will not access data out of his own tenant.

simon – blog

Simon is a lead developer responsible for designing and building application’s architecture from the ground up. As a mentor and a testing advocate, he supports other developers in their efforts to design software applications with code optimization and scalability in mind. He enjoys leading teams and discussing with clients issues concerning technical recommendations and possible adjustments to requirements.