Zack Herbert
Zack Herbert

Reputation: 960

calling a helper on Grape API name space

Working with on an API using Grape API and was wondering if it was possible to call a function in the namespace before an api gets called. There are two ways that we validate permission within our API and instead of calling them in each API call I would like to do it in the namespace before hand.

api.rb looks a little something like this:

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

Is it possible to call authenticate! for a whole namespace like i have below instead of calling it in each api?

Upvotes: 0

Views: 1124

Answers (1)

Marlon
Marlon

Reputation: 898

You can just use a before block inside your namespace. Your code would be something like this:

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

The before block will be called before every call to your API.

Upvotes: 1

Related Questions