Mixing security logic with models in Ruby on Rails?

Is there a bad design for mixing code that is related to the security logic in the model?

Example for editing a page in a before_save callback

  • The current user is captured using the current_user method at the controller level.
  • Throw exception if current_user.has_permission? :edit_page current_user.has_permission? :edit_page false
  • editor_id set to current_user.id
  • The change is recorded in a separate table

The model is not the only security check in the application. The user interface checks the resolution before viewing the screen editing. The model acts as a barrier to any errors at the View / Controller level.

Note. The only violation between the Model and Controller levels is the current_user method. The application I'm working on will never allow anonymous users.

+4
source share
3 answers

The model in the MVC framework must fully contain all of your business logic. In a well-designed MVC application, you should theoretically at least have the ability to reuse your models in a different context without rebuilding any of your business logic.

In each case, I can think about authorization, checking input and maintaining an audit trail - this is, of course, business logic, and therefore it should be processed in your model.

On the other hand, I think authentication, encryption, cryptographic hashing, etc. are not part of the model. These security aspects are not part of the core business logic; they are usually part of the application interface.

+4
source

I donโ€™t think itโ€™s a bad design to put security logic in the model. You host business logic there, and you can perhaps consider security logic as a kind of business logic. Of course, you donโ€™t want all this in the controller or in the view, you want to follow a skinny controller, a thick model .

Your models should stand alone as a single unit of application logic. You must completely control your models from the Rails console. In addition, the presence of security logic in the model facilitates the unit test.

+3
source

I would say it depends on whether your models are intended for direct access. If so, then there must be an awareness of security problems, possibly with mixin, since such problems are likely to be somewhat orthogonal to the main problems of the model.

If the models should be invisible, and you already have the security logic in your controllers, I would leave some models.

+1
source

All Articles