Rails設定權限套件-pundit

tingyiiii
tingyiiii
Published in
Dec 15, 2020

凡走過必留下痕跡,邊複習邊想記錄使用這些套件的步驟及過程!

套件名稱:pundit

功能:為專案加上設定權限(廢話XD

  1. 在專案Gemfile檔加入下面的這行並執行bundle install安裝套件
gem "pundit"

打好存檔後別忘了在終端機執行下面指令:

$ bundle install

2. 接著在app/controllers/application_controller.rb檔中引入套件來使用

# app/controllers/application_controller.rbclass ApplicationController < ActionController::Base  include Pundit  ...end

3. 在終端機可以執行以下指令,會生成app/policies/的資料夾及下面會有application policy的檔案可以看到套件預設的一些設定

$ rails g pundit:install

4. 之後就可以在app/policies/資料夾裡新增需要的Policy檔案

例如官方文件提供的範例:

# app/policies/post_policy
# 讓此類別去繼承ApplicationPolicy也就是步驟3所生成的檔案
# 進去此檔案會看到裡面有定義了user / record使用
class PostPolicy < ApplicationPolicy
def update?
user.admin? or not record.published?
end
end

此時user => current_user

record=>在controller使用這套件的authorize方法時代入的變數(舉例這裡應該是會呼叫@post等等看下面範例

而update?方法也會在某個要使用的controller中有同名方法 => update

白話文翻譯上面這段code就是如何可以執行update這方法?

除非user.admin?=true或是not record.published? = true就可以執行

再翻一步就是current_user.admin?=true或是not @post.published? = true

接著讓就是在controller中使用:

# app/controllers/posts_controller.rbdef update
@post = Post.find(params[:id])
# 使用套件提供的authorize,後面接會帶入的record引數
authorize @post

if @post.update(post_params)
redirect_to @post
else
render :edit
end
end

承上官方文件範例就會在posts_controller中有個對應的update方法~

在這中加上authorize @post 這行,authorize是套件提供的方法,後面帶會帶入record的引數@post,這樣就大功告成啦~(通過我們在policy檔案中設定的條件才會有權限執行這方法!!!

那如果我的controller檔中沒有同名對應的方法也可以設定嗎?

可以的~~~在官方文件中也有說明!!

# 如果是在同名的方法我們會用以下
authorize @post
# 那如果是在不同名的方法但想用同套權限設定也可以在authorize代入第2個引數,指引它去找我們在policy檔中的update?方法
authorize @post, :update?

Happy Coding ༼•̃͡ ɷ•̃͡༽

--

--