繁体   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