CanCanCan load_and_authorize_resource

问题描述 投票:0回答:1

我在1个问题中有两个问题

  1. load_and_authorize_resource在我的Pokemon控制器中不起作用。如果我理解文档load_and_authorize_resource应该阻止用户访问他们无权访问的路线/动作。这是控制器的代码:
class PokemonsController < ApplicationController
  load_and_authorize_resource

  def update
    if @pokemon.update_attributes(pokemon_params)
      flash[:success] = 'Pokemon was updated!'
      redirect_to root_path
    else
      render 'edit'
    end
  end


  def create
    @pokemon = Pokemon.new(pokemon_params)
    @pokemon.user_id = current_user.id
    @pokemon.trainer_id = Trainer.first.id

    if @pokemon.save
      flash[:success] = "Nice job! #{@pokemon.name} was created!"
      redirect_to pokemons_path
    else
      flash[:danger] = "Hmmm try that again."
      render :new
    end
  end

  def show
    @pokemon = Pokemon.find_by_slug(params[:slug])
  end

  def destroy
    if @pokemon.destroy
      flash[:success] = 'Congrats, you destroyed a pokemon😔'
    else
      flash[:warning] = 'I couldnt destroy this pokemon...'
    end
    redirect_to root_path
  end

  private

  def pokemon_params
    params.require(:pokemon).permit(
      :name,
      :pkmn_type,
      :level,
      :attack,
      :defense, 
      :speed, 
      :pokedex, 
      :sp_attack, 
      :sp_defense
    )
  end

end


这里是ability.rb模型:

class Ability
  include CanCan::Ability

  def initialize(user)
      user ||= User.new # guest user (not logged in)
      if user.admin?
        can :manage, :all
      else
        can :manage, Pokemon, user_id: user.id
        can :read, :all
      end
  end
end

我已经退出应用程序,因此没有current_user /会话,但是我仍然能够访问神奇宝贝的编辑视图。知道发生了什么吗?

问题2:我将如何调试它以备将来参考?

如果有帮助,这里是link to the repo。预先感谢😊

ruby-on-rails authorization ruby-on-rails-6 cancancan
1个回答
0
投票

我已经下载了您的仓库。首先,您的注册页面无法正常工作。没有必填的名字/姓氏字段。我认为您将来可以处理。关于您的问题,当我将您的子弹路由更改为默认ID路由时,cancancan可以正常工作。当我尝试编辑属于不同用户的神奇宝贝时,这是错误:

CanCan::AccessDenied - You are not authorized to access this page.:
Started GET "/pokemons/2/..." for ::1 at 2019-12-23 11:27:37 +0200

当我返回时,它会破坏这种行为,我可以编辑所有宠物小精灵。因此,问题不在CanCanCan中,而在slug的配置中。如果您不想更改默认路由或使用FriendlyId,建议您使用以下控制器操作:

  def edit
    @pokemon = Pokemon.find_by_slug(params[:slug])
    authorize! :edit, @pokemon
  end

注意:您必须删除行load_and_authorize_resource

[此配置在尝试编辑不属于用户的口袋妖怪时也会返回正确的错误:

enter image description here

希望我能有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.