【问题标题】:How to use Pundit with Actioncable (Rails 5)如何将 Pundit 与 Actioncable 一起使用(Rails 5)
【发布时间】:2017-05-23 19:25:50
【问题描述】:

我想知道如何限制到通道的连接或通过 rails5 中的通道传输消息。目前,我与使用权威人士的组中的用户分组,并且与 websocket 的连接发生在该组中。如果恶意用户随机猜测组,他们可能会通过套接字读取他们不应该读取的消息。

当您创建一条新消息时,以下代码将在我的控制器中运行:

if message.save
  ActionCable.server.broadcast "messages_#{message.groupchat_id}_channel",
    message: message.content,
    user: message.user.email
  head :ok
end

我不知道自己在做什么。

【问题讨论】:

  • 我认为任何人都不能直接通过套接字读取数据,否则 actioncable 将是一场灾难。

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


【解决方案1】:

这是我发现的将 Pundit 与 Activecable 结合使用的解决方案。

首先我们需要访问用户模型。您可以按照Action Cable Overview - Connection Setup 中的说明进行操作。主要是需要修改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

注意:您可能需要使用不同的方式来查找您的用户。我正在使用 devise_token_auth,因此需要将 uid、token 和 client_id 传递给 connection.rb,然后通过以下代码获取用户:

if user && user.valid_token?(token, client_id)
  user
else
  reject_unauthorized_connection
end

我提到这一点只是因为您获取用户的方式可能会有所不同。主要是你需要使用identified_by current_user 并设置它。

我没有立即在文档中找到的另一件事是,您的频道现在可以访问 current_user。由于用户名可能与您的 pundit_user 名不同,我发现此时手动将用户传递给 Pundit 最容易。所以在订阅我的频道文件时,我有这个代码:

  def subscribed
    message = MessagePolicy::Scope.new(self.current_user, Project).resolve.find(params[:message])
    stream_for message
  end

您当然也可以通过这种方式手动授权,而不是使用 Scope:

MessagePolicy.new(self.current_user, message).show?

【讨论】:

    【解决方案2】:

    您可以在 app/channels/application_cable/connection.rb 文件中为可操作连接添加另一层安全性。

    您可以按照本教程进行操作。我认为这给了你一些想法: https://www.learnenough.com/action-cable-tutorial#sec-login_protection

    【讨论】:

    • 专门寻找权威人士的解决方案。感谢您的努力,今晚我一定会读一读。
    猜你喜欢
    • 1970-01-01
    • 2017-04-02
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    相关资源
    最近更新 更多