Rails 4 Devise Strong Parameters Admin Model

2019-03-02 12:20发布

I have made a user and admin model using devise. I have used strong parameters in the app/controllers/application_controller.rb file

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  before_filter :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation, :remember_me) }
    devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:login, :password, :remember_me) }
  end

end

How do I whitelist the admin model?

devise_parameter_sanitizer.for(:sign_in) { |a| a.permit(:login, :password, :remember_me) }

Also how do I whitelist the admin sign_up so that no variables may be passed into it? My guess is

devise_parameter_sanitizer.for(:sign_up) { |a| a.permit()}

UPDATE

I would like to edit my question.

My question is how do I get the admin model to automatically blacklist my admin sign up page? If I simply leave nothing then I can still sign up through the "admins/sign_up". Sure I can delete the :regisitrations within the "app/models/admin.rb", but I would like to deny command line sign ups

--Would it be wise to use scoped views and specifically define each view for the admin and user models?--

1条回答
趁早两清
2楼-- · 2019-03-02 12:37

If you have separate controllers for users and admins then try something like this:

def configure_permitted_parameters
  if params[:controller] == "user"
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation, :remember_me) }
    devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:login, :password, :remember_me) }
  else
    devise_parameter_sanitizer.for(:sign_in) { |a| a.permit(:login, :password, :remember_me) }
    devise_parameter_sanitizer.for(:sign_up) { |a| a.permit()}

and there's another approach to it as well, create only one controller for both users and admin, named registrations_controller.rb, have a field in your users table named is_admin and set it for a user only if he/she is a admin. Create a seed to make your admins like this in your seeds.rb file:

admin_user = User.new(email: "abc@xyz.com", password: "123", password_confirmation: "123", is_admin: "true" )
admin_user.skip_confirmation!
admin_user.save
查看更多
登录 后发表回答