簡體   English   中英

Rails 5,Rolify-角色分配策略

[英]Rails 5, Rolify - Role Assignment Strategy

我不太擅長學習編碼。 我已經嘗試了4年,但仍在努力找出基本概念。

我還沒有找到正確的起點,所以我一直在填補可能是基礎的東西的空白,但我還不知道。

我有一個Rails 5應用程序。 它具有用於用戶,角色,app_roles和assign_roles的模型。

關聯是:

用戶

rolify strict: true # strict means you get true only on a role that you manually add
  attr_accessor :current_role
belongs_to :organisation

角色

has_and_belongs_to_many :users, :join_table => :users_roles

  belongs_to :resource,
             :polymorphic => true,
             :optional => true

AppRole

[無關聯]注意:這是我用來擁有CRUD來定義角色的資源,應用程序可以使用該角色來為用戶分配角色。

分配角色

[無關聯]注意:這是我用來允許某些用戶向其他用戶分配角色的資源。

組織

has_many :users

我正在使用rolify寶石。

我的用戶模型有:

class User < ApplicationRecord
  rolify strict: true # strict means you get true only on a role that you manually add
  attr_accessor :current_role

我的角色表具有:

class Role < ApplicationRecord
  has_and_belongs_to_many :users, :join_table => :users_roles

  belongs_to :resource,
             :polymorphic => true,
             :optional => true

  validates :resource_type,
            :inclusion => { :in => Rolify.resource_types },
            :allow_nil => true

  scopify
end

在我的assign_roles控制器中,我有:

  class Users::AssignRolesController < ApplicationController

  before_action :authenticate_user!

  def index
    # if @current_user.is_admin?
      @app_roles = AppRole.all
    # else
    #   @app_roles = AppRole.where(category: relevant_category)
    # end

    # if @current_user.is_admin?
        @users = User.all
   #  else 
      #   @users = current_user.organisation.users.select { |u| u.id != current_user.organisation.owner_id }
    # end  
  end


  def create
    user = User.find(params[:users])
    role = AppRole.find(params[:roles])
    # organisation = Organisation.first
    # @organisation = Organisation.find(@current_user.organisation)
     # byebug

    user.add_role role.display_name, @current_user.organisation

    flash[:notice] = "Successfully created"
    redirect_to action: :index
  end

  def show
    # @users = User.joins(:profiles).where('profiles.organisation_id = ?' @current_user.organisation.id)
    # @users = User.all
    @current_user.organisation.users
  end

  def update
  end

  def destroy

    user = User.find(params[:users])
    # role = AppRole.find(params[:roles])
    assigned_role = user.roles
    # user_roles = user.roles
    # organisation = Organisation.first
    # byebug

    user.remove_role assigned_role.name, @current_user.organisation

    flash[:notice] = "Successfully created"
    redirect_to action: :index
  end

end

在我的路線文件中,我有:

resources :users, shallow: true do
    scope module: :users do
      resources :assign_roles
      resources :identities
    end
  end 

在我的視圖/用戶/ assign_roles /索引文件中,我有:

<%= form_tag(url: '/assign_roles', method: :post ) do |f| %>
    <div class="row" style="margin-top:50px; margin-bottom: 150px">
    <div class="col-md-3 col-md-offset-1">
       <%= select_tag "users", options_from_collection_for_select(@users, "id", "full_name"), { class: "chosen-select form-control" } %>
    </div>

                        <!-- # roles -->

    <div class="col-md-3 col-md-offset-1">
        <%= select_tag "roles", options_from_collection_for_select(@app_roles, "id", "display_name"), :class => 'chosen-select form-control' %>
    </div>

    <div class="col-md-3 col-md-offset-1">
        <div class="form-actions">
            <%= submit_tag(value = "Submit") %>
        </div>
    </div>
</div>
<% end %>

到目前為止,一切看起來還可以。 我被困在下一部分。

在我的觀點/用戶/assign_roles/show.html.er中

我試圖在視圖上顯示每個用戶的角色。 我希望分配了所有現有角色的用戶能夠刪除它們。

我有:

