简体   繁体   中英

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

Im using the Devise gem for authentications. I have already created an Admin model and added Devise to it. Normally anyone can register. But I need only an Admin to add new Admins to the system. How can I do that?

Actually, you can found your answer in devise wiki

First you should read this How To: Add an Admin Role , Option 2 is suitable for your case.

Adding an "super admin" attribute to your admin model with boolean type.

$ rails generate migration add_super_admin_to_users super_admin:boolean

If you're using postgresql/mysql for dbms, Don't forget before migration add default false to super_admin attibute

If you have "Super Admin" user on your database, and then you should customize admin registration pages, Devise::RegistrationsController . This customize devise regristration controller

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

And add authenticate_role! on your application_controller.rb looks like

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

Add this to your views/devise/registrations/new.html.erb

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

you go to db under this seed.rb file

you type your details

Role.create(name: 'Admin')

User.create(name: "admin", email: admin@ibc.com", password: "admin", password_confirm: "admin)

ad go to terminal type

$rake db:seed

and check database fields

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM