devise - ActionCable 中的多个连接

标签 devise ruby-on-rails-5 actioncable

我的应用程序中有两个设计身份验证模型,并且想要在它们之间创建聊天。有人可以帮我为用户编写连接吗?以下是我所拥有的。我想检查是否可以让两个连接根据不同用户的个人登录拒绝其连接。如有任何帮助,我们将不胜感激。

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

最佳答案

稍微改编自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

关于devise - ActionCable 中的多个连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41672673/

相关文章:

ruby-on-rails - 我应该将 Rails 5.1 的中间件文件放在哪里?

javascript - Rails ActionCable/Turbolinks 聊天问题 : posting duplicate messages

ruby-on-rails - Rails and Devise - 访问 session 数据

c# - 使用 BCrypt.Net 模拟设计密码加密?

ruby-on-rails - 在 Rails 路由中定义 url 助手

ruby-on-rails - 将 MomentJS 格式化为 Rails DateTime

ruby-on-rails - 如何关闭Action电缆中的连接?

ruby-on-rails - ActionCable:从前端手动关闭连接

ruby-on-rails - 设计路线助手在测试期间不再为人所知

ruby-on-rails - 设计登录失败消息