将ActionCable与多种识别方法一起使用

时间:2017-10-11 13:17:04

标签: ruby-on-rails ruby websocket ruby-on-rails-5 actioncable

我使用ActionCable开发Ruby on Rails 5.1应用程序。 User authentification via 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

匿名用户将通过一些随机UUID(SecureRandom.urlsafe_base64)来识别。

问题:

如何最好地添加这种新类型的频道?我可以在某处添加一个布尔标志require_authentification,在我继承的通道类中覆盖它以进行匿名通信,并根据此属性在Connection中切换标识方法吗?或者我宁愿实施一个全新的模块,比如AnonymousApplicationCable

1 个答案:

答案 0 :(得分:1)

您好我遇到了同样的问题,在查看了rails github注释中的解决方案之后,我认为最好创建令牌并将逻辑保留在connect方法中。

所以我所做的只是使用warden检查,如果它是nil只是创建匿名令牌,否则。为此,我需要声明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