<% @users.each do |user| %>

      <td><%= user.roles.count %></td>
       <% user.roles.each do |role| %>
           <td><%= role.name.titleize %></td>
            <td><%= link_to 'Destroy', role, method: :delete, data: { confirm: 'Are you sure?' } %></td>
         <% end %>
    <% end %>

我的Assign_roles控制器保存在app / controllers / users文件夾中。 我的用於分配角色的views文件夾保存在app / views / users / assign_roles中

當我嘗試使用app / users / 4 / assign_roles表單時,我得到了要呈現的表單以及可分配的AppRoles列表。 我沒有收到任何錯誤消息。 相反,我會收到有關成功創建的通知。 但是,當我嘗試檢查用戶是否具有角色時,我得到了錯誤消息。

我可以看到服務器日志如下:

Started POST "/users/4/assign_roles?method=post&url=%2Fassign_roles" for ::1 at 2016-10-23 11:50:11 +1100
Processing by Users::AssignRolesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"U80gMQd01SaTcHHnnSFxvRc2u9JvJMFB+5smS9SaN8ZRixQvJRTMbutG0KkoqXL+oMU1aOxX8AURBtuy2Rm5yA==", "users"=>"4", "roles"=>"3", "commit"=>"Submit", "method"=>"post", "url"=>"/assign_roles", "user_id"=>"4"}
  User Load (0.8ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 4], ["LIMIT", 1]]
  User Load (0.5ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 4], ["LIMIT", 1]]
  AppRole Load (0.2ms)  SELECT  "app_roles".* FROM "app_roles" WHERE "app_roles"."id" = $1 LIMIT $2  [["id", 3], ["LIMIT", 1]]
  Organisation Load (0.4ms)  SELECT  "organisations".* FROM "organisations" ORDER BY "organisations"."id" ASC LIMIT $1  [["LIMIT", 1]]
  Role Load (1.1ms)  SELECT  "roles".* FROM "roles" WHERE "roles"."name" = $1 AND "roles"."resource_type" = $2 AND "roles"."resource_id" = $3 ORDER BY "roles"."id" ASC LIMIT $4  [["name", "sdfddd"], ["resource_type", "Organisation"], ["resource_id", 1], ["LIMIT", 1]]
   (0.2ms)  BEGIN
   (0.1ms)  ROLLBACK
  HABTM_Roles Load (0.4ms)  SELECT "users_roles".* FROM "users_roles" WHERE "users_roles"."user_id" = $1  [["user_id", 4]]
  Role Load (0.3ms)  SELECT  "roles".* FROM "roles" WHERE "roles"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
   (0.5ms)  SELECT "roles".id FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1  [["user_id", 4]]
  Role Load (0.3ms)  SELECT "roles".* FROM "roles" WHERE "roles"."id" = 1
  Role Load (0.4ms)  SELECT "roles".* FROM "roles" INNER JOIN "users_roles" ON "roles"."id" = "users_roles"."role_id" WHERE "users_roles"."user_id" = $1  [["user_id", 4]]
Redirected to http://localhost:3000/users/4/assign_roles
Completed 302 Found in 33ms (ActiveRecord: 6.5ms)

我不知道ROLLBACK行的含義,但是我認為正常運行時通常不會出現在這些日志消息中。

誰能看到我需要做些什么才能使角色分配正常工作?

組織模式

class Organisation < ApplicationRecord

  include LogoUploader[:logo]
  include BannerUploader[:banner]


  # --------------- associations

  has_many :users

  # --------------- scopes




  # --------------- validations


  # --------------- class methods

  enum org_type: {
                    University: 1,
                    Publicly_Funded_Research_Organisation: 2,
                    Industry: 3,
                    Grantor: 4,
                    Investor: 5,
                    Policy: 6,

                  }



  # --------------- callbacks

  # --------------- instance methods

  # --------------- private methods



end

resourcify添加到您的組織模型中,然后嘗試。

除了開發我們自己的RBAC(基於角色的訪問控制)以外,rails社區中已經有一些開源的gem。 我們可以利用它。

它是一個不錯的寶石

https://github.com/nathanl/authority

也有很多其他的寶石

https://www.ruby-toolbox.com/categories/rails_authorization

如果以上所有寶石都不滿足您的需求,那么至少可以將其用作開發的樣本模型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM