2016-10-03 72 views
0

我有兩個名爲Post和PostComment的模型。 目前,我用hidden_field形式助手發送額外的數據,如後一次,評論海報和後ID上的評論正在取得這樣的用戶ID:Rails將額外參數傳遞給請求而不使用hidden_​​field標記

<%= f.hidden_field :posttime, value: Time.now.getutc %> 
<%= f.hidden_field :post_id, value: @post.id %> 
<%= f.hidden_field :user_id, value: current_user.id %> 

點擊它晚了,我認爲我可以使用瀏覽器的檢查員更改這些值,因此這是安全漏洞。那麼如何安全地發送這些參數?

回答

1

通常這些值不是通過表單傳遞,而是通過使用嵌套的URL網址進行訪問(讀取怎麼會在這裏:http://guides.rubyonrails.org/routing.html

例如使用post_id形式的網址,你會設定您的評論路線包括帖子,例如,您將擁有new_post_comment_path,並且在您的控制器中,您可以訪問params[:post_id]而不通過表單。

你的形式將成爲這樣的事情:

<% form_for [@post, Comment.new] do |f| %> 
    ... 

重:user_id - 絕對不傳遞的形式,你說的很對,這是一個很大的安全隱患(人們可以添加評論對於其他人!)只需通過您的控制器中的身份驗證方法(即current_user)訪問它。

你會最終在你的控制器例如是這樣的:

def create 
    @post = Post.find(params[:post_id]) 
    @comment = @post.comments.new(comment_params) 
    @comment.user = current_user 
    if @comment.save 
    redirect_to [@post, @comment] 
    else 
    render_action :new 
    end 
end 

private 

# Don't forget to use require/permit to make sure the user can't 
# fake up the user/post id fields themselves out of whole-cloth 
def comment_params 
    # or whatever your permitted comment-fields are. 
    params.require(:comment).permit(:content) 
end 
+0

感謝許多清算事情爲我。我不知道'post_id'參數會自動傳遞,現在它更有意義。由於我使用的是設計,不應該是'@post_comment.user_id = current_user.id'(這意味着你的代碼行是錯誤的或者至少不遵循約定) –

+0

只要你有一個'belongs_to:user '在'Comment'模型中,你可以使用'user'或'user_id',他們都會正常工作:) 如果你有一個或者另一個驗證 - 使用帶驗證的驗證...(例如'validates_presence_of:user_id'意味着你應該更喜歡'@comment.user_id = current_user.id') –

+0

太好了!由於我們在控制器本身的用戶標識中進行了歸檔,並且我確定該表單僅在用戶登錄時纔可見,因此不需要「validates_presence_of:user_id」權限? –

1

Time.now.getutccurrent_user.id已經可以在你的createupdate方法的應用,所以你並不真的需要通過那些回來。至於@post.id你可以只存儲在您的newedit方法會話變量...

session[post_id] = @post.id 

,然後在你的create或`更新方法...

@post_comment.post_id = session[:post_id] 
+0

我完全沒有想到'Time.now.utc'可以在控制器內部使用。感謝您發現它。 –

相關問題