1

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!

stevec
  • 41,291
  • 27
  • 223
  • 311

1 Answers1

1

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.

Vasfed
  • 18,013
  • 10
  • 47
  • 53
  • Thanks for the great help. I have a complication in that I used a [custom controller](https://github.com/heartcombo/devise#configuring-controllers) very similar to how it's explained in the readme (i.e. a `user` controller). Do you know if that changes anything? – stevec Oct 24 '20 at 14:31
  • For reference, the changes I made were very simple, basically I wanted a user to [automatically become a Patient on sign up](https://stackoverflow.com/q/63515348/5783745), so I had to modify the user controller slightly to allow that, meaning my devise setup uses custom user controller – stevec Oct 24 '20 at 14:41
  • @stevec if only the code from accepted answer is added - that should not have any effect on security. But I should say, that if you're handling sensitive medical data - you'd better have someone experienced to audit your code, because it's nearly impossible to do in q&a format. – Vasfed Oct 24 '20 at 14:50
  • Thanks @vasfed, good advice, I'll definitely have it audited to be safe – stevec Oct 24 '20 at 14:59