0

Good day, I am using the CanCanCan gem, an authorization library for Ruby on Rails which restricts what resources a given user is allowed to access. It is working however when users sign up, all of the options including 'admin' and 'banned' show up. I want to hide those two checkboxes and leave 'customer' and 'sitter'. How would I do that?

user.rb

class User < ActiveRecord::Base

  ROLES = %i[admin sitter customer banned]

  def roles=(roles)
    roles = [*roles].map { |r| r.to_sym }
    self.roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.inject(0, :+)
  end

  def roles
    ROLES.reject do |r|
      ((roles_mask.to_i || 0) & 2**ROLES.index(r)).zero?
    end
  end

  def has_role?(role)
    roles.include?(role)
  end

edit.html.erb

        <% for role in User::ROLES %>
          <%= check_box_tag "user[roles][#{role}]", role, @user.roles.include?(role), {:name => "user[roles][]"}%>
          <%= label_tag "user_roles_#{role}", role.to_s.humanize %><br />
        <% end %>
        <%= hidden_field_tag "user[roles][]", "" %>
      </div>
      </div>

https://github.com/CanCanCommunity/cancancan

achilles77
  • 325
  • 2
  • 3
  • 11

2 Answers2

0

Allowing users to set their own roles is probably a bad idea, even for non-privileged roles.

Just guessing by context, you're working on a childcare application, where users can sign up as customers or as sitters. You should set up your checkboxes manually, rather than building them based on your @roles array list, or you can create a @public_roles array for use in your views that only includes non-admin roles.

Finally, for some reason, you have a role called 'banned' which technically isn't a role -- it's a user state which should be dealt with separately.

MarsAtomic
  • 10,436
  • 5
  • 35
  • 56
0

In edit.html.erb replace for role in User::ROLES with for role in %i[customer sitter]

You should consider the possibility that a malicious user may also craft their own checkbox for one of the protected states (admin or banned). Make sure to build in protection to make sure users cannot set themselves to admin unless they are allowed to.

james246
  • 1,884
  • 1
  • 15
  • 28