Model Level Resolution in Rails

I want to implement authorization in my Rails application at the model level (and not at the controller), similar to the way model validation is performed. What is the best way to do this?

If it is implemented in the models themselves, the main problem is that the models do not have access to the current user. I have seen solutions like: Thread.current[:user_id] = session[:user_id] , but that doesn't seem like a good idea.

I saw a different approach when variants of methods such as create, find and new are created, taking an additional parameter for the current user.

Another approach would be to implement all the methods in the User / role class, so Post.create or Post.find will be used user.posts.create or user.readable_posts.find .

Which of these approaches will be proposed? Are there any better ways to implement authorization? Are there any plugins that make this easy? I need an approach that scales well for multiple roles and models.

+4
source share
2 answers

I would recommend you take a look at declarative permission . It works with both models and controllers.

How you do what you ask has a before_filter parameter in the applicationController, which sets Authorization.current_user = current_user , where authorization is a module.

I think this approach is the best, it keeps the models clean and you don’t have to forget to include the user everywhere, but instead you can filter it in the model callback functions.

+1
source

Why would you do this? Isn't identifying the controller level enough?

 if @user.is_able_to_do_this? do_this else blah! end 

... and in your model

 def is_able_to_do_this if self.rights > Constant::Admin_level_whatever return true end return false end 
0
source

All Articles