如何隐藏用户授权的复选框

时间:2015-07-28 22:03:31

标签: ruby-on-rails ruby ruby-on-rails-4 rubygems cancancan

美好的一天,我正在使用CanCanCan gem,这是Ruby on Rails的授权库,它限制了允许给定用户访问的资源。但是当用户注册时,它会显示所有选项,包括“admin”和“banned”。我想隐藏这两个复选框,并留下'客户'和'保姆'。我该怎么做?

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

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分: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.