how to set role in rails :::: https://altalogy.com/blog/rails-6-user-accounts-with-3-types-of-roles/
https://altalogy.com/blog/rails-6-user-accounts-with-3-types-of-roles/
Authorization – CanCanCan
We use CanCanCan gem to restrict access to some parts of the app. Whatsmore, we grant different permissions for specific roles. Add to Gemfile:
gem 'cancancan'Run:
$ bundle installNext, use this command to generate ability class:
$ rails g cancan:abilityYou can define abilities in app/models/ability.rb. But first, we have to set different roles. It’s up to you how you want to define roles. We will use three roles: superadmin, supervisor, and user. We add three boolean columns for each role in the user model. Let’s start by generating migration:
$ rails generate migration add_roles_to_users superadmin_role:boolean supervisor_role:boolean user_role:booleanBefore we run the migration, let’s edit it. Open db/migrate/xxx_add_roles_to_users.rb and adjust the code:
class AddRolesToUsers < ActiveRecord::Migration[5.2] def change add_column :users, :superadmin_role, :boolean, default: false add_column :users, :supervisor_role, :boolean, default: false add_column :users, :user_role, :boolean, default: true endendWe’ve defined default values for superadmin and supervisor as a false, and true default value for user_role. Now we can run:
$ rake db:migrateTo verify current user’s role, you can use:
current_user.superadmin_role?current_user.supervisor_role?current_user.user_role?Views
To display some elements only for users with a specific role, you can use:
<% if current_user.superadmin_role? || current_user.supervisor_role? %> <p>Visible only for superadmins and supervisors! </p><% end %>Or you can use CanCanCan abilities:
<% if can? :manage, User %> <p>Visible only for superadmins and supervisors! </p><% end %>And in app/model/ability.rb:
class Ability include CanCan::Ability def initialize(user) # Define abilities for the passed in user here. For example: user ||= User.new # guest user (not logged in) if user.superadmin_role? can :manage, :all end if user.supervisor_role? can :manage, User end endend
Controllers
To authorize user access to controller’s actions, let’s add the following to a specific controller:
load_and_authorize_resourceIt will use a before action to load the resource into an instance variable and authorize it for every action.
Next, let’s modify app/model/ability.rb:
user ||= User.new # guest user (not logged in)if user.superadmin_role? can :manage, :all can :access, :rails_admin # only allow admin users to access Rails Admin can :manage, :dashboard # allow access to dashboardendif user.supervisor_role? can :manage, Userend
Comments
Post a Comment