0

I am changing the value in session in an api controller, but it doesn't reflect next time the value of that variable in session is fetched. Here is the api-controller...

module Api
    module V0
        class RecommendationsApiController < ApplicationController

           def x
              r1 = session[:last_id]
              r2 = some_function(r1)
              session[:last_id] = r2 
              #doesn't reflect in the session next time this same function is called, and the old value is shown
              #though checking the value of session at this point shows the right value been set in the @delegate part of the session

           end
        end
    end
end

this is the session_store.rb

Application.config.session_store :cookie_store, key: '_session_name'

application_controller.rb

  protect_from_forgery

  after_filter :set_csrf_cookie_for_ng

  def set_csrf_cookie_for_ng
    cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery?
  end

  protected

  def verified_request?
    super || form_authenticity_token == request.headers['X-XSRF-TOKEN']
  end

this is websiteApp.run function.

var csrf_token = $cookies['XSRF-TOKEN'];
$http.defaults.headers.common['X-XSRF-TOKEN'] = csrf_token;

I tried to set the token inside config, but config block doesn't have $cookies. So tried to set headers inside run.

Please help out.

red-devil
  • 1,064
  • 1
  • 20
  • 34
  • Have you looked at the cookie in your browser to see whether the value is actually getting to the browser? That'll tell you whether the problem is the cookie not being set, or the cookie not being read. There are posts out there on how to decrypt session cookies – PaulL Sep 11 '14 at 02:54

1 Answers1

0

Did you turned of CSRF validation for that action? if not, what's probably happening is that rails is clearing the session for security reasons. You should only deactivate it for specific actions:

protect_from_forgery :except => :my_action

or in this case

protect_from_forgery :except => :x
apeniche
  • 659
  • 3
  • 8
  • I didn't turn it off. I have added the `application_controller.rb` to the question. What else can be the issue? – red-devil Sep 10 '14 at 11:29
  • I would get rid of the after filter in the application controller (if its not useful for its purpose), and in the RecommendationsApiController add the following line: 'skip_before_filter :verify_authenticity_token, :only => [:x]' – apeniche Sep 10 '14 at 14:32
  • Removing `after_filter` and adding `skip_before_filter` in `RecommendationApiController` does no good. Though this is the reason why I had to add these lines http://stackoverflow.com/questions/7600347/rails-api-design-without-disabling-csrf-protection.. What else can I do? – red-devil Sep 10 '14 at 19:32
  • Are you using AngularJS (is AngularJS making the API request)? – apeniche Sep 10 '14 at 19:40
  • Yes I am making an api request using angularjs. – red-devil Sep 10 '14 at 19:41