问题描述
我使用 ActionCable 开发了一个 Ruby on Rails 5.1 应用程序.通过设计进行用户身份验证 适用于多个渠道.现在,我想添加不需要任何用户身份验证的第二种渠道.更准确地说,我想让匿名网站访问者与支持人员聊天.
I develop a Ruby on Rails 5.1 application using ActionCable. User authentification via Devise works fine for several channels. Now, I want to add a second type of channels which does not require any user authentification. More precisely, I would like to enable anonymous website visitors to chat with support staff.
我当前为经过身份验证的用户实现的 ApplicationCable::Connection
如下所示:
My current implementation of ApplicationCable::Connection
for authenticated users looks like this:
# 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
).
Anonymous users will be identified by some random UUID (SecureRandom.urlsafe_base64
).
问题:
如何最好地添加这种新型频道?我可以在某处添加一个布尔标志 require_authentification
,在我继承的通道类中覆盖它以进行匿名通信,并根据这个属性在 Connection
中切换识别方法吗?或者我更愿意实现一个全新的模块,比如 AnonymousApplicationCable
?
How do I best add this new type of channels? Could I add a boolean flag require_authentification
somewhere, override it in my inherited channel class for anonymous communication, and switch the identification method in Connection
depending on this attribute? Or would I rather have to implement a completely new module, say AnonymousApplicationCable
?
推荐答案
我遇到了同样的问题,在 rails github 评论中查看了您的解决方案后,我认为最好创建令牌并将逻辑保留在连接方法.
Hi I came into the same problem, after looking at your solution in rails github comment, I assume it is better to create the token and keep the logic in the connect method.
所以我所做的只是利用监狱长检查,如果它为零,则创建匿名令牌,否则.为此,我需要声明 2 个标识符 :uuid 和 :current_user
So what I do was just utillize the the warden checking and if it is nil just create the anonymous token and otherwise. For this to work, I need to declare 2 identifier :uuid and :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
这篇关于使用具有多种识别方法的 ActionCable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!