灿灿灿 load_and_authorize_resource

CanCanCan load_and_authorize_resource

我在 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 如果它有帮助的话。提前致谢

我已经下载了你的代码库。首先,您的注册页面无法正常工作。没有 first/last 姓名字段是必填项。我认为您将来可以处理它们。 你的问题呢,当我将你的 slug 路由更改为默认 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

当我返回 slug 时,它打破了这种行为,我可以编辑所有的口袋妖怪。 所以问题不在 CanCanCan 中,而是在 slug 的配置中。如果您不想更改默认路由或使用 FriendlyId,我建议您使用这样的控制器操作:

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

注意:您必须删除行 load_and_authorize_resource

此配置还 returns 更正了尝试编辑不属于用户的宠物小精灵时的错误:

希望能帮到你一点点。