Bor*_*ris 5 ruby ruby-on-rails websocket ruby-on-rails-5 actioncable
我使用ActionCable开发了Ruby on Rails 5.1应用程序。通过Devise进行用户身份验证可在多个渠道上正常使用。现在,我想添加第二种类型的通道,不需要任何用户身份验证。更准确地说,我希望匿名网站访问者能够与支持人员聊天。
我当前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
Run Code Online (Sandbox Code Playgroud)
匿名用户将通过一些随机UUID(SecureRandom.urlsafe_base64)进行标识。
题:
如何最好地添加这种新型渠道?我可以在require_authentification某处添加一个布尔标志,在继承的通道类中重写它以进行匿名通信,并Connection根据此属性切换标识方法吗?还是我不得不实施一个全新的模块AnonymousApplicationCable?
小智 6
嗨,我遇到了同样的问题,在 rails github 评论中查看了您的解决方案后,我认为最好创建令牌并将逻辑保留在连接方法中。
所以我所做的只是利用监狱长检查,如果它为零,则创建匿名令牌,否则。为此,我需要声明 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1077 次 |
| 最近记录: |