我使用 ActionCable 开发 Ruby on Rails 5.1 应用程序。通过 Devise 进行用户身份验证 https://rubytutorial.io/actioncable-devise-authentication/适用于多个频道。现在,我想添加一个第二类渠道不需要任何用户身份验证。更准确地说,我希望匿名网站访问者能够与支持人员聊天。
我目前的实施ApplicationCable::Connection
对于经过身份验证的用户,如下所示:
# app/channels/application_cable/connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
end
protected
def find_verified_user
user = User.find_by(id: cookies.signed['user.id'])
return user if user
fail 'User needs to be authenticated.'
end
end
end
匿名用户将通过一些随机的 UUID 来识别(SecureRandom.urlsafe_base64 https://ruby-doc.org/stdlib-2.2.3/libdoc/securerandom/rdoc/SecureRandom.html#method-c-urlsafe_base64).
问题:
如何最好地添加这种新型渠道?我可以添加一个布尔标志吗require_authentification
某处,在我继承的通道类中重写它以进行匿名通信,并切换识别方法Connection
取决于这个属性?或者我宁愿必须实现一个全新的模块,比如说AnonymousApplicationCable
?
您好,我遇到了同样的问题,在查看 Rails github 评论中的解决方案后,我认为最好创建令牌并将逻辑保留在 connect 方法中。
所以我所做的只是利用典狱长检查,如果为零,则创建匿名令牌,否则。为此,我需要声明 2 个标识符:uuid 和:current_user
class Connection < ActionCable::Connection::Base
identified_by :current_user, :uuid
def connect
if !env['warden'].user
self.uuid = SecureRandom.urlsafe_base64
else
self.current_user = find_verified_user
end
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)