2017-01-25 51 views
1

我在我的Rails應用程序中使用CanCan gem,並且希望檢查當前請求是否是我應用程序中的受保護資源。檢查當前請求是否在使用CanCan的Rails中受到保護

因此,例如,我有以下幾點:

class AdminController < ApplicationController 

    load_and_authorize_resource 

end 

我如何檢查,如果該請求被慘慘保護?

我可以通過params訪問控制器和操作。我不能使用標準can?cannot?助手,因爲他們將檢查current_user是否具有權限,而不是動作本身是否具有保護。

因此,例如:

class ApplicationController < ActionController::Base 

    before_action :check_protected 

    def check_protected 
    if can? params[:action].to_sym, Object.const_get(params[:controller].classify) 
     # resource is protected 
    else 
     # resource is not protected 
    end 
    end 

end 

^^這是行不通的,因爲它總是會說false當沒有current_user或者如果用戶沒有權限。 我需要檢查資源本身是否受CanCan保護。

如果我有這些例子:

class PostsController < AdminController 

    def index 
    end 

end 

class HomeController < ApplicationController 

    def index 
    end 

end 

爲PostsController的指數應該是識別爲保護和未受保護的指標HomeController中。

+0

康康舞是一種用戶授權的寶石,目的是檢查用戶是否有訪問授權資源。它需要能力類和current_user方法才能工作。您可以按照[本頁](https://github.com/ryanb/cancan/wiki/changing-defaults)的說明覆蓋默認值。 – trueinViso

+0

@trueinViso我有一個'Ability'類和'current_user'方法。但是我想知道當前的控制器方法是否有附加的cancan屬性。 – Cameron

+0

控制器方法沒有附加任何cancan屬性。能力是在current_user上定義的。當你說skip_authorize_resource時,這意味着它不會檢查current_user是否可以訪問資源。 – trueinViso

回答

1

CanCan使用CanCan::ControllerResource#skip?方法來確定它是否應該授權資源。所以我猜你可能會依賴於它,如下所示:

def check_protected 
    if CanCan::ControllerResource.new(self).skip?(:authorize) 
     # resource is not protected 
    else 
     # resource is protected 
    end 
    end 

我已經在我的沙箱嘗試過了,它爲我工作

+0

獲取錯誤'未初始化的常量CanCan :: ControllerResouce',因此它總是認爲資源受到保護。 – Cameron

+0

語法可能會警惕,取決於您使用的CanCan版本 –

+0

它不再抱怨錯誤,但它仍然返回false,即使對它們有保護的資源也是如此。例如'self'返回'#',並且儀表板從我的AdminController繼承,該AdminController中有'load_and_authorize_resource'。 – Cameron

相關問題