ActionCable 中的多个连接
Posted
技术标签:
【中文标题】ActionCable 中的多个连接【英文标题】:Multiple connections in ActionCable 【发布时间】:2017-05-31 01:44:00 【问题描述】:我的应用中有两个设计身份验证模型,并希望在它们之间创建一个聊天。有人可以帮我为用户编写连接吗?下面是我所拥有的。我想检查我是否可以让两个连接根据他们的个人登录拒绝不同用户的连接。任何帮助表示赞赏。
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
identified_by :current_supplier
def connect
self.current_user = find_verified_user
self.current_supplier = find_verified_supplier
end
private
def find_verified_user
if current_user = env['warden'].user('user')
current_user
end
end
def find_verified_supplier
if current_supplier = env['warden'].user('supplier')
current_supplier
else
reject_unauthorized_connection
end
end
end
end
【问题讨论】:
【参考方案1】:改编自this tutorial:
# app/channels/application_cable/connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_supplier, :current_user
def connect
find_verified
end
protected
def find_verified
setup_user if verified_user
setup_supplier if verified_supplier
reject_unauthorized_connection unless [current_supplier, current_user].any?
end
def verified_user
cookies.signed['user.expires_at'].present? &&
cookies.signed['user.expires_at'] > Time.zone.now
end
def verified_supplier
cookies.signed['supplier.expires_at'].present? &&
cookies.signed['supplier.expires_at'] > Time.zone.now
end
def setup_supplier
self.current_supplier = Supplier.find_by(id: cookies.signed['supplier.id'])
logger.add_tags 'ActionCable', "#current_supplier.model_name.name #current_supplier.id"
end
def setup_user
self.current_user = User.find_by(id: cookies.signed['user.id'])
logger.add_tags 'ActionCable', "#current_user.model_name.name #current_user.id"
end
end
end
还有:
# config/initializers/warden_hooks.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"] = 30.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
【讨论】:
以上是关于ActionCable 中的多个连接的主要内容,如果未能解决你的问题,请参考以下文章
ActionCable 不尊重 production.rb 中的端口分配
ActionCable:检测客户端连接丢失,向用户显示连接状态