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

4

2 回答 2

0

允许用户设置自己的角色可能是个坏主意,即使对于非特权角色也是如此。

只是根据上下文猜测,您正在开发一个托儿应用程序,用户可以在其中注册为客户或保姆。您应该手动设置您的复选框,而不是根据您的@roles数组列表构建它们,或者您可以创建一个@public_roles仅包含非管理员角色的数组以供在您的视图中使用。

最后,由于某种原因,您有一个名为“banned”的角色,从技术上讲,它不是一个角色——它是一个用户状态,应该单独处理。

于 2015-07-28T22:16:38.443 回答
0

在 edit.html.erb 替换for role in User::ROLESfor role in %i[customer sitter]

admin您应该考虑恶意用户也可能为一种受保护状态(或banned)制作自己的复选框的可能性。确保建立保护以确保用户无法设置自己,admin除非他们被允许。

于 2015-07-28T22:17:05.547 回答