env['warden'] not working with Rails 5
I had the same problem, but it turned out my issue was because I had two Devise models: User
and Customer
, since User was used for admin stuff, Customer was set to Warden's default_scope
. So to access the user
scope, I had to do the following
env['warden'].user(:user)
The symbol at the end defines the scope to use.
Here's where I found information on Warden's Scoped Users: https://github.com/wardencommunity/warden/wiki/Scopes#scoped-user-access
I found solution on this article https://rubytutorial.io/actioncable-devise-authentication/
Im not sure how it works, but it does the deal. How it would help for people with similar problem.
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
logger.add_tags 'ActionCable', current_user.email
end
protected
def find_verified_user
verified_user = User.find_by(id: cookies.signed['user.id'])
if verified_user && cookies.signed['user.expires_at'] > Time.now
verified_user
else
reject_unauthorized_connection
end
end
end
end
And I also created /config/initializers/warden_hooks.rb file
Warden::Manager.after_set_user do |user,auth,opts|
scope = opts[:scope]
auth.cookies.signed["#{scope}.id"] = user.id
auth.cookies.signed["#{scope}.expires_at"] = 60.minutes.from_now
end
Warden::Manager.before_logout do |user, auth, opts|
scope = opts[:scope]
auth.cookies.signed["#{scope}.id"] = nil
auth.cookies.signed["#{scope}.expires_at"] = nil
end