punditを使ってみる

punditとは

punditは認証系のgemの一種であり、対象のリソースに対して何を(誰を)許可するのかを定義することができます。

punditをインストー

gem 'pundit'

$ bundle install

punditの初期設定

app/controllers/application_controller.rbにPunditをincludeする。
(対象controllerの継承元でpunditをincludeしておく。)

include Pundit

$ rails g pundit:installを実行すると、app/policiesディレクトリが作成されます。

例えばhogehogeコントローラーへのアクセス制御を掛けたいとき、
$ rails g pundit:policy hogehogeを実行し、policyファイルapp/policies/hogehoge_policy.rbを作成されます。

認証に失敗する

hogehoge_controller.rbのindexアクションで、authorize貼ってみる。

# コントローラーのindexアクションにてauthorizeメソッドを呼び出す
def index
  authorize HogeHoge
end

# app/policies/hogehoge_policy.rbでindexをfalse(認証拒否)にしておく
class HogeHogePolicy < ApplicationPolicy
  def index?
    false
  end

認証拒否しておくとPundit::NotAuthorizedErrorが発生します。

認証に成功する

# hogehoges_controller
def index
  authorize HogeHoge
end

def new
  @hogehoge = HogeHoge.new
  authorize @hogehoge
end

def create
  @hogehoge = HogeHoge.new(permitted_attributes(HogeHoge))
end

def update
  @hogehoge = HogeHoge.find(params[:id])
  @hogehoge.update(permitted_attributes(@hogehoge))
end

policy(:hogehoge).fugafuga?(引数)




# app/policies/hogehoge_policy.rb
class HogeHogePolicy < ApplicationPolicy
  # indexアクション時のuser権限を確認しています。
  def index?
    user.staff? || user.admin?
  end

  # create, editアクションを実行できるかをチェックしています(newができればcreateもできる、editができればupdateもできる)
  def new?
    create?
  end

  def edit?
    update?
  end

  # 独自でメソッドを作ることもできる
  def fugafuga?(引数)
  end

  private
    # pundit側でストロングパラメータを設定できる
    def permitted_attributes
      [:strong_parameterA, :strong_parameterB]
    end 
end