我正在建造一个带有公寓宝石的SaaS平台,并正在为聊天功能引入ActionCable。我已经构建了大部分聊天功能,但在传输到频道时,我得到以下内容:
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 1], ["LIMIT", 1]]
An unauthorized connection attempt was rejected
Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
Finished "/cable/" [WebSocket] for 127.0.0.1 at 2017-02-01 08:49:53 -0600
Finished "/cable/" [WebSocket] for 127.0.0.1 at 2017-02-01 08:49:53 -0600
我在app / channels / connection.rb
中使用此代码module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
tenant = request.subdomain
Apartment::Tenant.switch!(tenant)
logger.add_tags "ActionCable", "User #{current_user.id}", "Tenant #{tenant}"
end
protected
def find_verified_user
if current_user = env['warden'].user
current_user
else
reject_unauthorized_connection
end
end
end
end
理论上应该切换租户并在正确的子域上进行Actioncable传输。但我仍然遇到这些错误。
我也使用Devise并以用户身份登录,因此没有理由我能够想到为什么连接被拒绝,因为它正在查找当前用户并验证用户是基于监护人ENV的登录设备用户。
我想知道,因为我应该以某种方式配置请求来源,因为我有子域名。
为了测试这个,我硬编码了我在lvh.me localhost域上使用的一个子域:
Rails.application.config.action_cable.allowed_request_origins = ['http://acme.lvh.me:3000']
我想知道allowed_request_origins是否与此有关,如果是这样,我如何使用正则表达式允许任何子域到lvh.me:3000 url / domainspace?
非常感谢帮助。
答案 0 :(得分:0)
在朋友的帮助下,我们了解到我们需要在建立连接之前切换租户。这是connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
tenant = request.subdomain
Apartment::Tenant.switch!(tenant)
self.current_user = find_verified_user
logger.add_tags "ActionCable", "User #{current_user.id}", "Tenant #{tenant}"
end
protected
def find_verified_user
if current_user = env['warden'].user
current_user
else
reject_unauthorized_connection
end
end
end
end
要处理development.rb中的正则表达式部分来处理请求来源,我这样做了:
Rails.application.config.action_cable.allowed_request_origins = ['http:\/\/*.lvh.me:3000*']
到目前为止,它正在工作,AC正在与子域上的公寓正常传输。至少在开发中。