Why we abbadoned cancan(cancancan for rails 4) and started using pundit. #1
So lets talk about the example features, problems and pundit of course.
Project allows to sign up for a company head person, and then add his employees. Then they can manage their company documents, invoices, crm tasks etc. etc. Also there is superadmin that can read all records.
In 1 company we have different roles with different abilities.
So at the and we have 2 main different security features.
1) Secure that employee of one company can't have any access to other company records.
2) Manage standard ability to diffrent actions by role of current user.
Let me tell you how we figured it out before we found pundit , and later on i show you how we managed it with pundit.
Secure that employee of one company can't have any access to other company records.
There are few different approaches to solve that problem. Affter a little research we started to discuss about selecting one of the two following:
- different database for each company , and managing db connection depends on current user
- scoping with for_company(user.company_id) for each record.
I suppose that could be another post about what adventages and disadvantages each of those approaches have, but in our case - when we expect each company have about 2-10 employees, creating new db for each of them doesn't seems legit. So we choosed simple rails backend security by adding proper scope for each query we have.
Lets dive into to code:
and then some code in controllers so we avoid using .for_company in every single AR scope:
and it works. Quite simple to write, so also readable . Testing .. well there were few problems, and tbh we did't managed all of them because we found pundit early enough ;] Let me show you how we use pundit and how we manage with problems that it gives.
Okey , so lets open the tests box and look what problems we found:
Well we didnt found any. It doesn't change anything in matter of tests. There were no problem to explain it for our juniors, and tbh there is no point to write plenty of tests because we use the same solution everywhere so it is enough if we test it in at least 1 place where we use that scope and in application_controller use magic method that pundit provides:
So that is all about "Secure that employee of one company can't have any access to other company records with pundit." feature. In second part of this blogpost i will show you how we handled ability authorization , and how awesome it looks like connected with scopes.
TL; DR: https://github.com/elabs - those guys know what are they doing ;]