railsで権限チェックをするgem pundit

railsではユーザ毎にアクセス件を設定したい場合はpunditというgemをよく使います。
導入は簡単です。

gem "pundit"

bundle install

続いてgeneratorをつかってpunditで使うクラスを生成します。

rails g pundit:install

これで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
end

では、権限を設定してみます。
試しにcommentモデルに対して権限を設定します。

class CommentPolicy < ApplicationPolicy
  def update?
    record.user == user ? true : false
  end

  def destroy?
    record.user == user ? true : false
  end
end

ここではcommentの更新処理と削除処理に対してユーザ情報をチェックしています。要するに投稿者本人かチェックしているという訳です。
あ、commentのテーブル構成はこんな感じです。

 create_table "comments", force: true do |t|
    t.string   "message"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "user_id"
    t.integer  "movie_id"
  end

で、後はcontrollerですが、こんな感じで書けます。

class CommentsController < ApplicationController
    include Pundit
 
    before_action :set_comment

    def show
    end

    def new
      @comment = Comment.new
    end

    def create
      @comment = Comment.new
    end

    def edit
      authorize @comment
    end

    def update
      authorize @comment
      ・・・・
      ・・
    end

    def set_comment
      @comment = Comment.find(params[:id])
      ・・・・
      ・・
    end
  end

こういうgemを使うとコードが整理されて綺麗になるなと思います。ので、使うべきですね。