我试图让Action Cable与Devise合作。
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.name
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
如果用户已登录,我仍然可以从nil
cookies.signed['user.id']
答案 0 :(得分:14)
使用以下内容更新connection.rb
:
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.studentid
end
protected
def find_verified_user # this checks whether a user is authenticated with devise
if verified_user = env['warden'].user
verified_user
else
reject_unauthorized_connection
end
end
end
end
答案 1 :(得分:5)
尝试在warden回调中设置cookie。
将文件添加到`config / initializers / your_file.rb``
将其添加到文件中:
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
或者你可以这样做:
verified_user = env['warden'].user
正如在这个非常好的课堂中所解释的那样:https://www.sitepoint.com/create-a-chat-app-with-rails-5-actioncable-and-devise/