Pundit - 政策无法识别

时间:2015-08-20 22:26:43

标签: ruby-on-rails pundit

我正在实施专家,并希望将用户#edit和user#update actions限制为仅限current_user

db.ListLeftPushAsync(key, newWork);
sub.Publish(channel, "");

以下是我的政策,其中(a)不起作用,(b)不合逻辑。

def edit
  @user = current_user
  authorize(@user)
end

def update
  @user = current_user
  authorise(@user)
  if @user.update_attributes(user_params)
    flash[:success] = "Profile updated"
    redirect_to edit_user_path
  else
    render 'edit'
  end
end

我现在更新了我的UserPolicy,如下所示。我已将操作设置为false以进行测试,因为所有内容都已获得授权:

class UserPolicy

  attr_reader :user, :user

  def initialise(user, user)
    @user = user
  end

  def update?
    true
  end

  alias_method :edit?, :update?

end

但我的政策未得到承认。在进一步阅读后,我将以下内容添加到我的ApplicationController中:

class UserPolicy < ApplicationPolicy

  def new?
    create?
  end

  def create?
    false
  end

  def edit?
    update?
  end

  def update?
    false
    #user.id == record.id
  end

end

当我现在导航到我收到的用户#edit动作时:

after_filter :verify_authorized, except: :index
after_filter :verify_policy_scoped, only: :index

1 个答案:

答案 0 :(得分:1)

首先,确保你有......

你的应用内/应用/控制器/ application_controller.rb

class ApplicationController < ActionController::Base
  include Pundit
end

your-app / app / policies / application_policy.rb ,具有常规操作的默认权限。

class ApplicationPolicy
  attr_reader :user, :record

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

  def index?
    false
  end

  def show?
    scope.where(:id => record.id).exists?
  end

  def create?
    false
  end

  def new?
    create?
  end

  def update?
    false
  end

  def edit?
    update?
  end

  def destroy?
    false
  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

然后,在UserPolicy

您-应用程序/应用程序/政策/ section_policy.rb

class UserPolicy < ApplicationPolicy
  def edit?
    user.id == record.id
  end

  def update?
    edit?
  end
end

因此,默认情况下,user将是您当前的用户,record将是编辑和更新操作中定义的@user

您不需要明确调用authorize方法。 Pundit知道如何处理您的@user属性。所以,你的控制器应该是:

def edit
  user
end

def update
  if user.update_attributes(user_params)
    flash[:success] = "Profile updated"
    redirect_to edit_user_path
  else
    render 'edit'
  end
end

private

def user
  @user ||= User.find(params[:id])
end
  

如果您没有current_user方法,则必须知道,您需要在应用程序控制器中定义pundit_user