2015-08-14 14 views
2

動作之前的導軌對於設置控制器中多個動作共享的變量似乎很有用。使用rails before_action如何防止惡意用戶創建/更新/編輯和刪除

但是,不是我們通常在教程中看到的set_post的默認實現是否適用於惡意用戶的攻擊?

如果我們把這樣的控制器:

PostsController < Application Controller 
    before_action :set_post , only: [:show,:create,:update] 

    def show 
    ... 
    end 

    def create 
    ... 
    end 

    def update 
    ... 
    end 

    private 
    def set_post 
    @post = Post.find(params[:id]) 
    end 
end 

當用戶所提供的機會來更新例如將他們生成表單後,並在後,則params [:編號]會包含適當帖子的ID - 可能由current_user擁有。

但是,對於惡意用戶來說,修改posted:id變量並不難,因爲他們實際上最終會在控制器中設置@post變量來代表不同的帖子,而不是原來的更新。

我可以看到這是更安全:

private 
def set_post 
    @post = Post.find(params[:id]) 
    if(@post.user_id != current_user.id) 
    redirect_to homepage, alert: "you can edit your own posts" 
    end 
end 

但是 - 這將阻止其他用戶查看其他人的帖子!因此,如何進行這種檢查以確保只有特定職位的所有者才能更新/編輯它。那是後話,更新控制器動作與這樣的檢查處理本身:

def update 
    if @post.user_id != current_user.id 
    redirect_to homepage, alert: "you can edit your own posts" 
    end 
    ... 
end 
+0

對於政策的邏輯,你可以使用寶石權威人士或cancancan。 – Gearnode

回答

3

你是對的,我居然看到正在取得安全問題經常被新手程序員的Rails。他們只是生成腳手架,不會改變他們的需求。

我使用的是像在我的控制器以下幾點:

before_action :set_post 
before_action :check_post_ownership, except: :show 

private 

def set_post 
    @post = Post.find(params[:id]) 
end 

def check_post_ownership 
    redirect_to homepage, alert: "..." unless @post.user_id == current_user.id 
end 
+0

好吧,很高興知道其他人正在進行這種檢查。 – RenegadeAndy

+0

過濾器 - 而不是before_action? – RenegadeAndy

+1

'before_action'實際上更好,我會改變我的答案。沒什麼大不了的,只是最近的命名趨勢。兩者都在做完全相同的事情。 – EugZol

相關問題