【问题标题】:Pundit - authorize not being called, but no error is being thrownPundit - 授权不被调用,但没有抛出错误
【发布时间】:2018-07-04 04:41:38
【问题描述】:

我正在使用权威人士进行授权。它没有按预期工作,但是在调用 authorize 时不会抛出任何错误来表示没有方法。

规格:

it "should let a user destroy their own picture" do
  sign_in(user2)
  expect do
    delete :destroy, { id: p1.id }
    expect(response.status).to eq(200)
  end.to change { Picture.count }.by(-1)
end

it "should not let a user delete another user's picture" do
  sign_in(user2)
  expect do
    delete :destroy, { id: p1.id }
    expect(response.status).to eq(403)
  end.to change { Picture.count }.by(0)
end

应用控制器:

class ApplicationController < ActionController::Base
  ...
  include Pundit
  rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized
  ...
end

图片控制器:

class PicturesController < ApplicationController
  def destroy
    @picture = Picture.find_by_id(params[:id])
    authorize(@picture)
    @picture.destroy
    redirect_to pictures_path
  end
end

应用策略

class ApplicationPolicy
  attr_reader :user, :record

  def initialize(user, record)
    @user = user
    @record = record
  end

  def scope
    Pundit.policy_scope!(user, record.class)
  end

  class Scope
    attr_reader :user, :scope

    def initialize(user, scope)
      @user = user
      @scope = scope
    end

    def resolve
      scope
    end
  end
end

图片政策

class PicturePolicy < ApplicationPolicy
  def destroy?
    @user&.id == @record&.user_id
  end
end

当我使用authorize(picture) 行运行测试时,两者都不会被破坏,没有它,两者都会被破坏。在 PicturePolicy#destroy? 中添加一些 put 语句时,它们不会显示。如果我添加一个ApplicationPolicy#destroy?,它似乎也没有被调用。但是,当我将 authorize(obj) 添加到我的控制器时,在运行该代码之后什么都没有,policy#authorize 也没有运行,但返回了 200。

知道我在这里缺少什么吗?

【问题讨论】:

    标签: ruby-on-rails pundit


    【解决方案1】:

    发现问题。我在一个不存在的 ruby​​ 版本中使用了安全访问 &amp;.。删除它修复了它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-26
      • 2017-10-12
      • 1970-01-01
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-22
      • 1970-01-01
      相关资源
      最近更新 更多