Rails 5 / Devise-以管理员身份删除用户

时间:2018-08-26 00:46:22

标签: ruby-on-rails ruby devise

我正在使用devise管理身份验证。我有一个User模型和Admin模型。我希望能够同时允许用户和管理员软删除用户帐户。

我已经为用户实现了软删除,并且一切正常,但是,为管理员添加功能会导致401 unauthorized并重定向到用户登录页面。我不确定如何解决这个问题。

到目前为止,我有:

config / routes.rb

...
devise_for :users
devise_scope :user do
  resources :users, only: [:destroy], controller: 'members/registrations', as: :user_registration do
    get 'cancel'
  end
end
...

controllers / members / registrations_controller.rb

class Members::RegistrationsController < Devise::RegistrationsController

  def destroy
    @user = User.find(params[:id])
    not_authorized unless authorized?
    @user.soft_delete
    user_post_destroy if is_current_user?
  end

  private

  def authorized?
    if signed_in?
      is_current_user?
    else
      session[:session_id] == @user.author_session_token
    end
  end

  def not_authorized
    flash[:error] = t('errors.messages.not_authorized')
    flash.keep
    redirect_back(fallback_location: root_path)
  end

  def user_post_destroy
    Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)
    set_flash_message :notice, :destroyed
    yield resource if block_given?
    respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name) }
  end

  def is_current_user?
    @user == current_user
  end

end

models / user.rb

...
def soft_delete
  update_attribute(:deleted_at, Time.current)
end

def active_for_authentication?
  super && !deleted_at
end

def inactive_message
  !deleted_at ? super : :deleted_account
end
...

0 个答案:

没有答案