防止 actioncable 订阅者向他们不属于 Rails 的聊天室提交消息

preventing actioncable subscribers from submitting messages to chatrooms that they are not a part of in Rails

如果我的应用程序使用 AJAX 将用户的 message 提交到不需要控制器的服务器端 speak 方法(因此没有 space写一个 before_filter),我将如何实现限制不属于 conversationusers 通过浏览器控制台提交消息的行为?

如果我打开我的应用程序并输入 App.messages.speak("hi", #guess random number#) 该消息将提交到对话中,无论他们是否参与其中。

messages_channel.rb

class MessagesChannel < ApplicationCable::Channel
 def speak(data)
  Message.create! body: data['body'], conversation_id: data['conversation_id'], user_id: current_user.id
 end
end

messages.coffee

App.messages = App.cable.subscriptions.create "MessagesChannel", 
 speak: (body, conversation_id) ->
  @perform 'speak', body: body, conversation_id: conversation_id

 submit_message = () ->
 $('#response').on 'keydown', (event) ->
  if event.keyCode is 13
    conversation_id = $("[data-conversation-id]").data("conversation-id")
    App.messages.speak(event.target.value, conversation_id)
    event.target.value = ""
    event.preventDefault()

我想我可以从 speak 方法中删除 conversation_id 参数并将其设置在不依赖于用户输入的其他地方吗?目前我将它设置为数据属性,这意味着人们仍然可以弄乱它。

通过回调解决了。

class Message < ApplicationRecord
 before_create :exclude_non_participants

 def exclude_non_participants
  if conversation.participates?(user)
   true
  else
   throw :abort
  end
 end
end

participates?(user) 在这种情况下是:

class Conversation < ApplicationRecord
 def participates?(user)
 sender == user || receiver == user
 end
end

如果有更好的方法,请告诉我。目前,我认为这可行吗?