2016-08-18 13 views
0

Grape APIを使用してAPIを操作し、apiが呼び出される前にネームスペース内の関数を呼び出すことが可能かどうか疑問に思っていました。私たちのAPI内でパーミッションを検証する方法は2つあり、それぞれのAPI呼び出しで呼び出すのではなく、事前にネームスペースで行いたいと思います。Grape APIネームスペースでヘルパーを呼び出す

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.rbは、このような小さなものになります!私は以下のように全体の名前空間の代わりに各APIでそれを呼び出すのですか?

答えて

1

ブロックの前にを使用することができます。 前のブロックがあなたのAPIへのすべての呼び出しの前に呼び出されます

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 

:あなたのコードは次のようなものになるだろう。

関連する問題