Using Devise / Cancan / Rolify Together

I'm trying to set up an authorization / authentication system, and I'm confused, so I have a few questions:

  • In many tutorials, people customize HABTM user / role relationships. I understand that this allows each user to have several roles, but if you want each user to have only one role, is this necessary? If I have options for “active” and “inactive” users, be roles or something else?
  • The Cancan wiki says that if you want one user to have one role, you just have to make it an attribute and then use "can: manage ,: all if user.role ==" admin "", but that’s not so dangerous because every time "admin" is just a string? Is this the case? What is the best way to handle this?

I tried my best to read the documentation on all issues, and I started with this tutorial

http://railsapps.github.com/tutorial-rails-bootstrap-devise-cancan.html

although I also read http://starqle.com/articles/rails-3-authentication-and-authorization-with-devise-and-cancan-part-1/ and tonyamoyal.com/2010/09/29/rails-authentication -with-devise-and-cancan-part-2-restful-resources-for-administrators /

I just can't get it to work the way I want. How to do it?

+6
source share
1 answer

1. You do not need multiple roles or a role table

CanCan is independent of how you define roles in your application. You can just as easily have a role field in your user model.

As for the "active" and "inactive" users, you have two options. You can have a field for this status, or you can have a "inactive" role and consider any other role to be "active". It depends on what you mean by “active” and how you use this information in your application.

2. There is nothing wrong with keeping the user role in the string.

The fact that the role is stored as a string does not make it less secure. However, you must use attr_protected to prevent the mass assignment of a user role.

attr_protected :role 

Therefore, users will not be able to update their own roles.

+8
source

Source: https://habr.com/ru/post/917375/


All Articles