我按照本指南使用Websocket创建聊天功能。
https://www.sitepoint.com/rails-and-actioncable-adding-advanced-features/
我陷入了一个问题,即使我使用标准Devise表单登录到应用程序后,env['warden'].user
也无法调整任何内容。
如果我使用另一种方法(现在对此进行评论)-它返回错误的用户
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
verified_user = env['warden'].user
if verified_user
verified_user
else
reject_unauthorized_connection
end
end
# def find_verified_user
# user_id = request.headers['HTTP_AUTHORIZATION']
# if verified_user = User.find_by(user_id)
# verified_user
# else
# reject_unauthorized_connection
# end
# end
end
end
日志说
Started GET "/cable/" [WebSocket] for 127.0.0.1 at 2017-04-06 17:40:17 +0300
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
An unauthorized connection attempt was rejected
Failed to upgrade to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
最佳答案
我遇到了同样的问题,但事实证明我的问题是因为我有两个Devise模型:User
和Customer
,因为User用于管理人员,所以Customer设置为Warden的default_scope
。因此,要访问user
范围,我必须执行以下操作
env['warden'].user(:user)
末尾的符号定义了使用范围。
在这里,我找到了有关Warden范围内用户的信息:https://github.com/wardencommunity/warden/wiki/Scopes#scoped-user-access
关于ruby-on-rails - env ['warden']不适用于Rails 5,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43258458/