2014-04-17 80 views
1

在控制器中安全使用多個示波器。在控制器中安全使用多個示波器

在控制器中,我需要調用三個範圍之一。如何安全地做到這一點?

如果我發送參數scope=destroy_all這將刪除所有條目。

方法控制器:

​​

的範圍:

scope :ended, -> {where ("date(current_timestamp) - date(created_at) > ends_at")} 
scope :active, -> {where ("date(current_timestamp) - date(created_at) < ends_at")} 

在訪問量:

.btn-group 
    = link_to _('Ended Campaigns'), admin_campaigns_path(scope: :ended), class: 'btn btn-default' 
    = link_to _('Ob-going Campaigns'), admin_campaigns_path(scope: :active), class: 'btn btn-default' 
    = link_to _('All Campaigns'), admin_campaigns_path(scope: :all), class: 'btn btn-default' 
+1

不這樣做,我會做!它太不安全了,至少把before_filter設置爲僅允許'ended'或'active'作爲params [:scope]的可能值。 params [:scope] = nil除非['ended','active']。include?(params [:scope]) – arieljuod

+0

@arieljuod我對before_filter不瞭解,你能解釋一下嗎? – user3458697

+0

查看我的回答 – arieljuod

回答

1

這是一個過濾器之前

class YourController 
    before_filter :filter_scopes, only: :index 

    def index 
    @campaigns = Campaign.send(params[:scope] || 'all') 
    end 

    private 
    def filter_scopes 
    params[:scope] = nil unless ['ended','active'].include?(params[:scope]) 
    end 
end 

這樣可以幫助您確定只有「結束」,「積極」和「全部」呼叫範圍

1

您可以加入白名單的範圍,就像這樣:

@campaigns = if %w(ended active).include?(params[:scope]) 
       Campaign.public_send(params[:scope]) 
      else 
       Campaign.all 
      end 
+0

謝謝。不知何故,通過「強大的參數」來做到這一點? – user3458697

0

時是允許值,我認爲這是太不安全和神祕,以至於將範圍應用程序留給用戶輸入。

如下

def index 
    @campaigns = Campaign.all 
    if params[:scope] == 'ended' 
    @campaign = @campaign.ended 
    elsif params[:scope] == 'active' 
    @campaign = @campaign.active 
    end 
end