しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

punditというユーザーの権限管理をするGemを試してみる

ユーザーの権限管理をしてくれるGemを試してみました。

github.com

インストール

installはいつもどおりbundlerで行います。

gem "pundit"

初期設定

ApplicationControllerでPunditをincludeします。

pundit_userは後で登場するApplicationPolicyの初期化時に渡すパラメータです。
本来はcurrent_userが返るのですが、今回はユーザー作成は行っていないのでnilを返すようにする。

class ApplicationController < ActionController::Base
  include Pundit

  def pundit_user
    nil
  end
end

次に下コマンドで初期化をします。

rails g pundit:install

app/policiesフォルダが作られるのでそこに機能単位のポリシーをセットしていきます。

controllerへのアクセスを制限する

例えばCommentControllerへのアクセスを制御する場合を考えます。

まずは以下コマンドでcommentへのpolicyを作成します。

rails g pundit:policy comment

CommentPolicyにindex?メソッドを追加します。

class CommentPolicy < ApplicationPolicy
  def index?
    false
  end

  class Scope < Scope
    def resolve
      scope
    end
  end
end

この状態でCommentControllerのindexでauthorizeメソッドを呼んだ場合、CommentPolicy#index?メソッドがfalseを返すのでPundit::NotAuthorizedErrorというエラーになります。

class CommentsController < ApplicationController
  def index
    @comments = Comment.all
    authorize @comments
  end
end

f:id:llcc:20160105205631p:plain

CommentPolicy#index?の戻り値をtrueにするとエラーが起きなくなります。

controller以外で認証チェックを使う

例えばviewでのチェックをしたい場合は以下のようにします。

<% if policy(@comments).index? %>
<h1>Listing Comments</h1>
<% end %>

参考URL

railsで権限チェックをするgem pundit - nakaearthの日記
rails 4 対応の認可の gem - @znz blog
Rubyist Magazine - 権限管理のgem、Punditの紹介