簡體   English   中英

在Rails中使用Devise Gem時如何讓admin只注冊新的管理員?

[英]In Rails when using the Devise Gem how to let only admin register new admins?

我使用Devise gem進行身份驗證。 我已經創建了一個Admin模型並添加了Devise。 通常任何人都可以注冊。 但我只需要一個管理員來添加新的管理員到系統。 我怎樣才能做到這一點?

實際上,你可以在設計維基中找到答案

首先,您應該閱讀如何:添加管理員角色 ,選項2適合您的情況。

使用布爾類型向管理模型添加“超級管理員”屬性。

$ rails generate migration add_super_admin_to_users super_admin:boolean

如果你正在使用postgresql / mysql for dbms,請不要忘記在遷移之前將default default false添加到super_admin

如果您的數據庫上有“超級管理員”用戶,那么您應該自定義管理員注冊頁面, Devise :: RegistrationsController 這個自定義設備注冊控制器

registrations_controller.rb

class RegistrationsController < Devise::RegistrationsController
  skip_before_filter :require_no_authentication
  before_filter :authenticate_user!, :authenticate_role!

  # GET /resource/sign_up
  def new
    super
  end

  # POST /resource
  def create
    super
  end

  protected

  def after_sign_up_path_for(resource)
    your_specific_path
  end

end

並添加authenticate_role! 在您的application_controller.rb看起來像

class ApplicationController < ActionController::Base
  protect_from_forgery


  protected
  def authenticate_role!
    if current_user.super_admin == true
      super
    else
      redirect_to another_path, notice: "You can't access this page"
    end
  end

end

將其添加到您的views/devise/registrations/new.html.erb

<div><%= f.label :super_admin %><br />
<%= f.check_box :super_admin %></div>

你去這個seed.rb文件下的db

你輸入你的詳細信息

Role.create(名稱:'Admin')

User.create(名稱:“admin”,電子郵件:admin@ibc.com“,密碼:”admin“,password_confirm:”admin)

廣告轉到終端類型

$ rake db:seed

並檢查數據庫字段

暫無
暫無

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

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