lynndylanhurley / devise_token_auth

Token based authentication for Rails JSON APIs. Designed to work with jToker and ng-token-auth.
Do What The F*ck You Want To Public License
3.52k stars 1.14k forks source link

Your application has sessions disabled. To write to the session you must first configure a session store #1616

Closed Hammam94 closed 3 weeks ago

Hammam94 commented 6 months ago

got this error Your application has sessions disabled. To write to the session you must first configure a session store while upgrading rails from 6.1 to 7.0.1 i am using api_only = true as i don't need to configure session_store my environment rails 7.0.1 ruby 3.2 devise_token_auth 1.2.2 devise 4.9.3

b-turchyn commented 3 weeks ago

I did some spelunking through the Devise code. I think what's going on is

My approach to solving this was to monkeypatch Devise's bypass_sign_in method to use warden.set_user with store: false, rather than writing to the Warden session store. I'm doing this because I will only be using this for token auth. I'm also often an idiot who has no idea what they're doing, so this could very well be a horrible idea that I will regret in a week. I hope to remember to update this here if that ends up being the case.

I took Ayush Newatia's post on monkeypatching Rails as heavy inspiration for my solution (most notably: using #prepend rather than #include, since the latter didn't work for me)

lib/core_extensions/sign_in_out.rb:

module CoreExtensions
  module SignInOut
    # This is the same as the one implemented in devise except it skips the session store
    def bypass_sign_in(resource, scope: nil)
      scope ||= Devise::Mapping.find_scope!(resource)
      expire_data_after_sign_in!
      warden.set_user(resource, {store: false}.merge!(scope: scope))
    end
  end
end

config/initializers/core_extensions.rb:

# Credit: https://binarysolo.blog/applying-monkey-patches-in-rails/
# Require all Ruby files in the core_extensions directory
Dir[Rails.root.join('lib', 'core_extensions', '*.rb')].each { |f| require f }

# Apply the monkey patches
Devise::Controllers::SignInOut.prepend CoreExtensions::SignInOut
Hammam94 commented 3 weeks ago

Thanks a lot this fixed the issue