Search code examples
ruby-on-railsrubydeviseruby-on-rails-6cancancan

When using cancancan with devise, does devise need to be added to ability.rb?


Question: when using cancancan for authorization and devise for authentication, do I have to define any authorizations for the devise part of the app, or does devise take care of everything itself?

Example

For example, for (all) other resources, we should place load_and_authorize_resource in the controller of that resource so that users who should not access it are prevented from doing so. Then, to allow access to those should have access, we can define abilities by adding code like this to ability.rb:

# ability.rb

can [:index, :show], [Patient], user_id: user.id

Back to my question - do I have to add load_and_authorize_resource to any of devise's controllers and define permissions for devise controllers in ability.rb? OR does devise take care of all that without the developer having to do anything?

We obviously don't want to allow one user to change another user's account info!


Solution

  • It's important to distinguish between devise authorization part of account info (session creation/logout/email+password+restoration/changing if you have that enabled) and any other custom logic and data related to it (for example - names, shoe sizes, whatever) that is kept inside or accesses the same model.

    Devise controllers, if you did not change them much - are very simple and do not need additional access control because by design user is only able to edit their own auth data (they simply do not handle user id from outside thus there's no way to tamper it). Moreover just adding load_and_authorize_resource will at least have no effect or more probably will interfere with existing devise code because it was not designed around cancancan.

    But if you have your own controllers for user profile(s), like user index, admin editing other's profiles etc - obviously, you have to facilitate access control there.