How to handle before filter for specific action in Grape?
One way I could think of is to use route_setting
to add custom attributes for the routes you would want to by-pass auth for. Check for these attributes in the before filter before calling authenticate!
. Something like the below should work:
module Backend
module V1
class Users < Grape::API
include Backend::V1::Defaults
before { authenticate! unless route.settings[:auth] && route.settings[:auth][:disabled] }
resource :users do
desc "Return a user"
params do
requires :id, type: Integer, desc: 'User id'
end
get ':id' do
UsersService::Fetch.new(current_user,params).call
end
desc "Update a user"
params do
requires :id, type: Integer, desc: 'User id'
requires :display_name, type: String, desc: 'Display name'
requires :email, type: String, desc: 'Email'
end
post ':id' do
UsersService::Save.new(current_user,params).call
end
desc "Reset user password"
params do
requires :old_password, type: String, desc: 'old password'
requires :password, type: String, desc: 'new password'
end
post 'password/reset' do
PasswordService::Reset.new(current_user,params).call
end
desc "Forget password"
route_setting :auth, disabled: true
params do
requires :email, type: String
end
post 'password/forget' do
PasswordService::Forget.new(current_user,params).call
end
end
end
end
end
A dirty way to help would be by using namespace
, something like:
module Backend
module V1
class Users < Grape::API
include Backend::V1::Defaults
namespace :users do
desc "Forget password"
params do
requires :email, type: String
end
post 'password/forget' do
PasswordService::Forget.new(current_user,params).call
end
namespace do
before { authenticate! }
desc "Return a user"
params do
requires :id, type: Integer, desc: 'User id'
end
get ':id' do
UsersService::Fetch.new(current_user,params).call
end
desc "Update a user"
params do
requires :id, type: Integer, desc: 'User id'
requires :display_name, type: String, desc: 'Display name'
requires :email, type: String, desc: 'Email'
end
post ':id' do
UsersService::Save.new(current_user,params).call
end
desc "Reset user password"
params do
requires :old_password, type: String, desc: 'old password'
requires :password, type: String, desc: 'new password'
end
post 'password/reset' do
PasswordService::Reset.new(current_user,params).call
end
end
end
end
end
end
This way we wont run before filter for users/password/forget
but for the rest we will run before { authenticate! }