Ruby On Rails before_filter called twice?

When I send an ajax request to my ruby controller, the before_filter function seems to be called twice for each ajax request. I use the before_filter for authentication.

The ajax request I use:

 $.ajax({
    type: 'GET',
    url: 'URL_TO__RoR_Controller',
    username: username,
    password: password,
    contentType: "application/json; charset=utf-8",
    success: function(data){
      console.log(data);
    },
    error: function(xhr, ajaxOptions, thrownError) {
      console.log(arguments);
    }
  });

The RoR code:

class Api::MyController < ApplicationController
before_filter :authenticate
attr_reader :current_user

def authenticate
print "===================================n"
authenticate_or_request_with_http_basic do |username, password|
  print "n--------------------------------n"
  print username, password
  print "n--------------------------------n"
  @current_user = User.authenticate(username, password)
  print "===================================n"
end
end

def show
 print "=================IN SHOW=================="
end
end

The RoR response to the ajax request:

Started GET "URL_TO__RoR_Controller" for 127.0.0.1 at 2015-10-08 10:18:18 +0200
Processing by Api::MyController#show as JSON
  Parameters: {"id"=>"show", "test"=>{}}
===================================
===================================
Filter chain halted as :authenticate rendered or redirected
Completed 401 Unauthorized in 1ms (ActiveRecord: 1.0ms)


Started GET "URL_TO__RoR_Controller" for 127.0.0.1 at 2015-10-08 10:18:19 +0200
Processing by Api::MyController#show as JSON
  Parameters: {"id"=>"show", "test"=>{}}
===================================

--------------------------------
USERPASS
--------------------------------
  User Load (0.2ms)  SELECT `users`.* FROM `users` WHERE `users`.`authorized` = 1 AND `users`.`login` = 'USER' LIMIT 1
===================================
=================IN SHOW==================
  Rendered URL_TO__RoR_Controller/show.json.rabl (0.8ms)
Completed 200 OK in 30ms (Views: 3.4ms | ActiveRecord: 1.7ms)

So basically the authenticate function seems to be executed twice for each ajax request I send. The first time authentication seems to fail. It doesn’t even get in the authenticate_or_request_with_http_basic function. The second time everything seems fine.

Obviously this is not the desired behaviour. What is causing this problem?


Source: ruby

Leave a Reply