gpt4 book ai didi

ruby-on-rails - rails Action 电缆 : How to authorize incoming connection?

转载 作者:行者123 更新时间:2023-12-04 03:41:40 25 4
gpt4 key购买 nike

我正在尝试在 websocket 连接上实现授权(rails 5.2.1)

按照 rubyonrails guideline ,我创建了connection.rb如下:

# 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

private
def find_verified_user
if verified_user = User.find_by(id: cookies.encrypted[:user_id])
verified_user
else
reject_unauthorized_connection
end
end
end
end

很遗憾,所有的 websocket 连接请求都被拒绝了。 (我发现 cookies.encrypted[:user_id] 返回 nil。)

Started GET "/cable" for ::1 at 2018-10-07 21:33:46 +0300
Started GET "/cable/" [WebSocket] for ::1 at 2018-10-07 21:33:46 +0300
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."is_active" = $1 AND "users"."id" IS NULL LIMIT $2 [["is_active", true], ["LIMIT", 1]]
↳ app/channels/application_cable/connection.rb:12
An unauthorized connection attempt was rejected
Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
Finished "/cable/" [WebSocket] for ::1 at 2018-10-07 21:33:46 +0300
Finished "/cable/" [WebSocket] for ::1 at 2018-10-07 21:33:46 +0300

请指导我如何访问 app/channels/application_cable/connection.rb 中的当前用户信息?

最佳答案

为了从 Devise 获取 current_user,您需要更改您的 connection.rb,如下所示:

module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user

def connect
self.current_user = find_verified_user
logger.add_tags 'ActionCable', current_user.email
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
end

关于ruby-on-rails - rails Action 电缆 : How to authorize incoming connection?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52691711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com