Check for the existing of a header attribute in rails before invoking an action
Asked Answered
H

3

6

I am building an API in rails 4. Before invoking an action, I am trying first to check whether an attribute exist in the http header. Is there a way to do that instead of checking each in all actions of the controllers. The rails documentation mentions something like

constraints(lambda { |req| req.env["HTTP_CUSTOM_HEADER"] =~ /value/ }) do
  #controller, action mapping
end

but I still want to give the user consuming my API a feedback. something like sending a json with a message stating: missing the custom attribute in the header

Habit answered 5/9, 2015 at 12:2 Comment(0)
S
7

You can add before_action to the controller and check a header attribute, for example:

class SomeController < ApplicationController
  before_action :render_message, unless: :check_header

  def check_header
    request.env["HTTP_CUSTOM_HEADER"] =~ /foo/
  end

  def render_message
    render json: { message: "missing the custom attribute in the header" }
  end
end

If check_attribute filter returns nil, then render_message action render desired message.

Saudra answered 5/9, 2015 at 12:13 Comment(2)
I have many controllers and I don't want to use that in each controller. I basicaly have 4 controllers and each one of them has to do this checkingHabit
ok, thanks, I think adding your code to the action controller will work perfectly. thanks for the inspiration :)Habit
A
1

You can check controller actions using before_action filter:

For example in APIController:

class APIController < ApplicationController
  before_action :check_headers

  private

  def check_header
    # do whatever is required here
  end
end
Ahem answered 5/9, 2015 at 12:18 Comment(0)
E
0

If the header existence acts as an authentication mechanism there is no point to hit backend for that, try to avoid it earlier on reverse-proxy side:

nginx.conf

server {
  location / {
    if ($http_x_custom_header) {
      return 200 'missing the custom attribute in the header'; 
    }
    proxy_pass...
  }
}
Egomania answered 8/9, 2015 at 19:4 Comment(2)
well since I am building an api for that, I would not want to do that as the api might get changed in the next versions. I still want to have full controll in my code baseHabit
Ok, makes sense to have the header detection on application layer if it behaves beyond than simple check and may change laterEgomania

© 2022 - 2024 — McMap. All rights reserved.