2016-08-18 29 views
0

使用Grape API在API上工作,並想知道是否可以在調用api之前在名稱空間中調用函數。有兩種方法可以在我們的API中驗證權限,而不是在每個API調用中調用它們,我希望事先在名稱空間中執行此操作。在葡萄API名稱空間上調用助手

api.rb看起來有點像這樣:

Module MyModule 
    class API < Grape::API 
    . 
    . 
    . 
    helpers do 
     . 
     . 
     . 
     def authenticate! 
     raise CanCan::AccessDenied unless authenticated? 
     end 

     def authorize!(*args) 
     # Not a super user and trying to access the API of a company other than your own? 
     if !current_user.super_user? && current_user.company != @company 
      raise CanCan::AccessDenied 
     end 

     Ability.new(current_user, host_parts).authorize!(*args) 
     end 
    end 

    ################################################ 
    # Clerk API 
    namespace :clerk do 
     authenticate! 
     resource: myResource do 
     **API code here** 
     end 
    end 
    end 
end 

是否有可能調用驗證!對於像下面這樣的整個命名空間,而不是在每個API中調用它?

回答

1

您可以在命名空間內的塊之前使用塊。您的代碼將是這樣的:

Module MyModule 
    class API < Grape::API 
    helpers do 
     def authenticate! 
      raise CanCan::AccessDenied unless authenticated? 
     end 

     def authorize!(*args) 
      if !current_user.super_user? && current_user.company != @company 
       raise CanCan::AccessDenied 
     end 

     Ability.new(current_user, host_parts).authorize!(*args) 
     end 
    end 

    # Clerk API 
    namespace :clerk do 
     resource: myResource do 
      before do 
       authenticate! 
      end 
     end 
    end 
    end 
end 

以前塊將在每次調用您的API之前調用。