1

I recently added a piece of code to my ApplicationController to set the timezone of the current block to the one specified by the user.

class ApplicationController < ActionController::Base
  around_action :set_time_zone, if: :current_user
  protect_from_forgery with: :exception

  private

  def set_time_zone(&block)
    Time.use_zone(current_user.time_zone, &block)
  end
end

For some reason when I try to sign in i get a

ActionController::InvalidAuthenticityToken in Devise::SessionsController#create

If i remove

around_action :set_time_zone, if: :current_user

I can sign in and if i add it back after I sign in, everything works as expected.

Any ideas?

  • I believe you need to require jquery_ujs in application.js //= require jquery_ujs – Rafal May 06 '17 at 00:01
  • @Rafal jquery_ujs is already required! –  May 08 '17 at 13:58
  • ok, and do you have <%= csrf_meta_tags %> tag in your application.rb ? – Rafal May 08 '17 at 18:51
  • @Rafal yes i do! It seems its a problem with the Devise controllers only –  May 08 '17 at 18:53
  • ok then you need to change it to protect_from_forgery with: :null_session – Rafal May 08 '17 at 18:56
  • See this answer for reference http://stackoverflow.com/questions/20875591/actioncontrollerinvalidauthenticitytoken-in-registrationscontrollercreate – Rafal May 08 '17 at 18:57
  • @Rafal thanks for the link, basically all that change does is not show the exception anymore but the error still exists –  May 08 '17 at 19:02
  • So try moving the protect_from_forgery before your around_filter, it might solve it based on the answers from the other question – Rafal May 08 '17 at 19:05
  • 1
    @Rafal that fixed it...thank you very much –  May 08 '17 at 19:06

1 Answers1

4

This page has good info on the problem, but I was weirdly able to fix this in Rails 5 by putting protect_from_forgery above the around_action/filter. Hope it helps!

jeremy6d
  • 108
  • 1
  • 7
  • This saved me almost 3.5 years later. I had a before_action setting context for Sentry. I had it above the protect_from_forgery call...which was causing InvalidAuthenticityToken errors just after log in. – hellion Sep 02 '20 at 04:50